feat: use JWT for authentication

BREAKING CHANGE: changes format of cookie
This commit is contained in:
Settel 2024-02-18 12:56:24 +01:00
parent bcc446ed16
commit 33bd7e8bab
2 changed files with 38 additions and 13 deletions

View File

@ -3,7 +3,6 @@ package handler
import (
"fmt"
"net/http"
"strings"
"sirlab.de/go/knowyt/user"
)
@ -30,22 +29,11 @@ func (authMux *AuthMux) accessDenied(w http.ResponseWriter, r *http.Request) {
}
func (authMux *AuthMux) getUserFromSession(r *http.Request) (*user.User, error) {
authCookie, err := r.Cookie("knowyt-auth")
usr, err := authMux.validateSessionAndGetUser(r)
if err != nil {
return nil, fmt.Errorf("invalid cookie")
}
vals := strings.SplitN(authCookie.Value, ":", 2)
usr, usrErr := authMux.app.GetUserById(vals[0])
if usrErr != nil {
return nil, fmt.Errorf("invalid cookie")
}
if usr.GetAuthCode() != vals[1] {
return nil, fmt.Errorf("invalid cookie")
}
if usr.IsAdmin() {
if cookieCameo, err := r.Cookie("knowyt-auth-cameo"); err == nil {
if usrCameo, err := authMux.app.GetUserById(cookieCameo.Value); err == nil {

View File

@ -2,9 +2,12 @@ package handler
import (
"crypto/rand"
"fmt"
"net/http"
"time"
"github.com/golang-jwt/jwt"
"sirlab.de/go/knowyt/user"
)
var secretKey []byte = nil
@ -25,3 +28,37 @@ func (authMux *AuthMux) createToken(uid string) (string, error) {
return token.SignedString(secretKey)
}
func (authMux *AuthMux) validateSessionAndGetUser(r *http.Request) (*user.User, error) {
tokenString, err := r.Cookie("knowyt-auth")
if err != nil {
return nil, err
}
token, err := jwt.Parse(tokenString.Value, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid JWT")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("invalid JWT")
}
userId := claims["uid"].(string)
if len(userId) == 0 {
return nil, fmt.Errorf("invalid JWT")
}
usr, err := authMux.app.GetUserById(userId)
if err != nil {
return nil, err
}
return usr, nil
}