initial commit
This commit is contained in:
60
backend/internal/auth/handler.go
Normal file
60
backend/internal/auth/handler.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"studia/internal/user"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
var secret = []byte("secret")
|
||||
|
||||
func LoginHandler(c *gin.Context, db *sql.DB) {
|
||||
var req LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Email == "" || req.Password == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
|
||||
return
|
||||
}
|
||||
|
||||
User, err := user.GetUserByEmail(db, req.Email)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
|
||||
return
|
||||
}
|
||||
|
||||
if !user.CheckPasswordHash(db, User.Email, req.Password) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
|
||||
return
|
||||
}
|
||||
|
||||
token, err := GenerateJWT(User.ID, User.Email, User.Role)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"token": token})
|
||||
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
1
backend/internal/auth/middleware.go
Normal file
1
backend/internal/auth/middleware.go
Normal file
@@ -0,0 +1 @@
|
||||
package auth
|
||||
Reference in New Issue
Block a user