quintodrome/core/auth/auth.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

77 lines
1.8 KiB
Go
Raw Normal View History

2020-02-06 12:48:35 -09:00
package auth
import (
"context"
2020-02-06 12:48:35 -09:00
"sync"
"time"
2021-05-11 13:21:18 -08:00
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/jwt"
"github.com/navidrome/navidrome/conf"
2020-02-06 12:48:35 -09:00
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
)
var (
once sync.Once
2021-04-30 06:00:03 -08:00
Secret []byte
TokenAuth *jwtauth.JWTAuth
sessionTimeOut time.Duration
2020-02-06 12:48:35 -09:00
)
func InitTokenAuth(ds model.DataStore) {
once.Do(func() {
secret, err := ds.Property(context.TODO()).DefaultGet(consts.JWTSecretKey, "not so secret")
2020-02-06 12:48:35 -09:00
if err != nil {
log.Error("No JWT secret found in DB. Setting a temp one, but please report this error", err)
}
2021-04-30 06:00:03 -08:00
Secret = []byte(secret)
TokenAuth = jwtauth.New("HS256", Secret, nil)
2020-02-06 12:48:35 -09:00
})
}
func CreateToken(u *model.User) (string, error) {
2021-05-11 13:21:18 -08:00
claims := map[string]interface{}{}
claims[jwt.IssuerKey] = consts.JWTIssuer
claims[jwt.IssuedAtKey] = time.Now().UTC().Unix()
claims[jwt.SubjectKey] = u.UserName
claims["uid"] = u.ID
2020-02-06 12:48:35 -09:00
claims["adm"] = u.IsAdmin
2021-05-11 13:21:18 -08:00
token, _, err := TokenAuth.Encode(claims)
if err != nil {
return "", err
}
2020-02-06 12:48:35 -09:00
return TouchToken(token)
}
func getSessionTimeOut() time.Duration {
if sessionTimeOut == 0 {
2020-07-02 12:41:54 -08:00
sessionTimeOut = conf.Server.SessionTimeout
log.Info("Setting Session Timeout", "value", sessionTimeOut)
}
return sessionTimeOut
}
2021-05-11 13:21:18 -08:00
func TouchToken(token jwt.Token) (string, error) {
claims, err := token.AsMap(context.Background())
if err != nil {
return "", err
2021-04-30 06:00:03 -08:00
}
2020-02-06 12:48:35 -09:00
2021-05-11 13:21:18 -08:00
timeout := getSessionTimeOut()
claims[jwt.ExpirationKey] = time.Now().UTC().Add(timeout).Unix()
_, newToken, err := TokenAuth.Encode(claims)
return newToken, err
2021-04-30 06:00:03 -08:00
}
2021-05-11 13:21:18 -08:00
func Validate(tokenStr string) (map[string]interface{}, error) {
token, err := jwtauth.VerifyToken(TokenAuth, tokenStr)
2020-02-06 12:48:35 -09:00
if err != nil {
return nil, err
}
2021-05-11 13:21:18 -08:00
return token.AsMap(context.Background())
2020-02-06 12:48:35 -09:00
}