Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func (s *Server) createUserHandler(w http.ResponseWriter, r *http.Request) http.Handler {
- usernameRegex := regex.MustCompile(`^[0-9A-Za-z\s]+$`)
- const minUsernameLength = 3
- const maxUsernameLength = 20
- const minPasswordLength = 8
- const maxPasswordLength = 64
- var (
- shortUsername = ResponseError{fmt.Sprintf("Username must be equal to or more than %d characters.", minUsernameLength), 0},
- longUsername = ResponseError{fmt.Sprintf("Username must be equal to or less than %d characters.", maxUsernameLength), 1},
- shortPassword = ResponseError{fmt.Sprintf("Username must be equal to or more than %d characters.", minPasswordLength), 2},
- longPassword = ResponseError{fmt.Sprintf("Username must be equal to or less than %d characters.", maxPasswordLength), 3},
- notAlphanumericUsername = ResponseError{"Usernames must be alphanumeric.", 4},
- )
- type requestUser struct {
- Username string `json:"username"`
- Password string `json:"password"`
- IsAdmin bool `json:"isAdmin"`
- }
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var reqUser requestUser
- if err := json.NewDecoder(r).Decode(&reqUser); err != nil {
- http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError))
- return
- }
- if len(reqUser.Username) < minUsernameLength {
- respond.JSON(w, nil, shortUsername)
- return
- } else if len(reqUser.Username) > maxUsernameLength {
- respond.JSON(w, nil, longUsername)
- return
- }
- if len(reqUser.Password) < minPasswordLength {
- respond.JSON(w, nil, shortPassword)
- return
- } else if len(reqUser.Password) > maxPasswordLength {
- respond.JSON(w, nil, longPassword)
- return
- }
- if !usernameRegex.Match([]byte(reqUser.Username)) {
- respond.JSON(w, nil, notAlphanumericUsername)
- return
- }
- hashedPassword, err := bcrypt.GenerateFromPassword([]byte(reqUser.Password), bcrypt.DefaultCost)
- if err != nil {
- s.logger.LogRequestError(r, fmt.Errorf("generating bcrypt hash from password: %v", err))
- http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
- return
- }
- user := user.User{Username: reqUser.Username, HashedPassword: string(hashedPassword), IsAdmin: reqUser.IsAdmin, IsVerified: s.getIsAdmin(r)}
- if err := s.store.User.Create(user); err != nil {
- s.logger.LogRequestError(r, fmt.Errorf("creating user: %v", err))
- http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
- return
- }
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement