feat: use JWT for authentication (WIP)

BREAKING CHANGE: changes format of cookie
This commit is contained in:
Settel 2024-02-18 11:17:19 +01:00
parent 0f0b2ede64
commit bcc446ed16
4 changed files with 42 additions and 3 deletions

View File

@ -3,6 +3,7 @@ module sirlab.de/go/knowyt
go 1.18
require (
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/google/uuid v1.3.0
github.com/imkira/go-observer v1.0.3
)

View File

@ -1,3 +1,5 @@
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/imkira/go-observer v1.0.3 h1:l45TYAEeAB4L2xF6PR2gRLn2NE5tYhudh33MLmC7B80=

View File

@ -36,17 +36,26 @@ func (authMux *AuthMux) Login(w http.ResponseWriter, r *http.Request) {
// check, if game is enabled
gm, err := authMux.app.GetGameById(usr.GetGameId())
if err != nil || !gm.IsActive() {
log.ErrorLog(fmt.Errorf("game %s disabled for user %s", gm.GetId(), usr.GetName()))
log.ErrorLog(fmt.Errorf("game %s disabled for user %s (%s)", gm.GetId(), usr.GetName(), usr.GetId()))
http.SetCookie(w, authMux.createCookie())
authMux.accessDenied(w, r)
return
}
}
log.Info("%s logged into game %s\n", usr.GetName(), usr.GetGameId())
log.Info("%s (%s) logged into game %s\n", usr.GetName(), usr.GetId(), usr.GetGameId())
tokenString, err := authMux.createToken(usr.GetId())
if err != nil {
log.ErrorLog(fmt.Errorf("failed to create JWT for user id %s (%s)", usr.GetName(), usr.GetId()))
log.ErrorLog(err)
http.SetCookie(w, authMux.createCookie())
authMux.accessDenied(w, r)
return
}
cookie := authMux.createCookie()
cookie.Value = usr.GetId() + ":" + usr.GetAuthCode()
cookie.Value = tokenString
cookie.MaxAge = 0
http.SetCookie(w, cookie)
w.Header().Add("Content-Type", "text/plain")

View File

@ -0,0 +1,27 @@
package handler
import (
"crypto/rand"
"time"
"github.com/golang-jwt/jwt"
)
var secretKey []byte = nil
func (authMux *AuthMux) createToken(uid string) (string, error) {
if secretKey == nil {
secretKey = make([]byte, 32)
if _, err := rand.Read(secretKey); err != nil {
return "", err
}
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512,
jwt.MapClaims{
"uid": uid,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
return token.SignedString(secretKey)
}