Client UUID added to JWT

This commit is contained in:
Magnus Åhall 2025-01-12 17:35:29 +01:00
parent dfd6260a7a
commit dc010df448
6 changed files with 65 additions and 38 deletions

View file

@ -2,8 +2,9 @@ package authentication
import (
// External
_ "git.gibonuddevalla.se/go/wrappederror"
werr "git.gibonuddevalla.se/go/wrappederror"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
@ -146,6 +147,14 @@ func (mngr *Manager) AuthenticationHandler(w http.ResponseWriter, r *http.Reques
data["uid"] = user.ID
data["login"] = user.Username
data["name"] = user.Name
data["cid"], err = mngr.NewClientUUID(user)
if err != nil {
mngr.log.Error("authentication", "error", err)
httpError(w, err)
return
}
token, err = mngr.GenerateToken(data)
if err != nil {
mngr.log.Error("authentication", "error", err)
@ -269,3 +278,31 @@ func (mngr *Manager) ChangePassword(username, currentPassword, newPassword strin
changed = (rowsAffected == 1)
return
} // }}}
func (mngr *Manager) NewClientUUID(user User) (clientUUID string, err error) { // {{{
// Each client session has its own UUID.
// Loop through until a unique one is established.
var proposedClientUUID string
var numSessions int
for {
proposedClientUUID = uuid.NewString()
row := mngr.db.QueryRow("SELECT COUNT(id) FROM public.client WHERE client_uuid = $1", proposedClientUUID)
err = row.Scan(&numSessions)
if err != nil {
err = werr.Wrap(err).WithData(proposedClientUUID)
return
}
if numSessions > 0 {
continue
}
_, err = mngr.db.Exec(`INSERT INTO public.client(user_id, client_uuid) VALUES($1, $2)`, user.ID, proposedClientUUID)
if err != nil {
err = werr.Wrap(err).WithData(proposedClientUUID)
return
}
clientUUID = proposedClientUUID
break
}
return
} // }}}