From 07d19e6b772e967778c64952677582dfc24da364 Mon Sep 17 00:00:00 2001 From: surtur Date: Mon, 4 Sep 2023 20:27:14 +0200 Subject: [PATCH] go: handle demoting admin to regular-user level --- modules/user/user.go | 46 ++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/modules/user/user.go b/modules/user/user.go index 7098cb1..a5ee646 100644 --- a/modules/user/user.go +++ b/modules/user/user.go @@ -259,8 +259,9 @@ func UpdateUserByAdmin(ctx context.Context, client *ent.Client, id uuid.UUID, em var u int + switch { // ignore updates to password when user finished setting up (if not admin). - if !isAdmin && finishedSetup { + case !isAdmin && finishedSetup: u, err = client.User. Update().Where(user.IDEQ(id)). SetEmail(email). @@ -268,23 +269,44 @@ func UpdateUserByAdmin(ctx context.Context, client *ent.Client, id uuid.UUID, em SetIsAdmin(isAdmin). SetIsActive(active). Save(ctx) - } else { + + default: var digest []byte - digest, err = passwd.GetHash(password) - if err != nil { + if digest, err = passwd.GetHash(password); err != nil { log.Errorf("error hashing password: %s", err) return errors.New("could not hash password") } - u, err = client.User. - Update().Where(user.IDEQ(id)). - SetEmail(email). - SetUsername(username). - SetPassword(digest). - SetIsAdmin(isAdmin). - SetIsActive(active). - Save(ctx) + var origU *ent.User + + if origU, err = QueryUserByUUID(ctx, client, id); err != nil { + return err + } + + // handle a situation when an admin account is demoted to a + // regular-user level. reset last-login so as to force the user to go + // through the initial password change flow. + if origU.IsAdmin && !isAdmin { + u, err = client.User. + Update().Where(user.IDEQ(id)). + SetEmail(email). + SetUsername(username). + SetPassword(digest). + SetIsAdmin(isAdmin). + SetIsActive(active). + SetLastLogin(time.Unix(0, 0)). + Save(ctx) + } else { + u, err = client.User. + Update().Where(user.IDEQ(id)). + SetEmail(email). + SetUsername(username). + SetPassword(digest). + SetIsAdmin(isAdmin). + SetIsActive(active). + Save(ctx) + } } switch {