Added login and logout

This commit is contained in:
Nedim
2023-11-06 11:22:51 +01:00
parent e47336dc8d
commit 367b5d51f2
9 changed files with 359 additions and 11 deletions

View File

@@ -4,9 +4,11 @@ import (
"crypto/rand"
"encoding/base64"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"gitlab.com/pactual1/backend/database/user"
usr "gitlab.com/pactual1/backend/database/user"
"gitlab.com/pactual1/backend/models"
"gitlab.com/pactual1/backend/services/messaging"
"gitlab.com/pactual1/backend/shared"
@@ -111,3 +113,59 @@ func UpdatePassword(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Password updated successfully"})
}
func Login(c *gin.Context) {
var req models.User
if err := c.BindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request"})
return
}
user, err := usr.GetUserByEmail(req.Email)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}
if usr.CheckPassword(user.Password, req.Password) {
if user.IsActive && user.LoginAttempts < 10 {
// Proceed with creating JWT token and resetting login attempts
token, err := usr.CreateSessionToken(user.ID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create JWT token"})
return
}
usr.ResetLoginAttempts(*user)
c.JSON(http.StatusOK, gin.H{"token": token})
} else {
c.JSON(http.StatusForbidden, gin.H{"error": "Account locked or too many attempts"})
}
} else {
// Wrong password, increment login attempts
usr.IncrementLoginAttempts(*user)
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
}
}
func Logout(c *gin.Context) {
// Extract the token from the request, typically from the Authorization header
tokenString := c.GetHeader("Authorization")
// If using a Bearer token, strip the 'Bearer ' prefix
if len(tokenString) > 7 && strings.ToUpper(tokenString[0:7]) == "BEARER " {
tokenString = tokenString[7:]
}
// Invalidate the session token
err := usr.InvalidateSessionToken(tokenString)
if err != nil {
// Handle error, could be not found or database error
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to logout"})
return
}
// Respond with success
c.JSON(http.StatusOK, gin.H{"message": "Successfully logged out"})
}