387 lines
11 KiB
Go
Executable File
387 lines
11 KiB
Go
Executable File
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strconv"
|
|
"time"
|
|
|
|
"online-back/internal/appresult"
|
|
"online-back/internal/config"
|
|
"online-back/internal/handlers"
|
|
"online-back/pkg/logging"
|
|
minioUpload "online-back/pkg/minio"
|
|
"online-back/pkg/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/jackc/pgx/v4"
|
|
"github.com/minio/minio-go/v7"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
const (
|
|
loginURL = "/login"
|
|
tokenURL = "/token"
|
|
profileURL = "/profile"
|
|
branchUserURL = "/branch-users"
|
|
fileUploadURL = "/file"
|
|
fileURL = "/file/:id"
|
|
)
|
|
|
|
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)
|
|
protected.POST(fileUploadURL, h.fileUpload)
|
|
protected.GET(fileURL, h.getFile)
|
|
protected.DELETE(fileURL, h.deleteFile)
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
// fileUpload godoc
|
|
// @Description file upload
|
|
// @Tags file-upload
|
|
//
|
|
// @Accept multipart/form-data
|
|
// @Produce json
|
|
// @Param file formData file true "this is a test file"
|
|
//
|
|
// @Security BearerAuth
|
|
// @Success 200 {object} appresult.AppSuccess
|
|
// @Failure 400 {object} appresult.AppError
|
|
// @Failure 500 {object} appresult.AppError
|
|
// @Router /file [post]
|
|
func (h *handler) fileUpload(c *gin.Context) {
|
|
file, header, err := c.Request.FormFile("file")
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
minioCfg := config.GetConfig().Minio
|
|
minioClient, ok := h.connectMinio(c, minioCfg)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
ctx := c.Request.Context()
|
|
if err := ensureBucket(ctx, minioClient, minioCfg.Bucket); err != nil {
|
|
h.logger.Errorf("ensure minio bucket failed: %v", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
objectName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
|
contentType := header.Header.Get("Content-Type")
|
|
|
|
if _, err := minioClient.PutObject(ctx, minioCfg.Bucket, objectName, file, header.Size, minio.PutObjectOptions{ContentType: contentType}); err != nil {
|
|
h.logger.Errorf("upload file to minio failed: %v", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, appresult.SuccessWithData(objectName))
|
|
}
|
|
|
|
// getFile godoc
|
|
// @Description download file
|
|
// @Tags file-upload
|
|
// @Produce octet-stream
|
|
// @Param id path string true "object name"
|
|
// @Security BearerAuth
|
|
// @Success 200 {file} binary
|
|
// @Failure 500 {object} appresult.AppError
|
|
// @Router /file/{id} [get]
|
|
func (h *handler) getFile(c *gin.Context) {
|
|
id := c.Param("id")
|
|
|
|
minioCfg := config.GetConfig().Minio
|
|
minioClient, ok := h.connectMinio(c, minioCfg)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, id, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
h.logger.Errorf("get object from minio failed: %v", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
|
return
|
|
}
|
|
defer object.Close()
|
|
|
|
content, err := io.ReadAll(object)
|
|
if err != nil {
|
|
h.logger.Errorf("read object from minio failed: %v", err)
|
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
|
return
|
|
}
|
|
|
|
c.Data(http.StatusOK, http.DetectContentType(content), content)
|
|
}
|
|
|
|
// deleteFile godoc
|
|
// @Description remove file
|
|
// @Tags file-upload
|
|
// @Produce json
|
|
// @Param id path string true "object name"
|
|
// @Security BearerAuth
|
|
// @Success 200 {object} appresult.AppSuccess
|
|
// @Failure 500 {object} appresult.AppError
|
|
// @Router /file/{id} [delete]
|
|
func (h *handler) deleteFile(c *gin.Context) {
|
|
id := c.Param("id")
|
|
|
|
minioCfg := config.GetConfig().Minio
|
|
minioClient, ok := h.connectMinio(c, minioCfg)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if err := minioClient.RemoveObject(c.Request.Context(), minioCfg.Bucket, id, minio.RemoveObjectOptions{GovernanceBypass: true}); err != nil {
|
|
h.logger.Errorf("remove object from minio failed: %v", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
|
|
}
|
|
|
|
// connectMinio opens a MinIO client, writing an error response and returning
|
|
// ok=false if the connection fails so callers can bail out immediately.
|
|
func (h *handler) connectMinio(c *gin.Context, cfg config.MinioConfig) (*minio.Client, bool) {
|
|
client, err := minioUpload.Connect(cfg.Endpoint, cfg.AccessKey, cfg.SecretKey, cfg.UseSSL)
|
|
if err != nil {
|
|
h.logger.Errorf("minio connection failed: %v", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return nil, false
|
|
}
|
|
return client, true
|
|
}
|
|
|
|
func ensureBucket(ctx context.Context, client *minio.Client, bucket string) error {
|
|
exists, err := client.BucketExists(ctx, bucket)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if exists {
|
|
return nil
|
|
}
|
|
return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})
|
|
}
|