| func HashPassword(password string) (string, error) { | |
| bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) | |
| return string(bytes), err | |
| } | |
| func CheckPasswordHash(password, hash string) bool { | |
| err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) | |
| return err == nil | |
| } | |
| // How I'm creating accounts | |
| func CreateNewUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) { | |
| body, err := ioutil.ReadAll(r.Body) | |
| if err != nil { | |
| respondError(w, http.StatusInternalServerError, "Couldn't read json body") | |
| return | |
| } | |
| var NewUser models.User | |
| err = json.Unmarshal(body, &NewUser) | |
| if err != nil { | |
| respondError(w, http.StatusInternalServerError, "Couldn't read json body") | |
| return | |
| } | |
| HashedPassword, err := utils.HashPassword(NewUser.Pass) | |
| NewUser.Pass = HashedPassword | |
| if err != nil { | |
| respondError(w, http.StatusInternalServerError, "Couldn't read json body") | |
| return | |
| } | |
| err = db.Create(&NewUser).Error | |
| if err != nil && strings.Contains(err.Error(), "1062") { | |
| errorMessage := fmt.Sprintf("User with email: %s already exists", NewUser.Email) | |
| respondError(w, http.StatusInternalServerError, errorMessage) | |
| return | |
| } else if err != nil { | |
| respondError(w, http.StatusInternalServerError, "Couldn't create new user account") | |
| return | |
| } | |
| PublicUserDetails := NewUser.GetPublicUser() | |
| tokenString, err := utils.CreateNewJWTToken(PublicUserDetails) | |
| if err != nil { | |
| respondError(w, http.StatusInternalServerError, "Account created but couldn't create JWT") | |
| return | |
| } | |
| respondJSON(w, http.StatusOK, utils.JWTResponse{Token: tokenString}) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment