98 lines
2.5 KiB
Go
98 lines
2.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"net/http"
|
|
"studia/internal/logger"
|
|
"studia/internal/user"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type LoginRequest struct {
|
|
Email string
|
|
Password string
|
|
}
|
|
|
|
type RegisterRequest struct {
|
|
Email string
|
|
Password string
|
|
Username string
|
|
}
|
|
|
|
const defaultRole = "user"
|
|
|
|
var secret = []byte("secret")
|
|
|
|
func Login(c *gin.Context, db *sql.DB) error {
|
|
var req LoginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
|
return err
|
|
}
|
|
|
|
if req.Email == "" || req.Password == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
|
|
return errors.New("Email and password are required")
|
|
}
|
|
|
|
User, err := user.GetUserByEmail(db, req.Email)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email "})
|
|
return err
|
|
}
|
|
logger.Log.Info().Msgf("User: %+v", User)
|
|
|
|
err = user.CheckPasswordHash(db, User.Email, req.Password)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
token, err := GenerateJWT(User.ID, User.Email, User.Role)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
|
|
return err
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"token": token})
|
|
return nil
|
|
}
|
|
|
|
func Register(c *gin.Context, db *sql.DB) error {
|
|
var req RegisterRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
// Log the error for debugging purposes
|
|
logger.Log.Error().Err(err).Msg("Failed to bind JSON for registration")
|
|
// Respond with a bad request status and an error message
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
|
return errors.New("Invalid request")
|
|
}
|
|
logger.Log.Info().Msgf("Register Request: %+v", req)
|
|
if req.Email == "" || req.Password == "" || req.Username == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
|
|
return errors.New("Email and password are required")
|
|
}
|
|
|
|
err := user.CreateUser(db, req.Email, req.Username, req.Password, []string{defaultRole})
|
|
if err != nil {
|
|
logger.Log.Error().Err(err).Msg("Failed to create user")
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
|
return err
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"message": "User created successfully"})
|
|
|
|
return nil
|
|
}
|
|
|
|
func GenerateJWT(uuid string, email string, roles []string) (any, error) {
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
"user": uuid,
|
|
"email": email,
|
|
"role": roles,
|
|
"exp": time.Now().Add(24 * time.Hour).Unix(),
|
|
})
|
|
return token.SignedString(secret)
|
|
}
|