// UserToken returns an HTTP handler to generate a token for a user. func UserToken(server *app.App) func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) { userTokenReq := &models.UserTokenRequest{} if err := binding.Bind(req, userTokenReq); err.Handle(w) { return } user, err := models.FindUserByEmail(server.DB, userTokenReq.Email) if err != nil { log.Println(err) server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "error getting user from database"}) return } if user.ID == "" { server.Render.JSON(w, http.StatusNotFound, map[string]string{"error": "invalid username or password"}) return } if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(userTokenReq.Password)); err != nil { server.Render.JSON(w, http.StatusNotFound, map[string]string{"error": "invalid username or password"}) return } token := jwt.New(jwt.GetSigningMethod("HS256")) token.Claims["id"] = user.ID tokenString, err := token.SignedString(server.JWTSecret) if err != nil { log.Println(err) server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "error signing token"}) return } server.Render.JSON(w, http.StatusCreated, map[string]string{"token": tokenString}) } }
// CreateUser is a http handler function to creation a new user. func CreateUser(server *app.App) func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) { userReq := &models.UserRequest{} if err := binding.Bind(req, userReq); err.Handle(w) { return } existing, err := models.FindUserByEmail(server.DB, userReq.Email) if err != nil { server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"}) log.Println(err) return } if existing.ID != "" { server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "user email must be unique across the application"}) return } user, err := models.NewUser(userReq.Email, []byte(userReq.Password)) if err != nil { server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"}) log.Println(err) return } if err := server.DB.Save(user); err != nil { server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"}) log.Println(err) return } user.Hash = "" server.Render.JSON(w, http.StatusCreated, user) } }