package user import ( "encoding/base64" "jannex/admin-dashboard-backend/modules/database" "jannex/admin-dashboard-backend/modules/logger" "jannex/admin-dashboard-backend/modules/structs" "jannex/admin-dashboard-backend/modules/utils" "jannex/admin-dashboard-backend/socketclients" "github.com/gofiber/fiber/v2" "github.com/rs/zerolog/log" "github.com/savsgio/gotils/uuid" "golang.org/x/crypto/bcrypt" ) func UserLogin(c *fiber.Ctx) error { // swagger:operation POST /user/auth/login user userLogin // --- // summary: Login user // consumes: // - application/json // produces: // - application/json // parameters: // - name: body // in: body // schema: // "$ref": "#/definitions/UserLoginRequest" // responses: // '200': // description: User logged in successfully // schema: // "$ref": "#/definitions/UserLoginResponse" // '400': // description: Invalid request body // '401': // description: Incorrect password or user deactivated // '500': // description: Failed to login user var body structs.UserLoginRequest if err := utils.BodyParserHelper(c, &body); err != nil { return c.SendStatus(fiber.StatusBadRequest) } decodedPassword, err := base64.StdEncoding.DecodeString(body.Password) if err != nil { log.Error().Msg("Failed to decode base64 password, err: " + err.Error()) return c.SendStatus(fiber.StatusBadRequest) } if passwordValid := utils.IsPasswordLengthValid(string(decodedPassword)); !passwordValid { return c.SendStatus(fiber.StatusBadRequest) } var user structs.User database.DB.First(&user, "username = ?", body.Username) if user.Id == "" { log.Error().Msg("User not found") return c.SendStatus(fiber.StatusBadRequest) } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), decodedPassword); err != nil { log.Error().Msg("Incorrect password") return c.SendStatus(fiber.StatusBadRequest) } if user.Deactivated { return c.SendStatus(fiber.StatusUnauthorized) } session, err := utils.GenerateSession() if err != nil { return c.SendStatus(fiber.StatusInternalServerError) } database.DB.Create(&structs.UserSession{ Id: session, IdForDeletion: uuid.V4(), UserId: user.Id, UserAgent: string(c.Context().UserAgent()), ExpiresAt: utils.GetSessionExpiresAtTime()}) logger.AddSystemLog("User %s has logged in", user.Id) return c.JSON(structs.UserLoginResponse{Session: session}) } func UserLogout(c *fiber.Ctx) error { // swagger:operation DELETE /user/auth/logout user userLogout // --- // summary: Logout user // consumes: // - application/json // produces: // - application/json // parameters: // - name: X-Authorization // in: header // description: User session id // responses: // '201': // description: User logged out successfully // '500': // description: Failed to logout user session := utils.GetXAuhorizationHeader(c) database.DB.Delete(&structs.UserSession{}, "id = ?", session) socketclients.CloseAllUserSessionConnections(session) logger.AddSystemLog("User %s has logged out", c.Locals("userId").(string)) return c.SendStatus(fiber.StatusCreated) }