Advertisement
Guest User

Untitled

a guest
Apr 4th, 2025
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 5.99 KB | Source Code | 0 0
  1. package controllers
  2.  
  3. import (
  4.     "fibber/models"
  5.     "fibber/utils"
  6.     "log"
  7.     "net/http"
  8.     "os"
  9.     "time"
  10.  
  11.     "github.com/gin-gonic/gin"
  12.     "github.com/go-playground/validator/v10"
  13.     "gorm.io/gorm"
  14. )
  15.  
  16. type AuthController interface {
  17.     Login(c *gin.Context)
  18.     Register(c *gin.Context)
  19.     Me(c *gin.Context)
  20.     Logout(c *gin.Context)
  21. }
  22.  
  23. type AuthControllerImpl struct{}
  24.  
  25. func NewAuthController() *AuthControllerImpl {
  26.     return &AuthControllerImpl{}
  27. }
  28.  
  29. type loginInput struct {
  30.     Email    string `validate:"required,email" json:"email"`
  31.     Password string `validate:"required" json:"password"`
  32. }
  33.  
  34. type registerInput struct {
  35.     Name          string `validate:"required,min=3,max=100" json:"name"`
  36.     Email         string `validate:"required,email" json:"email"`
  37.     Password      string `validate:"required,min=6,max=100" json:"password"`
  38.     LoginDirectly bool   `json:"login_directly"`
  39. }
  40.  
  41. func (a *AuthControllerImpl) Login(c *gin.Context) {
  42.     var body loginInput
  43.     if err := c.ShouldBindJSON(&body); err != nil {
  44.         c.JSON(http.StatusInternalServerError, gin.H{
  45.             "message": "Cannot bind request body",
  46.         })
  47.         return
  48.     }
  49.  
  50.     validate := validator.New()
  51.     if err := validate.Struct(body); err != nil {
  52.         log.Println("Validation error:", err)
  53.         c.JSON(http.StatusBadRequest, gin.H{
  54.             "message": "Invalid input data",
  55.             "errors":  err.Error(),
  56.         })
  57.         return
  58.     }
  59.     db := c.MustGet("db").(*gorm.DB)
  60.     var user models.User
  61.     result := db.Where("email = ?", body.Email).First(&user)
  62.     /* Checks if user exists */
  63.     if result.Error != nil {
  64.         log.Println("User not found:", body.Email)
  65.         c.JSON(http.StatusUnauthorized, gin.H{
  66.             "message": "User does not exist",
  67.         })
  68.         return
  69.     }
  70.  
  71.     /* Checks for password */
  72.     if !utils.VerifyPassword(body.Password, user.Password) {
  73.         log.Println("Invalid password for user:", body.Email)
  74.         c.JSON(http.StatusUnauthorized, gin.H{
  75.             "message": "Invalid credentials",
  76.         })
  77.         return
  78.     }
  79.  
  80.     tokenString, err := utils.CreateToken(user.ID, os.Getenv("JWT_SECRET"))
  81.     if err != nil {
  82.         log.Println("Error creating token:", err)
  83.         c.JSON(http.StatusInternalServerError, gin.H{
  84.             "message": "Internal server error",
  85.         })
  86.         return
  87.     }
  88.     exp := time.Now().Add(time.Hour * 24).Unix()
  89.     /* INFO: name of the cookie is "auth_gin" */
  90.     c.SetCookie("auth_gin", tokenString, int(exp), "/", "localhost", false, true)
  91.  
  92.     c.JSON(200, gin.H{
  93.         "message": "Login successful",
  94.     })
  95. }
  96.  
  97. func (a *AuthControllerImpl) Me(c *gin.Context) {
  98.     cookie, err := c.Cookie("auth_gin")
  99.     if err != nil {
  100.         c.JSON(http.StatusUnauthorized, gin.H{
  101.             "message": "Unauthorized",
  102.         })
  103.         return
  104.     }
  105.  
  106.     userId, err := utils.VerifyToken(cookie, os.Getenv("JWT_SECRET"))
  107.     if err != nil {
  108.         log.Println("Error verifying token:", err)
  109.         c.JSON(http.StatusUnauthorized, gin.H{
  110.             "message": "Unauthorized",
  111.         })
  112.         return
  113.     }
  114.  
  115.     db := c.MustGet("db").(*gorm.DB)
  116.     var user models.User
  117.     result := db.Model(&models.User{}).Where("id = ?", userId).First(&user)
  118.  
  119.     if result.Error != nil {
  120.         if result.Error == gorm.ErrRecordNotFound {
  121.             log.Default().Println("User not found:", userId)
  122.             c.JSON(http.StatusNotFound, gin.H{
  123.                 "message": "User not found",
  124.             })
  125.             return
  126.         }
  127.         c.JSON(http.StatusInternalServerError, gin.H{
  128.             "message": "Internal server error",
  129.         })
  130.         return
  131.     }
  132.  
  133.     c.JSON(http.StatusOK, gin.H{
  134.         "user_name":  user.Name,
  135.         "created_at": user.CreatedAt,
  136.     })
  137.     return
  138. }
  139.  
  140. func (a *AuthControllerImpl) Register(c *gin.Context) {
  141.     var body registerInput
  142.     if err := c.ShouldBindJSON(&body); err != nil {
  143.         c.JSON(http.StatusInternalServerError, gin.H{
  144.             "message": "Cannot bind request body",
  145.         })
  146.         return
  147.     }
  148.  
  149.     validate := validator.New()
  150.     if err := validate.Struct(body); err != nil {
  151.         log.Println("Validation error:", err)
  152.         c.JSON(http.StatusBadRequest, gin.H{
  153.             "message": "Invalid input data",
  154.             "errors":  err.Error(),
  155.         })
  156.         return
  157.     }
  158.  
  159.     db := c.MustGet("db").(*gorm.DB)
  160.     hashedPassword, err := utils.HashPassword(body.Password)
  161.     if err != nil {
  162.         log.Println("Error hashing password:", err)
  163.         c.JSON(http.StatusInternalServerError, gin.H{
  164.             "message": "Cannot hash password",
  165.             "errors":  err.Error(),
  166.         })
  167.         return
  168.     }
  169.  
  170.     newUser := models.User{
  171.         Name:     body.Name,
  172.         Email:    body.Email,
  173.         Password: hashedPassword,
  174.     }
  175.  
  176.     result := db.Create(&newUser)
  177.     if result.Error != nil {
  178.         log.Println("Error inserting into database:", result.Error)
  179.         c.JSON(http.StatusConflict, gin.H{
  180.             "message": "User with this email already exists",
  181.             "errors":  result.Error.Error(),
  182.         })
  183.         return
  184.     }
  185.  
  186.     if body.LoginDirectly {
  187.         tokenString, err := utils.CreateToken(newUser.ID, os.Getenv("JWT_SECRET"))
  188.         if err != nil {
  189.             log.Println("Error creating token:", err)
  190.             c.JSON(http.StatusInternalServerError, gin.H{
  191.                 "message": "Internal server error",
  192.             })
  193.             return
  194.         }
  195.         exp := time.Now().Add(time.Hour * 24).Unix()
  196.         /* INFO: name of the cookie is "auth_gin" */
  197.         c.SetCookie("auth_gin", tokenString, int(exp), "/", "localhost", false, true)
  198.  
  199.         c.JSON(http.StatusCreated, gin.H{
  200.             "message": "User created and logged in",
  201.             "data": map[string]any{
  202.                 "user_name":  newUser.Name,
  203.                 "created_at": newUser.CreatedAt,
  204.             },
  205.         })
  206.         return
  207.     }
  208.  
  209.     c.JSON(http.StatusCreated, gin.H{
  210.         "message": "User created",
  211.         "data": map[string]any{
  212.             "user_name":  newUser.Name,
  213.             "created_at": newUser.CreatedAt,
  214.         },
  215.     })
  216.     return
  217. }
  218.  
  219. func (a *AuthControllerImpl) Logout(c *gin.Context) {
  220.     cookie, err := c.Cookie("auth_gin")
  221.     if err != nil {
  222.         c.JSON(http.StatusUnauthorized, gin.H{
  223.             "message": "Unauthorized",
  224.         })
  225.         return
  226.     }
  227.  
  228.     if _, err := utils.VerifyToken(cookie, os.Getenv("JWT_SECRET")); err != nil {
  229.         log.Println("Error verifying token:", err)
  230.         c.JSON(http.StatusUnauthorized, gin.H{
  231.             "message": "Unauthorized",
  232.         })
  233.         return
  234.     }
  235.  
  236.     /* INFO: name of the cookie is "auth_gin" */
  237.     c.SetCookie("auth_gin", "", -1, "/", "localhost", false, true) // set cookie to expire immediately
  238.  
  239.     c.JSON(http.StatusOK, gin.H{
  240.         "message": "Logged out successfully!",
  241.     })
  242.     return
  243. }
  244.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement