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

@@ -2,7 +2,6 @@ package db
import (
"context"
"strconv"
"online-back/internal/admin/auth"
"online-back/pkg/client/postgresql"
@@ -22,32 +21,27 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
}
const (
loginQuery = `SELECT id, password FROM admin WHERE login = $1`
adminQuery = `SELECT id, password FROM admin WHERE id = $1`
loginQuery = `SELECT id, password FROM users WHERE email = $1`
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
profileQuery = `SELECT id, fullname, phone_number, avatar, created_at
FROM admin WHERE id = $1`
FROM users WHERE id = $1`
)
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.ResLoginDTO, error) {
var result auth.ResLoginDTO
err := r.client.QueryRow(ctx, loginQuery, dto.Login).Scan(&result.Id, &result.Password)
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
var result auth.UserCredentials
err := r.client.QueryRow(ctx, loginQuery, dto.Email).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) {
var result auth.ResLoginDTO
err := r.client.QueryRow(ctx, adminQuery, id).Scan(&result.Id, &result.Password)
func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredentials, error) {
var result auth.UserCredentials
err := r.client.QueryRow(ctx, userByIDQuery, id).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) GetProfile(ctx context.Context, id string) (auth.ResUserDTO, error) {
var profile auth.ResUserDTO
adminID, err := strconv.Atoi(id)
if err != nil {
return profile, err
}
err = r.client.QueryRow(ctx, profileQuery, adminID).Scan(
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
&profile.Id,
&profile.FullName,
&profile.PhoneNumber,

View File

@@ -3,23 +3,23 @@ package auth
import "time"
type LoginDTO struct {
Login string `json:"login" binding:"required"`
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
type ResLoginDTO struct {
Id int `json:"id"`
Password string `json:"-"`
}
type TokenReqBody struct {
type RefreshTokenDTO struct {
RefreshToken string `json:"refreshToken" binding:"required"`
}
type ResUserDTO struct {
type UserProfileDTO struct {
Id int `json:"id"`
FullName string `json:"fullName"`
PhoneNumber string `json:"phoneNumber"`
Avatar string `json:"avatar"`
CreatedAt time.Time `json:"createdAt"`
}
type UserCredentials struct {
Id int
Password string
}

View File

@@ -1,35 +0,0 @@
package auth
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
func imageStorageDir(publicRoot string) string {
return filepath.Join(publicRoot, "images")
}
func imagePublicPath(filename string) string {
return "/images/" + filename
}
func resolveImagePath(publicRoot, filename string) (string, error) {
if filename == "" || strings.Contains(filename, "..") || strings.ContainsAny(filename, `/\`) {
return "", fmt.Errorf("invalid file name")
}
base := filepath.Clean(imageStorageDir(publicRoot))
path := filepath.Clean(filepath.Join(base, filepath.Base(filename)))
if !strings.HasPrefix(path, base+string(os.PathSeparator)) && path != base {
return "", fmt.Errorf("invalid file path")
}
return path, nil
}
func newUploadFilename(original string) string {
return fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(original))
}

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"))
}

View File

@@ -3,7 +3,7 @@ package auth
import "context"
type Repository interface {
Login(ctx context.Context, dto LoginDTO) (ResLoginDTO, error)
CheckAdmin(ctx context.Context, id int) (ResLoginDTO, error)
GetProfile(ctx context.Context, req string) (ResUserDTO, error)
Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
GetUserByID(ctx context.Context, id int) (UserCredentials, error)
GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
}