recreate migration create table users; with unique constrains

This commit is contained in:
valitovgaziz
2024-08-19 21:42:02 +05:00
parent 4b7af37296
commit 568d09d0a2
5 changed files with 22 additions and 23 deletions
+3 -2
View File
@@ -4,7 +4,7 @@ import (
"github.com/golang-jwt/jwt/v4"
)
type Crenetials struct {
type Credentials struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
@@ -14,4 +14,5 @@ type Crenetials struct {
type Claims struct {
jwt.RegisteredClaims
Email string `json:"email"`
}
Phone string `json:"phone"`
}
+6 -3
View File
@@ -15,14 +15,16 @@ import (
var jwtKey = []byte(os.Getenv("SECRET_KEY"))
func Login(w http.ResponseWriter, r *http.Request) {
var creds models.Crenetials
var creds models.Credentials
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// check user
var user models.User
if result := psql.PSQL_GORM_DB.Where("email = ?", creds.Email).First(&user); result.Error != nil || !checkPasswordHash(creds.Password, user.Password) {
// get user by email
result := psql.PSQL_GORM_DB.Where("email = ?", creds.Email).First(&user)
if result.Error != nil || !checkPasswordHash(creds.Password, user.Password) {
w.WriteHeader(http.StatusInternalServerError)
return
}
@@ -34,6 +36,7 @@ func Login(w http.ResponseWriter, r *http.Request) {
ExpiresAt: jwt.NewNumericDate(expirationtime),
},
Email: user.Email,
Phone: user.Phone,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
@@ -54,4 +57,4 @@ func Login(w http.ResponseWriter, r *http.Request) {
func checkPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
}
+6 -6
View File
@@ -12,15 +12,15 @@ import (
)
func Register(w http.ResponseWriter, r *http.Request) {
var Crenetials models.Crenetials
var Credentials models.Credentials
// Decoe body
if err := json.NewDecoder(r.Body).Decode(&Crenetials); err != nil {
if err := json.NewDecoder(r.Body).Decode(&Credentials); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// shep password
hashedPassword, err := hashPassword(Crenetials.Password)
hashedPassword, err := hashPassword(Credentials.Password)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
@@ -30,10 +30,10 @@ func Register(w http.ResponseWriter, r *http.Request) {
user := models.User{
Id: id,
Name: Crenetials.Name,
Email: Crenetials.Email,
Name: Credentials.Name,
Email: Credentials.Email,
Password: hashedPassword,
Phone: Crenetials.Phone,
Phone: Credentials.Phone,
}
if result := psql.PSQL_GORM_DB.Create(&user); result.Error != nil {
w.WriteHeader(http.StatusInternalServerError)