implement JWT tokens, regenerate docs and sqlc

This commit is contained in:
zardzul
2026-03-14 18:46:48 +01:00
parent 131aee8638
commit d5e608feeb
18 changed files with 441 additions and 82 deletions
+67 -3
View File
@@ -2,7 +2,9 @@ package handlers
import (
"net/http"
"time"
db "zardzul/music-index/sqlc"
"zardzul/music-index/utils"
"zardzul/music-index/repository"
@@ -13,11 +15,19 @@ import (
)
type UserHandler struct {
repo repository.UserRepository
repo repository.UserRepository
jwtSecret string
jwtIssuer string
jwtTTL time.Duration
}
func NewUserHandler(repo repository.UserRepository) *UserHandler {
return &UserHandler{repo: repo}
func NewUserHandler(repo repository.UserRepository, jwtSecret string, jwtIssuer string, jwtTTL time.Duration) *UserHandler {
return &UserHandler{
repo: repo,
jwtSecret: jwtSecret,
jwtIssuer: jwtIssuer,
jwtTTL: jwtTTL,
}
}
type CreateUserRequest struct {
@@ -116,3 +126,57 @@ func (h *UserHandler) GetUsernameByID(c *gin.Context) {
"user_name": username,
})
}
type LoginRequest struct {
UserMail string `json:"user_mail" binding:"required,email"`
Password string `json:"password" binding:"required"`
}
type LoginResponse struct {
Token string `json:"token"`
}
// Login godoc
// @Summary Log in with email and password
// @Tags user
// @Accept json
// @Produce json
// @Param payload body LoginRequest true "Login payload"
// @Success 200 {object} LoginResponse
// @Failure 400 {object} ErrorResponse
// @Failure 401 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /users/login [post]
func (h *UserHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
return
}
user, err := h.repo.GetUserAuthByEmail(c.Request.Context(), req.UserMail)
if err != nil {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid credentials"})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
c.JSON(http.StatusUnauthorized, ErrorResponse{Error: "invalid credentials"})
return
}
token, err := utils.GenerateToken(
h.jwtSecret,
h.jwtIssuer,
user.ID.String(),
user.UserName,
user.UserMail,
h.jwtTTL,
)
if err != nil {
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "failed to create token"})
return
}
c.JSON(http.StatusOK, LoginResponse{Token: token})
}