diff options
author | Joe Chen <jc@unknwon.io> | 2022-11-05 17:55:05 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-11-05 17:55:05 +0800 |
commit | fd798b4197dc53df872d20f5d10edb8d73c32386 (patch) | |
tree | e59c8e5881f2162e211850ede549a1f57df64515 /internal/db/users.go | |
parent | a66c90462da24a916ee62afcb5a1f79d06ed8399 (diff) |
refactor(db): migrate methods off `user.go` (#7228)
Diffstat (limited to 'internal/db/users.go')
-rw-r--r-- | internal/db/users.go | 32 |
1 files changed, 26 insertions, 6 deletions
diff --git a/internal/db/users.go b/internal/db/users.go index 146a65a4..f87dc28d 100644 --- a/internal/db/users.go +++ b/internal/db/users.go @@ -62,6 +62,8 @@ type UsersStore interface { GetByUsername(ctx context.Context, username string) (*User, error) // HasForkedRepository returns true if the user has forked given repository. HasForkedRepository(ctx context.Context, userID, repoID int64) bool + // IsUsernameUsed returns true if the given username has been used. + IsUsernameUsed(ctx context.Context, username string) bool // ListFollowers returns a list of users that are following the given user. // Results are paginated by given page and page size, and sorted by the time of // follow in descending order. @@ -231,11 +233,8 @@ func (db *users) Create(ctx context.Context, username, email string, opts Create return nil, err } - _, err = db.GetByUsername(ctx, username) - if err == nil { + if db.IsUsernameUsed(ctx, username) { return nil, ErrUserAlreadyExist{args: errutil.Args{"name": username}} - } else if !IsErrUserNotExist(err) { - return nil, err } _, err = db.GetByEmail(ctx, email) @@ -262,11 +261,11 @@ func (db *users) Create(ctx context.Context, username, email string, opts Create AvatarEmail: email, } - user.Rands, err = GetUserSalt() + user.Rands, err = userutil.RandomSalt() if err != nil { return nil, err } - user.Salt, err = GetUserSalt() + user.Salt, err = userutil.RandomSalt() if err != nil { return nil, err } @@ -371,6 +370,17 @@ func (db *users) HasForkedRepository(ctx context.Context, userID, repoID int64) return count > 0 } +func (db *users) IsUsernameUsed(ctx context.Context, username string) bool { + if username == "" { + return false + } + return db.WithContext(ctx). + Select("id"). + Where("lower_name = ?", strings.ToLower(username)). + First(&User{}). + Error != gorm.ErrRecordNotFound +} + func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) { /* Equivalent SQL for PostgreSQL: @@ -569,6 +579,16 @@ func (u *User) DisplayName() string { return u.Name } +// NewGhostUser creates and returns a fake user for people who has deleted their +// accounts. +func NewGhostUser() *User { + return &User{ + ID: -1, + Name: "Ghost", + LowerName: "ghost", + } +} + // HomeURLPath returns the URL path to the user or organization home page. // // TODO(unknwon): This is also used in templates, which should be fixed by |