gpaste/auth.go
Torjus Håkestad 790cc43949
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Add authlevel to middleware
2022-01-20 01:11:40 +01:00

70 lines
1.4 KiB
Go

package gpaste
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
)
type AuthLevel int
const (
AuthLevelUnset AuthLevel = iota
AuthLevelUser
AuthLevelAdmin
)
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
}
func (as *AuthService) ValidateToken(rawToken string) (*jwt.StandardClaims, error) {
claims := &jwt.StandardClaims{}
token, err := jwt.ParseWithClaims(rawToken, claims, func(t *jwt.Token) (interface{}, error) {
return as.hmacSecret, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
return claims, nil
}