This commit is contained in:
PB
2023-04-16 17:17:05 +02:00
parent cd9bbdfd75
commit 7adf3b9512
24 changed files with 509 additions and 325 deletions

View File

@@ -0,0 +1,50 @@
package service
import (
"errors"
"strconv"
"git.pbiernat.dev/egommerce/identity-service/pkg/config"
"github.com/gofiber/fiber/v2"
)
var (
AuthService *Auth
JWTService *JWT
ErrLoginIncorrect = errors.New("login incorrect")
)
func init() {
cookieExpireTime, _ := strconv.Atoi(config.GetEnv("AUTH_COOKIE_EXPIRE_TIME", "5"))
AuthService = &Auth{"jwt_token", "jwt_token_refresh", cookieExpireTime}
}
type Auth struct {
TokenCookieName string
RefreshTokenCookieName string
cookieExpireTime int
}
func (a *Auth) Login(login, pass string) (string, error) {
if login == "admin" && pass == "secret" {
token, err := JWTService.CreateToken()
if err != nil {
return "", err
}
return token, nil
}
return "", ErrLoginIncorrect
}
// Cookie create fiber.Cookie struct
func (a *Auth) Cookie(name, value string) *fiber.Cookie {
return &fiber.Cookie{
Name: name,
Value: value,
MaxAge: a.cookieExpireTime * 300, // FIXME: env/config
Path: "/", // FIXME: env/config
}
}

View File

@@ -0,0 +1,53 @@
package service
import (
"fmt"
"strconv"
"time"
"git.pbiernat.dev/egommerce/identity-service/pkg/config"
"github.com/golang-jwt/jwt"
)
var (
tokenExpireTime int
tokenSecret []byte
)
func init() {
tokenExpireTime, _ = strconv.Atoi(config.GetEnv("JWT_TOKEN_EXPIRE_TIME", "5"))
tokenSecret = []byte(config.GetEnv("JWT_SECRET_KEY", "B413IlIv9nKQfsMCXTE0Cteo4yHgUEfqaLfjg73sNlh")) // FIXME env: JWT_SECRET_KEY !!!
JWTService = &JWT{tokenExpireTime, tokenSecret}
}
type JWT struct {
tokenExpireTime int
tokenSecret []byte
}
func (s *JWT) CreateToken() (string, error) {
claims := &jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Duration(s.tokenExpireTime) * time.Minute).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(s.tokenSecret)
}
func (s *JWT) ValidateToken(tokenStr string) error {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return s.tokenSecret, nil
})
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return nil
}
return err
}