2022-01-19 20:45:53 +00:00
|
|
|
package gpaste
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
2022-01-20 02:35:55 +00:00
|
|
|
"git.t-juice.club/torjus/gpaste/users"
|
2022-01-19 20:45:53 +00:00
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
|
|
|
type AuthService struct {
|
2022-01-20 02:35:55 +00:00
|
|
|
users users.UserStore
|
2022-01-19 20:45:53 +00:00
|
|
|
hmacSecret []byte
|
|
|
|
}
|
|
|
|
|
2022-01-20 12:33:11 +00:00
|
|
|
type Claims struct {
|
|
|
|
Role users.Role `json:"role,omitempty"`
|
|
|
|
|
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
|
|
|
|
2022-01-20 02:35:55 +00:00
|
|
|
func NewAuthService(store users.UserStore, signingSecret []byte) *AuthService {
|
2022-01-19 20:45:53 +00:00
|
|
|
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
|
2022-01-20 12:33:11 +00:00
|
|
|
claims := new(Claims)
|
|
|
|
claims.Subject = user.Username
|
|
|
|
claims.ExpiresAt = time.Now().Add(7 * 24 * time.Hour).Unix()
|
|
|
|
claims.NotBefore = time.Now().Unix()
|
|
|
|
claims.IssuedAt = time.Now().Unix()
|
|
|
|
claims.Id = uuid.NewString()
|
|
|
|
claims.Role = user.Role
|
2022-01-19 20:45:53 +00:00
|
|
|
|
|
|
|
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
|
2022-01-24 19:25:52 +00:00
|
|
|
|
2022-01-19 20:45:53 +00:00
|
|
|
signed, err := token.SignedString(as.hmacSecret)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return signed, nil
|
|
|
|
}
|
|
|
|
|
2022-01-20 12:33:11 +00:00
|
|
|
func (as *AuthService) ValidateToken(rawToken string) (*Claims, error) {
|
|
|
|
claims := &Claims{}
|
2022-01-19 20:45:53 +00:00
|
|
|
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
|
|
|
}
|
2022-01-24 19:25:52 +00:00
|
|
|
|
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
|
|
|
}
|