token based login: fix re-logins

This commit is contained in:
Lou Knauer 2022-07-26 13:50:54 +02:00
parent dc0bf80742
commit d4b1b32ca0
2 changed files with 25 additions and 13 deletions

View File

@ -2,6 +2,7 @@ package auth
import (
"crypto/ed25519"
"database/sql"
"encoding/base64"
"errors"
"fmt"
@ -106,8 +107,15 @@ func (ja *JWTAuthenticator) Login(user *User, rw http.ResponseWriter, r *http.Re
}
}
}
if rawrole, ok := claims["roles"].(string); ok {
roles = append(roles, rawrole)
}
if user == nil {
user, err = ja.auth.GetUser(sub)
if err != nil && err != sql.ErrNoRows {
return nil, err
} else if user == nil {
user = &User{
Username: sub,
Roles: roles,
@ -117,6 +125,7 @@ func (ja *JWTAuthenticator) Login(user *User, rw http.ResponseWriter, r *http.Re
return nil, err
}
}
}
user.Expiration = time.Unix(int64(exp), 0)
return user, nil

View File

@ -38,13 +38,8 @@ func (auth *Authentication) GetUser(username string) (*User, error) {
func (auth *Authentication) AddUser(user *User) error {
rolesJson, _ := json.Marshal(user.Roles)
password, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
cols := []string{"username", "password", "roles"}
vals := []interface{}{user.Username, string(password), string(rolesJson)}
cols := []string{"username", "roles"}
vals := []interface{}{user.Username, string(rolesJson)}
if user.Name != "" {
cols = append(cols, "name")
vals = append(vals, user.Name)
@ -53,6 +48,14 @@ func (auth *Authentication) AddUser(user *User) error {
cols = append(cols, "email")
vals = append(vals, user.Email)
}
if user.Password != "" {
password, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
cols = append(cols, "password")
vals = append(vals, string(password))
}
if _, err := sq.Insert("user").Columns(cols...).Values(vals...).RunWith(auth.db).Exec(); err != nil {
return err