add jwt authentication, and fix cours for next js

This commit is contained in:
Tulyaganov Shuhrat committed 2023-05-02 11:02:06 +03:00
1 parent 3026f89f2e
commit 05b8d55d0e
17 files changed
+471 -64

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
package jwt
import (
"fmt"
"github.com/golang-jwt/jwt/v5"
)
func ValidateToken(tokenString string, secretKey []byte) (bool, error) {
token, err := jwt.Parse(tokenString, 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 secretKey, nil
})
if err != nil {
return false, err
}
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return true, nil
} else {
return false, nil
}
}
+48
View File
@@ -0,0 +1,48 @@
package jwt
import (
"os"
"time"
"git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd/model"
"github.com/golang-jwt/jwt/v5"
)
type jwtToken struct {
AccesToken string
RefreshToken string
}
func GenerateTokens(payload model.User) (*jwtToken, error) {
AccessKey := os.Getenv("JWT_SECRET_KEY_ACCESS")
RefreshKey := os.Getenv("JWT_SECRET_KEY_REFRESH")
claimsAccess := jwt.MapClaims{
"name": payload.Login,
"permisionlvl": payload.PermisionLVL,
"email": payload.Email,
"exp": time.Now().Add(time.Hour * 24 * 60).Unix(),
}
claimsRefresh := jwt.MapClaims{
"name": payload.Login,
"permisionlvl": payload.PermisionLVL,
"email": payload.Email,
"exp": time.Now().Add(time.Hour * 24 * 360).Unix(),
}
tokenAcc := jwt.NewWithClaims(jwt.SigningMethodHS256, claimsAccess)
tokenRef := jwt.NewWithClaims(jwt.SigningMethodHS256, claimsRefresh)
AccesToken, err := tokenAcc.SignedString([]byte(AccessKey))
if err != nil {
return nil, err
}
RefreshToken, err := tokenRef.SignedString([]byte(RefreshKey))
if err != nil {
return nil, err
}
return &jwtToken{
AccesToken: AccesToken,
RefreshToken: RefreshToken,
}, nil
}
+12 -1
View File
@@ -1,6 +1,8 @@
package password
import "golang.org/x/crypto/bcrypt"
import (
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (*[]byte, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
@@ -9,3 +11,12 @@ func HashPassword(password string) (*[]byte, error) {
}
return &bytes, err
}
func CheckValid(password string, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
if err != nil {
return false
}
return true
}