Files
online-backend/internal/admin/auth/handler.go
GuwandykA 77bc4025d3 Add branch_user table and branch-user assignment endpoints
Introduces a branch_user join table linking branches to users, plus
create/delete API endpoints under the auth module for managing branch
assignments. The create response includes the branch's localized name
via a join. Regenerated swagger docs to include the new endpoints.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-08 15:02:05 +05:00

242 lines
6.6 KiB
Go
Executable File

package auth
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"online-back/pkg/utils"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
"golang.org/x/crypto/bcrypt"
)
const (
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
branchUserURL = "/branch-users"
)
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.refreshToken)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
branchUserGroup := router.Group(branchUserURL, appresult.JwtTokenCheck())
branchUserGroup.POST("", h.createBranchUser)
branchUserGroup.DELETE("/:id", h.deleteBranchUser)
}
// login godoc
// @Summary Login
// @Description Authenticates a user by email and password
// @Tags auth
// @Accept json
// @Produce json
// @Param body body LoginDTO true "Login payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /login [post]
func (h *handler) login(c *gin.Context) {
var dto LoginDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
user, err := h.repository.Login(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("login lookup failed: %v", err)
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(user.Id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// refreshToken godoc
// @Summary Refresh tokens
// @Description Issues a new access and refresh token pair
// @Tags auth
// @Accept json
// @Produce json
// @Param body body RefreshTokenDTO true "Refresh token payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /token [post]
func (h *handler) refreshToken(c *gin.Context) {
var dto RefreshTokenDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
claims, err := utils.ParseRefreshToken(dto.RefreshToken)
if err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
id, ok := utils.ClaimID(claims)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
user, err := h.repository.GetUserByID(c.Request.Context(), id)
if err != nil || user.Id != id {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile
// @Tags auth
// @Produce json
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [get]
func (h *handler) getProfile(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
profile, err := h.repository.GetProfile(c.Request.Context(), userID)
if err != nil {
h.logger.Errorf("get profile failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
// createBranchUser godoc
// @Summary Assign user to branch
// @Description Creates a branch-user assignment
// @Tags auth
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateBranchUserDTO true "Branch-user payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branch-users [post]
func (h *handler) createBranchUser(c *gin.Context) {
var dto CreateBranchUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.CreateBranchUser(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create branch user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// deleteBranchUser godoc
// @Summary Remove user from branch
// @Description Deletes a branch-user assignment
// @Tags auth
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch-user ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branch-users/{id} [delete]
func (h *handler) deleteBranchUser(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.DeleteBranchUser(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete branch user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func currentUserID(c *gin.Context) (int, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int:
return id, id > 0
case string:
parsed, err := strconv.Atoi(id)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}