authentication.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package controller
  2. import (
  3. "kng_feed_api/helper"
  4. "kng_feed_api/model"
  5. "net/http"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func Register(context *gin.Context) {
  9. var input model.AuthenticationInput
  10. if err := context.ShouldBindJSON(&input); err != nil {
  11. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  12. return
  13. }
  14. user := model.User{
  15. Username: input.Username,
  16. Password: input.Password,
  17. }
  18. savedUser, err := user.Save()
  19. if err != nil {
  20. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  21. return
  22. }
  23. context.JSON(http.StatusCreated, gin.H{"user": savedUser})
  24. }
  25. func Login(context *gin.Context) {
  26. var input model.AuthenticationInput
  27. if err := context.ShouldBindJSON(&input); err != nil {
  28. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  29. return
  30. }
  31. user, err := model.FindUserByUsername(input.Username)
  32. if err != nil {
  33. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  34. return
  35. }
  36. err = user.ValidatePassword(input.Password)
  37. if err != nil {
  38. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  39. return
  40. }
  41. jwt, err := helper.GenerateJWT(user)
  42. if err != nil {
  43. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  44. return
  45. }
  46. context.JSON(http.StatusOK, gin.H{"jwt": jwt})
  47. }