Also save admin uploads locally under /public/images with a 10MB limit. Co-authored-by: Cursor <cursoragent@cursor.com>
339 lines
8.7 KiB
Go
Executable File
339 lines
8.7 KiB
Go
Executable File
package auth
|
|
|
|
import (
|
|
_ "bankline/docs"
|
|
"bankline/internal/appresult"
|
|
"bankline/internal/config"
|
|
"bankline/internal/handlers"
|
|
"bankline/pkg/logging"
|
|
"bankline/pkg/utils"
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
minioUpload "bankline/pkg/minio"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt"
|
|
)
|
|
|
|
const (
|
|
loginURL = "/login"
|
|
tokenURL = "/token"
|
|
|
|
getProfileURL = "/get-profile"
|
|
fileUploadURL = "/file"
|
|
fileRemoveURL = "/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.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
|
|
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
|
|
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.DeleteObject)
|
|
router.POST(tokenURL, h.token)
|
|
|
|
}
|
|
|
|
// =================================================================================
|
|
|
|
// login godoc
|
|
// @Description login for Admin
|
|
// @Tags auth
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param auth body LoginDTO true "Login JSON"
|
|
// @Success 200 {string} string true "token"
|
|
// @Router /admin/login [post]
|
|
func (h *handler) login(c *gin.Context) {
|
|
|
|
var (
|
|
loginReq LoginDTO
|
|
)
|
|
if err := c.ShouldBindJSON(&loginReq); err != nil {
|
|
fmt.Println("err in login", err)
|
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
return
|
|
}
|
|
|
|
res, err := h.repository.Login(context.TODO(), loginReq)
|
|
if err != nil {
|
|
fmt.Println("err in repository.Login", err)
|
|
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
password := []byte(fmt.Sprint(loginReq.Password))
|
|
oldHash := []byte(fmt.Sprint(res.Password))
|
|
errCompareHash := bcrypt.CompareHashAndPassword(oldHash, password)
|
|
if errCompareHash != nil {
|
|
fmt.Println("errCompareHash", errCompareHash)
|
|
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
newTokenPair, err := utils.GenerateTokenPair(res.Id)
|
|
if err != nil {
|
|
fmt.Println("err in GenerateTokenPair", err)
|
|
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
|
return
|
|
}
|
|
|
|
successResult := appresult.Success
|
|
successResult.Data = newTokenPair
|
|
|
|
c.JSON(http.StatusOK, successResult)
|
|
return
|
|
}
|
|
|
|
// getProfile godoc
|
|
// @Description profile data for Admin
|
|
// @Tags admin
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Security BearerAuth
|
|
// @Success 200 {object} ResUserDTO
|
|
// @Router /admin/get-profile [get]
|
|
func (h *handler) getProfile(c *gin.Context) {
|
|
uuid := c.Keys["id"]
|
|
fmt.Println("uuid ----", uuid)
|
|
dt, err := h.repository.GetProfile(context.Background(), fmt.Sprint(uuid))
|
|
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
|
|
successResult := appresult.Success
|
|
successResult.Data = dt
|
|
c.JSON(http.StatusOK, successResult)
|
|
}
|
|
|
|
// 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 {string} string
|
|
// @Router /admin/file [post]
|
|
func (h *handler) fileUpload(c *gin.Context) {
|
|
|
|
const maxUploadBytes = 10 << 20 // 10 MB
|
|
|
|
file, header, err := c.Request.FormFile("file")
|
|
if err != nil {
|
|
c.String(http.StatusBadRequest, "get form err: %s", err.Error())
|
|
return
|
|
}
|
|
|
|
defer func(file multipart.File) {
|
|
err := file.Close()
|
|
if err != nil {
|
|
fmt.Println("hello", err)
|
|
}
|
|
}(file)
|
|
|
|
if header.Size > maxUploadBytes {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "file size must not exceed 10 MB"})
|
|
return
|
|
}
|
|
|
|
cfg := config.GetConfig()
|
|
appDirPath := cfg.PublicFilePath + "/images/"
|
|
|
|
err = os.MkdirAll(appDirPath, os.ModePerm)
|
|
if err != nil {
|
|
fmt.Println("wwwww", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create upload directory"})
|
|
return
|
|
}
|
|
|
|
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
|
dbPath := "/public/images/" + appName
|
|
localPath := appDirPath + appName
|
|
|
|
if err := c.SaveUploadedFile(header, localPath); err != nil {
|
|
fmt.Println("Error saving file to public/images:", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "File upload failed"})
|
|
return
|
|
}
|
|
|
|
// minioClient, err := minioUpload.ConnectionMinio()
|
|
// if err != nil {
|
|
// c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
|
// return
|
|
// }
|
|
//
|
|
// contentType := header.Header.Get("Content-Type")
|
|
// ctx := context.Background()
|
|
//
|
|
// if err := minioUpload.EnsureBucket(ctx, minioClient); err != nil {
|
|
// fmt.Println("ensure bucket:", err)
|
|
// c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create MinIO bucket"})
|
|
// return
|
|
// }
|
|
//
|
|
// size := header.Size
|
|
// if size <= 0 {
|
|
// size = -1
|
|
// }
|
|
// _, err = minioClient.PutObject(ctx, minioUpload.BucketName, appName, file, size, minio.PutObjectOptions{ContentType: contentType})
|
|
// if err != nil {
|
|
// fmt.Println("Error uploading file to MinIO:", err)
|
|
// c.JSON(http.StatusInternalServerError, gin.H{"error": "File upload to MinIO failed"})
|
|
// return
|
|
// }
|
|
|
|
successResult := appresult.Success
|
|
successResult.Data = dbPath
|
|
c.JSON(http.StatusOK, successResult)
|
|
|
|
return
|
|
}
|
|
|
|
func GetObject(c *gin.Context) {
|
|
|
|
id := c.Param("id")
|
|
minioClient, err := minioUpload.ConnectionMinio()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
|
return
|
|
}
|
|
|
|
object, err := minioClient.GetObject(context.Background(), minioUpload.BucketName, id, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
fmt.Println("Error connection:", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
|
return
|
|
}
|
|
|
|
contentBytes := StreamToByte(object)
|
|
contentType := http.DetectContentType(contentBytes)
|
|
c.Data(http.StatusOK, contentType, contentBytes)
|
|
}
|
|
|
|
func StreamToByte(stream io.Reader) []byte {
|
|
buf := new(bytes.Buffer)
|
|
_, _ = buf.ReadFrom(stream)
|
|
return buf.Bytes()
|
|
}
|
|
|
|
// DeleteObject godoc
|
|
// @Description remove file
|
|
// @Tags file-upload
|
|
//
|
|
// @Accept multipart/form-data
|
|
// @Produce json
|
|
//
|
|
// @Param id path string true "file path"
|
|
// @Security BearerAuth
|
|
// @Success 200 {string} string
|
|
// @Router /admin/file/{id} [delete]
|
|
func (h *handler) DeleteObject(c *gin.Context) {
|
|
|
|
id := c.Param("id")
|
|
minioClient, err := minioUpload.ConnectionMinio()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
|
return
|
|
}
|
|
|
|
suc, err := DeleteItemInMinio(context.Background(), minioClient, id)
|
|
if err != nil {
|
|
fmt.Println("Error connection:", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
|
return
|
|
}
|
|
successResult := appresult.Success
|
|
successResult.Data = suc
|
|
c.JSON(http.StatusOK, successResult)
|
|
}
|
|
|
|
func DeleteItemInMinio(ctx context.Context, minioClient *minio.Client, value string) (string, error) {
|
|
err := minioClient.RemoveObject(ctx, minioUpload.BucketName, value, minio.RemoveObjectOptions{GovernanceBypass: true})
|
|
if err != nil {
|
|
fmt.Println("error remove file in minio:", err)
|
|
return "", err
|
|
}
|
|
return "File successfully removed!!!", nil
|
|
}
|
|
|
|
// token godoc
|
|
// @Description token for Admin
|
|
// @Tags auth
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param auth body TokenReqBody true "Token JSON"
|
|
// @Success 200 {string} string true "token"
|
|
// @Router /admin/token [post]
|
|
func (h *handler) token(c *gin.Context) {
|
|
var (
|
|
err error
|
|
tokenReq TokenReqBody
|
|
)
|
|
|
|
if err = c.ShouldBindJSON(&tokenReq); err != nil {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
return
|
|
}
|
|
|
|
token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
|
}
|
|
return []byte(utils.SecretKey), nil
|
|
})
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
|
|
res, err := h.repository.CheckAdmin(context.TODO(), int(claims["id"].(float64)))
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
if int(claims["id"].(float64)) == res.Id {
|
|
|
|
newTokenPair, err := utils.GenerateTokenPair(int(claims["id"].(float64)))
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
|
return
|
|
}
|
|
|
|
successResult := appresult.Success
|
|
successResult.Data = newTokenPair
|
|
c.JSON(http.StatusOK, successResult)
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|