gpaste/auth.go

62 lines
1.3 KiB
Go
Raw Normal View History

2022-01-19 20:45:53 +00:00
package gpaste
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
)
type AuthService struct {
users UserStore
hmacSecret []byte
}
func NewAuthService(store UserStore, signingSecret []byte) *AuthService {
return &AuthService{users: store, hmacSecret: signingSecret}
}
func (as *AuthService) Login(username, password string) (string, error) {
user, err := as.users.Get(username)
if err != nil {
return "", err
}
if err := user.ValidatePassword(password); err != nil {
return "", err
}
// TODO: Set iss and aud
claims := jwt.StandardClaims{
Subject: user.Username,
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
NotBefore: time.Now().Unix(),
IssuedAt: time.Now().Unix(),
Id: uuid.NewString(),
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
signed, err := token.SignedString(as.hmacSecret)
if err != nil {
return "", err
}
return signed, nil
}
2022-01-20 00:04:44 +00:00
func (as *AuthService) ValidateToken(rawToken string) (*jwt.StandardClaims, error) {
2022-01-19 20:45:53 +00:00
claims := &jwt.StandardClaims{}
token, err := jwt.ParseWithClaims(rawToken, claims, func(t *jwt.Token) (interface{}, error) {
return as.hmacSecret, nil
})
if err != nil {
2022-01-20 00:04:44 +00:00
return nil, err
2022-01-19 20:45:53 +00:00
}
if !token.Valid {
2022-01-20 00:04:44 +00:00
return nil, fmt.Errorf("invalid token")
2022-01-19 20:45:53 +00:00
}
2022-01-20 00:04:44 +00:00
return claims, nil
2022-01-19 20:45:53 +00:00
}