From f40d44fa1c4abd3e9ad754bc9a92d62758816ea2 Mon Sep 17 00:00:00 2001 From: Yang Luo Date: Wed, 20 Sep 2023 22:45:00 +0800 Subject: [PATCH] Refactor out GenerateIdForNewUser() --- controllers/account.go | 19 ++++--------------- object/user.go | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/controllers/account.go b/controllers/account.go index 9856dc43..9ed2408d 100644 --- a/controllers/account.go +++ b/controllers/account.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "net/http" - "strconv" "strings" "github.com/casdoor/casdoor/form" @@ -119,20 +118,10 @@ func (c *ApiController) Signup() { } } - id := util.GenerateId() - if application.GetSignupItemRule("ID") == "Incremental" { - lastUser, err := object.GetLastUser(authForm.Organization) - if err != nil { - c.ResponseError(err.Error()) - return - } - - lastIdInt := -1 - if lastUser != nil { - lastIdInt = util.ParseInt(lastUser.Id) - } - - id = strconv.Itoa(lastIdInt + 1) + id, err := object.GenerateIdForNewUser(application) + if err != nil { + c.ResponseError(err.Error()) + return } username := authForm.Username diff --git a/object/user.go b/object/user.go index 7b37ec00..872efb0f 100644 --- a/object/user.go +++ b/object/user.go @@ -16,6 +16,7 @@ package object import ( "fmt" + "strconv" "strings" "github.com/casdoor/casdoor/conf" @@ -483,7 +484,7 @@ func GetMaskedUsers(users []*User, errs ...error) ([]*User, error) { return users, nil } -func GetLastUser(owner string) (*User, error) { +func getLastUser(owner string) (*User, error) { user := User{Owner: owner} existed, err := ormer.Engine.Desc("created_time", "id").Get(&user) if err != nil { @@ -900,3 +901,22 @@ func (user *User) IsGlobalAdmin() bool { return user.Owner == "built-in" } + +func GenerateIdForNewUser(application *Application) (string, error) { + if application.GetSignupItemRule("ID") != "Incremental" { + return util.GenerateId(), nil + } + + lastUser, err := getLastUser(application.Organization) + if err != nil { + return "", err + } + + lastUserId := -1 + if lastUser != nil { + lastUserId = util.ParseInt(lastUser.Id) + } + + res := strconv.Itoa(lastUserId + 1) + return res, nil +}