fixed
This commit is contained in:
88
backend/internal/admin/auth/db/postgresql.go
Executable file
88
backend/internal/admin/auth/db/postgresql.go
Executable file
@@ -0,0 +1,88 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/pkg/client/postgresql"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.ResLoginDTO, error) {
|
||||
var (
|
||||
result auth.ResLoginDTO
|
||||
)
|
||||
|
||||
q := `select
|
||||
id, password
|
||||
from admin
|
||||
where login = $1 ;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, dto.Login).Scan(&result.Id, &result.Password)
|
||||
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) {
|
||||
|
||||
var (
|
||||
result auth.ResLoginDTO
|
||||
)
|
||||
|
||||
q := `select
|
||||
id, password
|
||||
from admin
|
||||
where id = $1 ;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(&result.Id, &result.Password)
|
||||
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetProfile(ctx context.Context, uuid string) (auth.ResUserDTO, error) {
|
||||
|
||||
var (
|
||||
ad auth.ResUserDTO
|
||||
)
|
||||
id, _ := strconv.Atoi(uuid)
|
||||
|
||||
q := `select
|
||||
id, fullname,
|
||||
phone_number, avatar,
|
||||
created_at
|
||||
from admin
|
||||
where id = $1;`
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&ad.Id, &ad.FullName,
|
||||
&ad.PhoneNumber, &ad.Avatar,
|
||||
&ad.CreatedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return ad, err
|
||||
}
|
||||
|
||||
return ad, nil
|
||||
}
|
||||
81
backend/internal/admin/auth/db/postgresql_test.go
Normal file
81
backend/internal/admin/auth/db/postgresql_test.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/pkg/logging"
|
||||
"errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"golang.org/x/net/context"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/pashagolub/pgxmock"
|
||||
)
|
||||
|
||||
var (
|
||||
// prepare mock
|
||||
colums = []string{"id", "password"}
|
||||
|
||||
// request
|
||||
req = auth.LoginDTO{
|
||||
Login: "admin@admin.com",
|
||||
}
|
||||
|
||||
// expected
|
||||
want = auth.ResLoginDTO{
|
||||
Id: 1,
|
||||
Password: "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i",
|
||||
}
|
||||
)
|
||||
|
||||
// Setup will prepare mock and account service instance
|
||||
func Run(t *testing.T) pgxmock.PgxPoolIface {
|
||||
t.Helper()
|
||||
mock, err := pgxmock.NewPool()
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error occur: %v\n", err)
|
||||
}
|
||||
defer mock.Close()
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
mock := Run(t)
|
||||
q := `select id, password from admin where login = $1 ;`
|
||||
|
||||
t.Run("EXPECT SUCCESS", func(t *testing.T) {
|
||||
mock.ExpectQuery(regexp.QuoteMeta(q)).
|
||||
WithArgs(req.Login).
|
||||
WillReturnRows(mock.NewRows(colums).
|
||||
AddRow(1, "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i"))
|
||||
|
||||
// actual
|
||||
logger := logging.GetLogger()
|
||||
ops := NewRepository(mock, logger)
|
||||
got, err := ops.Login(context.Background(), req)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, got.Id, want.Id)
|
||||
assert.Equal(t, got, want)
|
||||
})
|
||||
|
||||
t.Run("EXPECT FAIL", func(t *testing.T) {
|
||||
mock.ExpectQuery(regexp.QuoteMeta(q)).
|
||||
WithArgs(req.Login).
|
||||
WillReturnError(errors.New("error getting user data"))
|
||||
|
||||
// actual
|
||||
logger := logging.GetLogger()
|
||||
ops := NewRepository(mock, logger)
|
||||
got, err := ops.Login(context.Background(), req)
|
||||
assert.Error(t, err)
|
||||
if got.Id == 0 {
|
||||
assert.Nil(t, nil)
|
||||
}
|
||||
})
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("there were unfulfilled expectation: %v\n", err)
|
||||
}
|
||||
}
|
||||
29
backend/internal/admin/auth/dto.go
Executable file
29
backend/internal/admin/auth/dto.go
Executable file
@@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Login string `json:"login" binding:"required" required:"this one failed" `
|
||||
Password string `json:"password" binding:"required" required:"this one failed"`
|
||||
}
|
||||
|
||||
type ResLoginDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type TokenReqBody struct {
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
}
|
||||
|
||||
type ReqDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
|
||||
type ResUserDTO struct {
|
||||
Id int `json:"Id"`
|
||||
FullName string `json:"fullName"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
320
backend/internal/admin/auth/handler.go
Executable file
320
backend/internal/admin/auth/handler.go
Executable file
@@ -0,0 +1,320 @@
|
||||
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 {
|
||||
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 {
|
||||
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) {
|
||||
|
||||
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)
|
||||
|
||||
cfg := config.GetConfig()
|
||||
appDirPath := cfg.PublicFilePath + "/images/"
|
||||
|
||||
err = os.MkdirAll(appDirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
fmt.Println("wwwww", err)
|
||||
}
|
||||
|
||||
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
||||
dbPath := "/images/" + appName
|
||||
|
||||
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
|
||||
}
|
||||
9
backend/internal/admin/auth/storage.go
Executable file
9
backend/internal/admin/auth/storage.go
Executable file
@@ -0,0 +1,9 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user