Align schema, API routes, and auth with updated admin domain model.

Rename users table fields and loan documents table, expand branch billing credentials, switch to /api/admin prefix, refactor auth endpoints, replace PATCH with PUT for status updates, remove file upload APIs, and regenerate Swagger with ordered tags.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-06 14:09:45 +05:00
parent 0c717101da
commit 82e1aad016
22 changed files with 4248 additions and 418 deletions

View File

@@ -1,13 +1,10 @@
package auth
import (
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/handlers"
"online-back/pkg/logging"
"online-back/pkg/utils"
@@ -17,11 +14,9 @@ import (
)
const (
loginURL = "/login"
tokenURL = "/token"
getProfileURL = "/get-profile"
fileUploadURL = "/file"
fileRemoveURL = "/file/:id"
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
)
type handler struct {
@@ -30,50 +25,48 @@ type handler struct {
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{
logger: logger,
repository: repository,
}
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.token)
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.deleteObject)
router.POST(tokenURL, h.refreshToken)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
}
// login godoc
// @Description login for Admin
// @Tags auth
// @Accept json
// @Produce json
// @Param auth body LoginDTO true "Login JSON"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /login [post]
// @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 loginReq LoginDTO
if err := c.ShouldBindJSON(&loginReq); err != nil {
var dto LoginDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
ctx := c.Request.Context()
res, err := h.repository.Login(ctx, loginReq)
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(res.Password), []byte(loginReq.Password)); err != nil {
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(res.Id)
tokenPair, err := utils.GenerateTokenPair(user.Id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
@@ -82,23 +75,25 @@ func (h *handler) login(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// token godoc
// @Description refresh admin tokens
// @Tags auth
// @Accept json
// @Produce json
// @Param auth body TokenReqBody true "Token JSON"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /token [post]
func (h *handler) token(c *gin.Context) {
var tokenReq TokenReqBody
if err := c.ShouldBindJSON(&tokenReq); err != nil {
// 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(tokenReq.RefreshToken)
claims, err := utils.ParseRefreshToken(dto.RefreshToken)
if err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
@@ -110,8 +105,8 @@ func (h *handler) token(c *gin.Context) {
return
}
admin, err := h.repository.CheckAdmin(c.Request.Context(), id)
if err != nil || admin.Id != id {
user, err := h.repository.GetUserByID(c.Request.Context(), id)
if err != nil || user.Id != id {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
@@ -126,100 +121,46 @@ func (h *handler) token(c *gin.Context) {
}
// getProfile godoc
// @Description profile data for Admin
// @Tags admin
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /get-profile [get]
// @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) {
adminID, _ := c.Get("id")
profile, err := h.repository.GetProfile(c.Request.Context(), fmt.Sprint(adminID))
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.StatusBadRequest, appresult.ErrNotFound)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
// fileUpload godoc
// @Description file upload
// @Tags file-upload
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "upload file"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /file [post]
func (h *handler) fileUpload(c *gin.Context) {
header, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
func currentUserID(c *gin.Context) (int, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
cfg := config.GetConfig()
dir := imageStorageDir(cfg.PublicFilePath)
if err := os.MkdirAll(dir, 0755); err != nil {
h.logger.Errorf("create upload dir failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
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
}
filename := newUploadFilename(header.Filename)
if err := c.SaveUploadedFile(header, filepath.Join(dir, filename)); err != nil {
h.logger.Errorf("save upload failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(imagePublicPath(filename)))
}
// GetObject serves uploaded images from local storage.
func GetObject(c *gin.Context) {
path, err := resolveImagePath(config.GetConfig().PublicFilePath, c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
content, err := os.ReadFile(path)
if err != nil {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.Data(http.StatusOK, http.DetectContentType(content), content)
}
// deleteObject godoc
// @Description remove file
// @Tags file-upload
// @Accept json
// @Produce json
// @Param id path string true "file name"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /file/{id} [delete]
func (h *handler) deleteObject(c *gin.Context) {
path, err := resolveImagePath(config.GetConfig().PublicFilePath, c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
if err := os.Remove(path); err != nil {
h.logger.Errorf("delete file failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
}