fixed
This commit is contained in:
89
backend/pkg/utils/utils.go
Executable file
89
backend/pkg/utils/utils.go
Executable file
@@ -0,0 +1,89 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bankline/internal/config"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
const (
|
||||
SecretKey = "8a96a17e136bee4e61b3f9c443a4a408bfb452df763ed42d9db2f285aaa43a5c+"
|
||||
)
|
||||
|
||||
func DoWithTries(fn func() error, attemtps int, delay time.Duration) (err error) {
|
||||
for attemtps > 0 {
|
||||
if err = fn(); err != nil {
|
||||
time.Sleep(delay)
|
||||
attemtps--
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func CreateFile(folderName string, file *multipart.FileHeader, r *gin.Context) (string, error) {
|
||||
cfg := config.GetConfig()
|
||||
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(filepath.Base(file.Filename)))
|
||||
appDirPath := cfg.PublicFilePath + "/" + folderName
|
||||
|
||||
err := os.MkdirAll(appDirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
return "str", err
|
||||
}
|
||||
|
||||
pathApp := fmt.Sprintf("%s/%s", appDirPath, appName)
|
||||
if err := r.SaveUploadedFile(file, pathApp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
pathApp = "/public/" + folderName + "/" + appName
|
||||
return pathApp, err
|
||||
}
|
||||
|
||||
func RemoveFile(path string) error {
|
||||
err := os.RemoveAll(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateTokenPair(id int) (map[string]string, error) {
|
||||
cfg := config.GetConfig()
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
claims["id"] = id
|
||||
claims["admin"] = true
|
||||
claims["exp"] = time.Now().Add(time.Minute * 60).Unix()
|
||||
|
||||
t, err := token.SignedString([]byte(cfg.JwtKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refreshToken := jwt.New(jwt.SigningMethodHS256)
|
||||
rtClaims := refreshToken.Claims.(jwt.MapClaims)
|
||||
rtClaims["id"] = id
|
||||
rtClaims["exp"] = time.Now().Add(time.Hour * 24 * 30).Unix()
|
||||
|
||||
rt, err := refreshToken.SignedString([]byte(SecretKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return map[string]string{
|
||||
"accessToken": t,
|
||||
"refreshToken": rt,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user