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 } func (as *AuthService) ValidateToken(rawToken string) error { claims := &jwt.StandardClaims{} token, err := jwt.ParseWithClaims(rawToken, claims, func(t *jwt.Token) (interface{}, error) { return as.hmacSecret, nil }) if err != nil { return err } if !token.Valid { return fmt.Errorf("invalid token") } return nil }