settings section
This commit is contained in:
58
internal/admin/auth/db/postgresql.go
Executable file
58
internal/admin/auth/db/postgresql.go
Executable file
@@ -0,0 +1,58 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/admin/auth"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
loginQuery = `SELECT id, password FROM admin WHERE login = $1`
|
||||
adminQuery = `SELECT id, password FROM admin WHERE id = $1`
|
||||
profileQuery = `SELECT id, fullname, phone_number, avatar, created_at
|
||||
FROM admin 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)
|
||||
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)
|
||||
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(
|
||||
&profile.Id,
|
||||
&profile.FullName,
|
||||
&profile.PhoneNumber,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
)
|
||||
return profile, err
|
||||
}
|
||||
25
internal/admin/auth/dto.go
Executable file
25
internal/admin/auth/dto.go
Executable file
@@ -0,0 +1,25 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Login string `json:"login" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type ResLoginDTO struct {
|
||||
Id int `json:"id"`
|
||||
Password string `json:"-"`
|
||||
}
|
||||
|
||||
type TokenReqBody struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type ResUserDTO struct {
|
||||
Id int `json:"id"`
|
||||
FullName string `json:"fullName"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
35
internal/admin/auth/files.go
Normal file
35
internal/admin/auth/files.go
Normal file
@@ -0,0 +1,35 @@
|
||||
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))
|
||||
}
|
||||
225
internal/admin/auth/handler.go
Executable file
225
internal/admin/auth/handler.go
Executable file
@@ -0,0 +1,225 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
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.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)
|
||||
}
|
||||
|
||||
// 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]
|
||||
func (h *handler) login(c *gin.Context) {
|
||||
var loginReq LoginDTO
|
||||
if err := c.ShouldBindJSON(&loginReq); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := c.Request.Context()
|
||||
res, err := h.repository.Login(ctx, loginReq)
|
||||
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 {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenPair, err := utils.GenerateTokenPair(res.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
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 {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := utils.ParseRefreshToken(tokenReq.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
|
||||
}
|
||||
|
||||
admin, err := h.repository.CheckAdmin(c.Request.Context(), id)
|
||||
if err != nil || admin.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
|
||||
// @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]
|
||||
func (h *handler) getProfile(c *gin.Context) {
|
||||
adminID, _ := c.Get("id")
|
||||
profile, err := h.repository.GetProfile(c.Request.Context(), fmt.Sprint(adminID))
|
||||
if err != nil {
|
||||
h.logger.Errorf("get profile failed: %v", err)
|
||||
c.JSON(http.StatusBadRequest, 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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"))
|
||||
}
|
||||
9
internal/admin/auth/storage.go
Executable file
9
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