diff --git a/easyauth.go b/easyauth.go index 5279a57..1a77eaf 100644 --- a/easyauth.go +++ b/easyauth.go @@ -11,8 +11,9 @@ import ( ) type EasyAuth struct { - client Auth - jwtSecret []byte + client Auth + JwtSecret []byte + TimeUntilJWTExpired time.Duration } type UserClaims struct { @@ -23,10 +24,24 @@ type UserClaims struct { func NewEasyAuth(client Auth) (EasyAuth, error) { e := EasyAuth{} e.client = client - e.jwtSecret = []byte("hsajedogö") + e.JwtSecret = []byte("hsajedogö") + e.TimeUntilJWTExpired = 120 * time.Minute return e, nil } +func (e EasyAuth) CheckUser(w http.ResponseWriter, r *http.Request) (AuthentikUser, error) { + user, con, err := e.GetUser(w, r) + if err != nil { + return AuthentikUser{}, err + } + + if !con { + return AuthentikUser{}, ErrUserNeedRedirect + } + + return user, nil +} + func (e EasyAuth) GetUser(w http.ResponseWriter, r *http.Request) (AuthentikUser, bool, error) { store, err := session.Start(context.Background(), w, r) if err != nil { @@ -48,7 +63,7 @@ func (e EasyAuth) GetUser(w http.ResponseWriter, r *http.Request) (AuthentikUser jwtString := fmt.Sprintf("%s", jwtData) parsedAccessToken, _ := jwt.ParseWithClaims(jwtString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) { - return e.jwtSecret, nil + return e.JwtSecret, nil }) if !parsedAccessToken.Valid { @@ -83,7 +98,7 @@ func (e EasyAuth) AuthHTTPHandler(w http.ResponseWriter, r *http.Request) { panic(err) // TODO: Deal with error } - expired := time.Now().Add(5 * time.Minute) + expired := time.Now().Add(e.TimeUntilJWTExpired) claims := UserClaims{} claims.Issuer = "EasyAuth" @@ -94,7 +109,7 @@ func (e EasyAuth) AuthHTTPHandler(w http.ResponseWriter, r *http.Request) { claims.User = user jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS512, claims) - jwtString, err := jwtToken.SignedString(e.jwtSecret) + jwtString, err := jwtToken.SignedString(e.JwtSecret) if err != nil { panic(err) // TODO: Deal with error } diff --git a/errors.go b/errors.go index 222248a..59eaba5 100644 --- a/errors.go +++ b/errors.go @@ -11,4 +11,5 @@ var ( ErrWrongResponseFromServer = errors.New("cant get access token from server") ErrCantGetUserInfo = errors.New("cant get user info") ErrCreateRequestForUserInfo = errors.New("cant create request for get user") + ErrUserNeedRedirect = errors.New("user need to login at oauth server") )