func CreateUserHandler(w http.ResponseWriter, r *http.Request) { fields := CreateUserForm{} cef, err := form.Parse(&fields, w, r) if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } if cef.HasError() { cef.Error.Send(http.StatusBadRequest) return } hash, err := cryptoutils.Hash(fields.Password, conf.PasswordLevel) if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } user := model.User{ ID: bson.NewObjectId(), Name: fields.Name, Email: strings.TrimSpace(fields.Email), Hash: hash, CreatedAt: time.Now(), } s := conf.M.Copy() defer s.Close() if err := s.DB("").C("users").Insert(&user); err != nil { if mgo.IsDup(err) { cef.Error.SendMessage("this email address already exists", http.StatusBadRequest) return } log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } token := model.NewToken(user.ID) if err := s.DB("").C("tokens").Insert(&token); err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } user.AccessToken = token.Token httpres.Json(w, http.StatusCreated, UserResponse{user}) }
func CreateUserHandler(w http.ResponseWriter, r *http.Request) { fields := createUserForm{} if formutils.ParseSend(w, r, &fields) { return } hash, err := cryptoutils.Hash(fields.Password, conf.PasswordLevel) if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } user := model.User{ ID: bson.NewObjectId(), Name: fields.Name, Email: strings.TrimSpace(fields.Email), PasswordHash: hash, CreatedAt: time.Now(), } if err := ctx.M(r).DB("").C("users").Insert(&user); err != nil { if mgo.IsDup(err) { eres.New(w).AddField("email", "already exists").Send() return } log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } token := model.NewToken(user.ID, false) if err := ctx.M(r).DB("").C("tokens").Insert(&token); err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } rp := userResponse{ User: user, AccessToken: token.Token, } httpres.Json(w, http.StatusCreated, rp) }