| package auth
|
|
|
| import (
|
| "crypto/sha256"
|
| "encoding/hex"
|
| "errors"
|
| "fmt"
|
| "time"
|
|
|
| "github.com/golang-jwt/jwt/v5"
|
| )
|
|
|
| var (
|
|
|
| jwtSecret = []byte("atlassian_proxy_jwt_secret")
|
|
|
|
|
| tokenExpiration = 24 * time.Hour
|
| )
|
|
|
|
|
| type Claims struct {
|
| jwt.RegisteredClaims
|
| UserID uint `json:"user_id"`
|
| }
|
|
|
|
|
| func GenerateToken(userID uint) (string, error) {
|
|
|
| claims := Claims{
|
| RegisteredClaims: jwt.RegisteredClaims{
|
| ExpiresAt: jwt.NewNumericDate(time.Now().Add(tokenExpiration)),
|
| IssuedAt: jwt.NewNumericDate(time.Now()),
|
| NotBefore: jwt.NewNumericDate(time.Now()),
|
| },
|
| UserID: userID,
|
| }
|
|
|
|
|
| token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
|
| return token.SignedString(jwtSecret)
|
| }
|
|
|
|
|
| func ParseToken(tokenString string) (*Claims, error) {
|
|
|
| token, err := jwt.ParseWithClaims(tokenString, &Claims{}, 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 jwtSecret, nil
|
| })
|
|
|
| if err != nil {
|
| return nil, err
|
| }
|
|
|
|
|
| if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
| return claims, nil
|
| }
|
|
|
| return nil, errors.New("invalid token")
|
| }
|
|
|
|
|
| func HashPassword(password string) string {
|
|
|
| hash := sha256.Sum256([]byte(password))
|
| return hex.EncodeToString(hash[:])
|
| }
|
|
|
|
|
| func VerifyPassword(hashedPassword, password string) bool {
|
| return hashedPassword == HashPassword(password)
|
| }
|
|
|