80 lines
2.0 KiB
Go
Raw Normal View History

2023-10-08 15:59:42 +07:00
package auth
import (
"furtuna-be/internal/constants/role"
"net/http"
"github.com/gin-gonic/gin"
"furtuna-be/internal/common/errors"
auth2 "furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
)
type AuthHandler struct {
service services.Auth
}
func (a *AuthHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
authRoute := group.Group("/auth")
authRoute.POST("/login", a.AuthLogin)
}
func NewAuthHandler(service services.Auth) *AuthHandler {
return &AuthHandler{
service: service,
}
}
// AuthLogin handles the authentication process for user login.
// @Summary User login
// @Description Authenticates a user based on the provided credentials and returns a JWT token.
// @Accept json
// @Produce json
// @Param bodyParam body auth2.LoginRequest true "User login credentials"
// @Success 200 {object} response.BaseResponse{data=response.LoginResponse} "Login successful"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/auth/login [post]
// @Tags Auth Login API's
func (h *AuthHandler) AuthLogin(c *gin.Context) {
var bodyParam auth2.LoginRequest
if err := c.ShouldBindJSON(&bodyParam); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
authUser, err := h.service.AuthenticateUser(c, bodyParam.Email, bodyParam.Password)
if err != nil {
response.ErrorWrapper(c, err)
return
}
var branch *response.Branch
if authUser.RoleID != role.SuperAdmin {
branch = &response.Branch{
ID: authUser.BranchID,
Name: authUser.BranchName,
}
}
resp := response.LoginResponse{
Token: authUser.Token,
Branch: branch,
Name: authUser.Name,
Role: response.Role{
ID: int64(authUser.RoleID),
Role: authUser.RoleName,
},
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Message: "Login Success",
Data: resp,
})
}