1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648 |
- package db
- import (
- "context"
- "database/sql"
- "fmt"
- "os"
- "strings"
- "time"
- "unicode/utf8"
- "github.com/go-macaron/binding"
- api "github.com/gogs/go-gogs-client"
- "github.com/pkg/errors"
- "gorm.io/gorm"
- log "unknwon.dev/clog/v2"
- "gogs.io/gogs/internal/auth"
- "gogs.io/gogs/internal/conf"
- "gogs.io/gogs/internal/cryptoutil"
- "gogs.io/gogs/internal/dbutil"
- "gogs.io/gogs/internal/errutil"
- "gogs.io/gogs/internal/markup"
- "gogs.io/gogs/internal/osutil"
- "gogs.io/gogs/internal/repoutil"
- "gogs.io/gogs/internal/strutil"
- "gogs.io/gogs/internal/tool"
- "gogs.io/gogs/internal/userutil"
- )
- type UsersStore interface {
-
-
-
-
-
-
-
-
-
-
-
- Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
-
-
-
-
-
- Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
-
-
- GetByEmail(ctx context.Context, email string) (*User, error)
-
-
- GetByID(ctx context.Context, id int64) (*User, error)
-
-
- GetByUsername(ctx context.Context, username string) (*User, error)
-
-
- GetByKeyID(ctx context.Context, keyID int64) (*User, error)
-
-
-
- GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error)
-
-
-
-
-
- SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error)
-
-
-
- IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool
-
-
-
-
- ChangeUsername(ctx context.Context, userID int64, newUsername string) error
-
- Update(ctx context.Context, userID int64, opts UpdateUserOptions) error
-
- UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
-
-
- DeleteCustomAvatar(ctx context.Context, userID int64) error
-
-
-
-
-
- DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error
-
- DeleteInactivated() error
-
-
- AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error
-
-
-
-
- GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error)
-
-
- ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error)
-
-
- MarkEmailActivated(ctx context.Context, userID int64, email string) error
-
-
-
- MarkEmailPrimary(ctx context.Context, userID int64, email string) error
-
- DeleteEmail(ctx context.Context, userID int64, email string) error
-
- Follow(ctx context.Context, userID, followID int64) error
-
- Unfollow(ctx context.Context, userID, followID int64) error
-
- IsFollowing(ctx context.Context, userID, followID int64) bool
-
-
-
- ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
-
-
-
- ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
-
-
- List(ctx context.Context, page, pageSize int) ([]*User, error)
-
- Count(ctx context.Context) int64
- }
- var Users UsersStore
- var _ UsersStore = (*users)(nil)
- type users struct {
- *gorm.DB
- }
- func NewUsersStore(db *gorm.DB) UsersStore {
- return &users{DB: db}
- }
- type ErrLoginSourceMismatch struct {
- args errutil.Args
- }
- func IsErrLoginSourceMismatch(err error) bool {
- _, ok := errors.Cause(err).(ErrLoginSourceMismatch)
- return ok
- }
- func (err ErrLoginSourceMismatch) Error() string {
- return fmt.Sprintf("login source mismatch: %v", err.args)
- }
- func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
- login = strings.ToLower(login)
- query := db.WithContext(ctx)
- if strings.Contains(login, "@") {
- query = query.Where("email = ?", login)
- } else {
- query = query.Where("lower_name = ?", login)
- }
- user := new(User)
- err := query.First(user).Error
- if err != nil && err != gorm.ErrRecordNotFound {
- return nil, errors.Wrap(err, "get user")
- }
- var authSourceID int64
- createNewUser := false
-
- if err == nil {
-
-
- if loginSourceID >= 0 && user.LoginSource != loginSourceID {
- return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
- }
-
- if user.IsLocal() {
- if userutil.ValidatePassword(user.Password, user.Salt, password) {
- return user, nil
- }
- return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login, "userID": user.ID}}
- }
- authSourceID = user.LoginSource
- } else {
-
- if loginSourceID <= 0 {
- return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
- }
- authSourceID = loginSourceID
- createNewUser = true
- }
- source, err := LoginSources.GetByID(ctx, authSourceID)
- if err != nil {
- return nil, errors.Wrap(err, "get login source")
- }
- if !source.IsActived {
- return nil, errors.Errorf("login source %d is not activated", source.ID)
- }
- extAccount, err := source.Provider.Authenticate(login, password)
- if err != nil {
- return nil, err
- }
- if !createNewUser {
- return user, nil
- }
-
- if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
- return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
- }
- return db.Create(ctx, extAccount.Name, extAccount.Email,
- CreateUserOptions{
- FullName: extAccount.FullName,
- LoginSource: authSourceID,
- LoginName: extAccount.Login,
- Location: extAccount.Location,
- Website: extAccount.Website,
- Activated: true,
- Admin: extAccount.Admin,
- },
- )
- }
- func (db *users) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
- err := isUsernameAllowed(newUsername)
- if err != nil {
- return err
- }
- if db.IsUsernameUsed(ctx, newUsername, userID) {
- return ErrUserAlreadyExist{
- args: errutil.Args{
- "name": newUsername,
- },
- }
- }
- user, err := db.GetByID(ctx, userID)
- if err != nil {
- return errors.Wrap(err, "get user")
- }
- return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- err := tx.Model(&User{}).
- Where("id = ?", user.ID).
- Updates(map[string]any{
- "lower_name": strings.ToLower(newUsername),
- "name": newUsername,
- "updated_unix": tx.NowFunc().Unix(),
- }).Error
- if err != nil {
- return errors.Wrap(err, "update user name")
- }
-
- if strings.EqualFold(user.Name, newUsername) {
- return nil
- }
-
- err = tx.Model(&PullRequest{}).
- Where("head_user_name = ?", user.LowerName).
- Update("head_user_name", strings.ToLower(newUsername)).
- Error
- if err != nil {
- return errors.Wrap(err, `update "pull_request.head_user_name"`)
- }
-
- rows, err := tx.Model(&Repository{}).Where("owner_id = ?", user.ID).Rows()
- if err != nil {
- return errors.Wrap(err, "iterate repositories")
- }
- defer func() { _ = rows.Close() }()
- for rows.Next() {
- var repo struct {
- ID int64
- }
- err = tx.ScanRows(rows, &repo)
- if err != nil {
- return errors.Wrap(err, "scan rows")
- }
- deleteRepoLocalCopy(repo.ID)
- RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
- }
- if err = rows.Err(); err != nil {
- return errors.Wrap(err, "check rows.Err")
- }
-
- userPath := repoutil.UserPath(user.Name)
- if osutil.IsExist(userPath) {
- newUserPath := repoutil.UserPath(newUsername)
- err = os.Rename(userPath, newUserPath)
- if err != nil {
- return errors.Wrap(err, "rename user directory")
- }
- }
- return nil
- })
- }
- func (db *users) Count(ctx context.Context) int64 {
- var count int64
- db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeIndividual).Count(&count)
- return count
- }
- type CreateUserOptions struct {
- FullName string
- Password string
- LoginSource int64
- LoginName string
- Location string
- Website string
- Activated bool
- Admin bool
- }
- type ErrUserAlreadyExist struct {
- args errutil.Args
- }
- func IsErrUserAlreadyExist(err error) bool {
- return errors.As(err, &ErrUserAlreadyExist{})
- }
- func (err ErrUserAlreadyExist) Error() string {
- return fmt.Sprintf("user already exists: %v", err.args)
- }
- type ErrEmailAlreadyUsed struct {
- args errutil.Args
- }
- func IsErrEmailAlreadyUsed(err error) bool {
- return errors.As(err, &ErrEmailAlreadyUsed{})
- }
- func (err ErrEmailAlreadyUsed) Email() string {
- email, ok := err.args["email"].(string)
- if ok {
- return email
- }
- return "<email not found>"
- }
- func (err ErrEmailAlreadyUsed) Error() string {
- return fmt.Sprintf("email has been used: %v", err.args)
- }
- func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
- err := isUsernameAllowed(username)
- if err != nil {
- return nil, err
- }
- if db.IsUsernameUsed(ctx, username, 0) {
- return nil, ErrUserAlreadyExist{
- args: errutil.Args{
- "name": username,
- },
- }
- }
- email = strings.ToLower(strings.TrimSpace(email))
- _, err = db.GetByEmail(ctx, email)
- if err == nil {
- return nil, ErrEmailAlreadyUsed{
- args: errutil.Args{
- "email": email,
- },
- }
- } else if !IsErrUserNotExist(err) {
- return nil, err
- }
- user := &User{
- LowerName: strings.ToLower(username),
- Name: username,
- FullName: opts.FullName,
- Email: email,
- Password: opts.Password,
- LoginSource: opts.LoginSource,
- LoginName: opts.LoginName,
- Location: opts.Location,
- Website: opts.Website,
- MaxRepoCreation: -1,
- IsActive: opts.Activated,
- IsAdmin: opts.Admin,
- Avatar: cryptoutil.MD5(email),
- AvatarEmail: email,
- }
- user.Rands, err = userutil.RandomSalt()
- if err != nil {
- return nil, err
- }
- user.Salt, err = userutil.RandomSalt()
- if err != nil {
- return nil, err
- }
- user.Password = userutil.EncodePassword(user.Password, user.Salt)
- return user, db.WithContext(ctx).Create(user).Error
- }
- func (db *users) DeleteCustomAvatar(ctx context.Context, userID int64) error {
- _ = os.Remove(userutil.CustomAvatarPath(userID))
- return db.WithContext(ctx).
- Model(&User{}).
- Where("id = ?", userID).
- Updates(map[string]any{
- "use_custom_avatar": false,
- "updated_unix": db.NowFunc().Unix(),
- }).
- Error
- }
- type ErrUserOwnRepos struct {
- args errutil.Args
- }
- func IsErrUserOwnRepos(err error) bool {
- return errors.As(errors.Cause(err), &ErrUserOwnRepos{})
- }
- func (err ErrUserOwnRepos) Error() string {
- return fmt.Sprintf("user still has repository ownership: %v", err.args)
- }
- type ErrUserHasOrgs struct {
- args errutil.Args
- }
- func IsErrUserHasOrgs(err error) bool {
- _, ok := errors.Cause(err).(ErrUserHasOrgs)
- return ok
- }
- func (err ErrUserHasOrgs) Error() string {
- return fmt.Sprintf("user still has organization membership: %v", err.args)
- }
- func (db *users) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
- user, err := db.GetByID(ctx, userID)
- if err != nil {
- if IsErrUserNotExist(err) {
- return nil
- }
- return errors.Wrap(err, "get user")
- }
-
-
- var count int64
- err = db.WithContext(ctx).Model(&Repository{}).Where("owner_id = ?", userID).Count(&count).Error
- if err != nil {
- return errors.Wrap(err, "count repositories")
- } else if count > 0 {
- return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
- }
- err = db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
- if err != nil {
- return errors.Wrap(err, "count organization membership")
- } else if count > 0 {
- return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
- }
- needsRewriteAuthorizedKeys := false
- err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
-
- err = tx.
- Table("repository").
- Where("id IN (?)", tx.
- Select("repo_id").
- Table("watch").
- Where("user_id = ?", userID),
- ).
- UpdateColumn("num_watches", gorm.Expr("num_watches - 1")).
- Error
- if err != nil {
- return errors.Wrap(err, `decrease "repository.num_watches"`)
- }
-
- err = tx.
- Table("repository").
- Where("id IN (?)", tx.
- Select("repo_id").
- Table("star").
- Where("uid = ?", userID),
- ).
- UpdateColumn("num_stars", gorm.Expr("num_stars - 1")).
- Error
- if err != nil {
- return errors.Wrap(err, `decrease "repository.num_stars"`)
- }
-
- err = tx.
- Table("user").
- Where("id IN (?)", tx.
- Select("follow_id").
- Table("follow").
- Where("user_id = ?", userID),
- ).
- UpdateColumn("num_followers", gorm.Expr("num_followers - 1")).
- Error
- if err != nil {
- return errors.Wrap(err, `decrease "user.num_followers"`)
- }
-
- err = tx.
- Table("user").
- Where("id IN (?)", tx.
- Select("user_id").
- Table("follow").
- Where("follow_id = ?", userID),
- ).
- UpdateColumn("num_following", gorm.Expr("num_following - 1")).
- Error
- if err != nil {
- return errors.Wrap(err, `decrease "user.num_following"`)
- }
- if !skipRewriteAuthorizedKeys {
-
- needsRewriteAuthorizedKeys = tx.Where("owner_id = ?", userID).First(&PublicKey{}).Error != gorm.ErrRecordNotFound
- }
- err = tx.Model(&Issue{}).Where("assignee_id = ?", userID).Update("assignee_id", 0).Error
- if err != nil {
- return errors.Wrap(err, "clear assignees")
- }
- for _, t := range []struct {
- table any
- where string
- }{
- {&Watch{}, "user_id = @userID"},
- {&Star{}, "uid = @userID"},
- {&Follow{}, "user_id = @userID OR follow_id = @userID"},
- {&PublicKey{}, "owner_id = @userID"},
- {&AccessToken{}, "uid = @userID"},
- {&Collaboration{}, "user_id = @userID"},
- {&Access{}, "user_id = @userID"},
- {&Action{}, "user_id = @userID"},
- {&IssueUser{}, "uid = @userID"},
- {&EmailAddress{}, "uid = @userID"},
- {&User{}, "id = @userID"},
- } {
- err = tx.Where(t.where, sql.Named("userID", userID)).Delete(t.table).Error
- if err != nil {
- return errors.Wrapf(err, "clean up table %T", t.table)
- }
- }
- return nil
- })
- if err != nil {
- return err
- }
- _ = os.RemoveAll(repoutil.UserPath(user.Name))
- _ = os.Remove(userutil.CustomAvatarPath(userID))
- if needsRewriteAuthorizedKeys {
- err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
- if err != nil {
- return errors.Wrap(err, `rewrite "authorized_keys" file`)
- }
- }
- return nil
- }
- func (db *users) DeleteInactivated() error {
- var userIDs []int64
- err := db.Model(&User{}).Where("is_active = ?", false).Pluck("id", &userIDs).Error
- if err != nil {
- return errors.Wrap(err, "get inactivated user IDs")
- }
- for _, userID := range userIDs {
- err = db.DeleteByID(context.Background(), userID, true)
- if err != nil {
-
- if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
- continue
- }
- return errors.Wrapf(err, "delete user with ID %d", userID)
- }
- }
- err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
- if err != nil {
- return errors.Wrap(err, `rewrite "authorized_keys" file`)
- }
- return nil
- }
- func (*users) recountFollows(tx *gorm.DB, userID, followID int64) error {
-
- err := tx.Model(&User{}).
- Where("id = ?", followID).
- Update(
- "num_followers",
- tx.Model(&Follow{}).Select("COUNT(*)").Where("follow_id = ?", followID),
- ).
- Error
- if err != nil {
- return errors.Wrap(err, `update "user.num_followers"`)
- }
-
- err = tx.Model(&User{}).
- Where("id = ?", userID).
- Update(
- "num_following",
- tx.Model(&Follow{}).Select("COUNT(*)").Where("user_id = ?", userID),
- ).
- Error
- if err != nil {
- return errors.Wrap(err, `update "user.num_following"`)
- }
- return nil
- }
- func (db *users) Follow(ctx context.Context, userID, followID int64) error {
- if userID == followID {
- return nil
- }
- return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- f := &Follow{
- UserID: userID,
- FollowID: followID,
- }
- result := tx.FirstOrCreate(f, f)
- if result.Error != nil {
- return errors.Wrap(result.Error, "upsert")
- } else if result.RowsAffected <= 0 {
- return nil
- }
- return db.recountFollows(tx, userID, followID)
- })
- }
- func (db *users) Unfollow(ctx context.Context, userID, followID int64) error {
- if userID == followID {
- return nil
- }
- return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- err := tx.Where("user_id = ? AND follow_id = ?", userID, followID).Delete(&Follow{}).Error
- if err != nil {
- return errors.Wrap(err, "delete")
- }
- return db.recountFollows(tx, userID, followID)
- })
- }
- func (db *users) IsFollowing(ctx context.Context, userID, followID int64) bool {
- return db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
- }
- var _ errutil.NotFound = (*ErrUserNotExist)(nil)
- type ErrUserNotExist struct {
- args errutil.Args
- }
- func IsErrUserNotExist(err error) bool {
- return errors.As(err, &ErrUserNotExist{})
- }
- func (err ErrUserNotExist) Error() string {
- return fmt.Sprintf("user does not exist: %v", err.args)
- }
- func (ErrUserNotExist) NotFound() bool {
- return true
- }
- func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
- if email == "" {
- return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
- }
- email = strings.ToLower(email)
-
- user := new(User)
- err := db.WithContext(ctx).
- Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
- Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
- Where(db.
- Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
- Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
- ).
- First(&user).
- Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
- }
- return nil, err
- }
- return user, nil
- }
- func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
- user := new(User)
- err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
- }
- return nil, err
- }
- return user, nil
- }
- func getUserByUsername(ctx context.Context, db *gorm.DB, userType UserType, username string) (*User, error) {
- if username == "" {
- return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
- }
- user := new(User)
- err := db.WithContext(ctx).
- Where("type = ? AND lower_name = ?", userType, strings.ToLower(username)).
- First(user).
- Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
- }
- return nil, err
- }
- return user, nil
- }
- func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
- return getUserByUsername(ctx, db.DB, UserTypeIndividual, username)
- }
- func (db *users) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
- user := new(User)
- err := db.WithContext(ctx).
- Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
- Where("public_key.id = ?", keyID).
- First(user).
- Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
- }
- return nil, err
- }
- return user, nil
- }
- func (db *users) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
- emails := make([]string, 0, len(usernames))
- return emails, db.WithContext(ctx).
- Model(&User{}).
- Select("email").
- Where("lower_name IN (?) AND is_active = ?", usernames, true).
- Find(&emails).Error
- }
- func (db *users) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
- if username == "" {
- return false
- }
- err := db.WithContext(ctx).
- Select("id").
- Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
- First(&User{}).
- Error
- return !errors.Is(err, gorm.ErrRecordNotFound)
- }
- func (db *users) List(ctx context.Context, page, pageSize int) ([]*User, error) {
- users := make([]*User, 0, pageSize)
- return users, db.WithContext(ctx).
- Where("type = ?", UserTypeIndividual).
- Limit(pageSize).Offset((page - 1) * pageSize).
- Order("id ASC").
- Find(&users).
- Error
- }
- func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
-
- users := make([]*User, 0, pageSize)
- return users, db.WithContext(ctx).
- Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
- Where("follow.follow_id = ?", userID).
- Limit(pageSize).Offset((page - 1) * pageSize).
- Order("follow.id DESC").
- Find(&users).
- Error
- }
- func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
-
- users := make([]*User, 0, pageSize)
- return users, db.WithContext(ctx).
- Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
- Where("follow.user_id = ?", userID).
- Limit(pageSize).Offset((page - 1) * pageSize).
- Order("follow.id DESC").
- Find(&users).
- Error
- }
- func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
- if keyword == "" {
- return []*User{}, 0, nil
- }
- keyword = "%" + strings.ToLower(keyword) + "%"
- tx := db.WithContext(ctx).
- Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
- var count int64
- err := tx.Model(&User{}).Count(&count).Error
- if err != nil {
- return nil, 0, errors.Wrap(err, "count")
- }
- users := make([]*User, 0, pageSize)
- return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
- }
- func (db *users) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
- return searchUserByName(ctx, db.DB, UserTypeIndividual, keyword, page, pageSize, orderBy)
- }
- type UpdateUserOptions struct {
- LoginSource *int64
- LoginName *string
- Password *string
-
- GenerateNewRands bool
- FullName *string
- Email *string
- Website *string
- Location *string
- Description *string
- MaxRepoCreation *int
- LastRepoVisibility *bool
- IsActivated *bool
- IsAdmin *bool
- AllowGitHook *bool
- AllowImportLocal *bool
- ProhibitLogin *bool
- Avatar *string
- AvatarEmail *string
- }
- func (db *users) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
- updates := map[string]any{
- "updated_unix": db.NowFunc().Unix(),
- }
- if opts.LoginSource != nil {
- updates["login_source"] = *opts.LoginSource
- }
- if opts.LoginName != nil {
- updates["login_name"] = *opts.LoginName
- }
- if opts.Password != nil {
- salt, err := userutil.RandomSalt()
- if err != nil {
- return errors.Wrap(err, "generate salt")
- }
- updates["salt"] = salt
- updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
- opts.GenerateNewRands = true
- }
- if opts.GenerateNewRands {
- rands, err := userutil.RandomSalt()
- if err != nil {
- return errors.Wrap(err, "generate rands")
- }
- updates["rands"] = rands
- }
- if opts.FullName != nil {
- updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
- }
- if opts.Email != nil {
- _, err := db.GetByEmail(ctx, *opts.Email)
- if err == nil {
- return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
- } else if !IsErrUserNotExist(err) {
- return errors.Wrap(err, "check email")
- }
- updates["email"] = *opts.Email
- }
- if opts.Website != nil {
- updates["website"] = strutil.Truncate(*opts.Website, 255)
- }
- if opts.Location != nil {
- updates["location"] = strutil.Truncate(*opts.Location, 255)
- }
- if opts.Description != nil {
- updates["description"] = strutil.Truncate(*opts.Description, 255)
- }
- if opts.MaxRepoCreation != nil {
- if *opts.MaxRepoCreation < -1 {
- *opts.MaxRepoCreation = -1
- }
- updates["max_repo_creation"] = *opts.MaxRepoCreation
- }
- if opts.LastRepoVisibility != nil {
- updates["last_repo_visibility"] = *opts.LastRepoVisibility
- }
- if opts.IsActivated != nil {
- updates["is_active"] = *opts.IsActivated
- }
- if opts.IsAdmin != nil {
- updates["is_admin"] = *opts.IsAdmin
- }
- if opts.AllowGitHook != nil {
- updates["allow_git_hook"] = *opts.AllowGitHook
- }
- if opts.AllowImportLocal != nil {
- updates["allow_import_local"] = *opts.AllowImportLocal
- }
- if opts.ProhibitLogin != nil {
- updates["prohibit_login"] = *opts.ProhibitLogin
- }
- if opts.Avatar != nil {
- updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
- }
- if opts.AvatarEmail != nil {
- updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
- }
- return db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
- }
- func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
- err := userutil.SaveAvatar(userID, avatar)
- if err != nil {
- return errors.Wrap(err, "save avatar")
- }
- return db.WithContext(ctx).
- Model(&User{}).
- Where("id = ?", userID).
- Updates(map[string]any{
- "use_custom_avatar": true,
- "updated_unix": db.NowFunc().Unix(),
- }).
- Error
- }
- func (db *users) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
- email = strings.ToLower(strings.TrimSpace(email))
- _, err := db.GetByEmail(ctx, email)
- if err == nil {
- return ErrEmailAlreadyUsed{
- args: errutil.Args{
- "email": email,
- },
- }
- } else if !IsErrUserNotExist(err) {
- return errors.Wrap(err, "check user by email")
- }
- return db.WithContext(ctx).Create(
- &EmailAddress{
- UserID: userID,
- Email: email,
- IsActivated: isActivated,
- },
- ).Error
- }
- var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
- type ErrEmailNotExist struct {
- args errutil.Args
- }
- func IsErrEmailAddressNotExist(err error) bool {
- _, ok := errors.Cause(err).(ErrEmailNotExist)
- return ok
- }
- func (err ErrEmailNotExist) Error() string {
- return fmt.Sprintf("email address does not exist: %v", err.args)
- }
- func (ErrEmailNotExist) NotFound() bool {
- return true
- }
- func (db *users) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
- conds := db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
- if needsActivated {
- conds.Where("is_activated = ?", true)
- }
- emailAddress := new(EmailAddress)
- err := conds.First(emailAddress).Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrEmailNotExist{
- args: errutil.Args{
- "email": email,
- },
- }
- }
- return nil, err
- }
- return emailAddress, nil
- }
- func (db *users) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
- user, err := db.GetByID(ctx, userID)
- if err != nil {
- return nil, errors.Wrap(err, "get user")
- }
- var emails []*EmailAddress
- err = db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&emails).Error
- if err != nil {
- return nil, errors.Wrap(err, "list emails")
- }
- isPrimaryFound := false
- for _, email := range emails {
- if email.Email == user.Email {
- isPrimaryFound = true
- email.IsPrimary = true
- break
- }
- }
-
-
- if !isPrimaryFound {
- emails = append(emails, &EmailAddress{
- Email: user.Email,
- IsActivated: user.IsActive,
- IsPrimary: true,
- })
- }
- return emails, nil
- }
- func (db *users) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
- return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- err := db.WithContext(ctx).
- Model(&EmailAddress{}).
- Where("uid = ? AND email = ?", userID, email).
- Update("is_activated", true).
- Error
- if err != nil {
- return errors.Wrap(err, "mark email activated")
- }
- return NewUsersStore(tx).Update(ctx, userID, UpdateUserOptions{GenerateNewRands: true})
- })
- }
- type ErrEmailNotVerified struct {
- args errutil.Args
- }
- func IsErrEmailNotVerified(err error) bool {
- _, ok := errors.Cause(err).(ErrEmailNotVerified)
- return ok
- }
- func (err ErrEmailNotVerified) Error() string {
- return fmt.Sprintf("email has not been verified: %v", err.args)
- }
- func (db *users) MarkEmailPrimary(ctx context.Context, userID int64, email string) error {
- var emailAddress EmailAddress
- err := db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return ErrEmailNotExist{args: errutil.Args{"email": email}}
- }
- return errors.Wrap(err, "get email address")
- }
- if !emailAddress.IsActivated {
- return ErrEmailNotVerified{args: errutil.Args{"email": email}}
- }
- user, err := db.GetByID(ctx, userID)
- if err != nil {
- return errors.Wrap(err, "get user")
- }
- return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
-
- err = tx.FirstOrCreate(
- &EmailAddress{
- UserID: user.ID,
- Email: user.Email,
- IsActivated: user.IsActive,
- },
- &EmailAddress{
- UserID: user.ID,
- Email: user.Email,
- },
- ).Error
- if err != nil {
- return errors.Wrap(err, "upsert former primary email address")
- }
- return tx.Model(&User{}).
- Where("id = ?", user.ID).
- Updates(map[string]any{
- "email": email,
- "updated_unix": tx.NowFunc().Unix(),
- },
- ).Error
- })
- }
- func (db *users) DeleteEmail(ctx context.Context, userID int64, email string) error {
- return db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).Delete(&EmailAddress{}).Error
- }
- type UserType int
- const (
- UserTypeIndividual UserType = iota
- UserTypeOrganization
- )
- type User struct {
- ID int64 `gorm:"primaryKey"`
- LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
- Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
- FullName string
-
- Email string `xorm:"NOT NULL" gorm:"not null"`
- Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
- LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
- LoginName string
- Type UserType
- Location string
- Website string
- Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
- Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
- Created time.Time `xorm:"-" gorm:"-" json:"-"`
- CreatedUnix int64
- Updated time.Time `xorm:"-" gorm:"-" json:"-"`
- UpdatedUnix int64
-
- LastRepoVisibility bool
-
- MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
-
- IsActive bool
- IsAdmin bool
- AllowGitHook bool
- AllowImportLocal bool
- ProhibitLogin bool
-
- Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
- AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
- UseCustomAvatar bool
-
- NumFollowers int
- NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
- NumStars int
- NumRepos int
-
- Description string
- NumTeams int
- NumMembers int
- Teams []*Team `xorm:"-" gorm:"-" json:"-"`
- }
- func (u *User) BeforeCreate(tx *gorm.DB) error {
- if u.CreatedUnix == 0 {
- u.CreatedUnix = tx.NowFunc().Unix()
- u.UpdatedUnix = u.CreatedUnix
- }
- return nil
- }
- func (u *User) AfterFind(_ *gorm.DB) error {
- u.FullName = markup.Sanitize(u.FullName)
- u.Created = time.Unix(u.CreatedUnix, 0).Local()
- u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
- return nil
- }
- func (u *User) IsLocal() bool {
- return u.LoginSource <= 0
- }
- func (u *User) IsOrganization() bool {
- return u.Type == UserTypeOrganization
- }
- func (u *User) APIFormat() *api.User {
- return &api.User{
- ID: u.ID,
- UserName: u.Name,
- Login: u.Name,
- FullName: u.FullName,
- Email: u.Email,
- AvatarUrl: u.AvatarURL(),
- }
- }
- func (u *User) maxNumRepos() int {
- if u.MaxRepoCreation <= -1 {
- return conf.Repository.MaxCreationLimit
- }
- return u.MaxRepoCreation
- }
- func (u *User) canCreateRepo() bool {
- return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
- }
- func (u *User) CanCreateOrganization() bool {
- return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
- }
- func (u *User) CanEditGitHook() bool {
- return u.IsAdmin || u.AllowGitHook
- }
- func (u *User) CanImportLocal() bool {
- return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
- }
- func (u *User) DisplayName() string {
- if len(u.FullName) > 0 {
- return u.FullName
- }
- return u.Name
- }
- func (u *User) HomeURLPath() string {
- return conf.Server.Subpath + "/" + u.Name
- }
- func (u *User) HTMLURL() string {
- return conf.Server.ExternalURL + u.Name
- }
- func (u *User) AvatarURLPath() string {
- defaultURLPath := conf.UserDefaultAvatarURLPath()
- if u.ID <= 0 {
- return defaultURLPath
- }
- hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
- switch {
- case u.UseCustomAvatar:
- if !hasCustomAvatar {
- return defaultURLPath
- }
- return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
- case conf.Picture.DisableGravatar:
- if !hasCustomAvatar {
- if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
- log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
- }
- }
- return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
- }
- return tool.AvatarLink(u.AvatarEmail)
- }
- func (u *User) AvatarURL() string {
- link := u.AvatarURLPath()
- if link[0] == '/' && link[1] != '/' {
- return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
- }
- return link
- }
- func (u *User) IsFollowing(followID int64) bool {
- return Users.IsFollowing(context.TODO(), u.ID, followID)
- }
- func (u *User) IsUserOrgOwner(orgID int64) bool {
- return Organizations.IsOwnedBy(context.TODO(), orgID, u.ID)
- }
- func (u *User) IsPublicMember(orgID int64) bool {
- _, public := Organizations.HasMember(context.TODO(), orgID, u.ID)
- return public
- }
- func (u *User) GetOrganizationCount() (int64, error) {
- return Organizations.CountByUser(context.TODO(), u.ID)
- }
- func (u *User) ShortName(length int) string {
- return strutil.Ellipsis(u.Name, length)
- }
- func NewGhostUser() *User {
- return &User{
- ID: -1,
- Name: "Ghost",
- LowerName: "ghost",
- }
- }
- var (
- reservedUsernames = map[string]struct{}{
- "-": {},
- "explore": {},
- "create": {},
- "assets": {},
- "css": {},
- "img": {},
- "js": {},
- "less": {},
- "plugins": {},
- "debug": {},
- "raw": {},
- "install": {},
- "api": {},
- "avatar": {},
- "user": {},
- "org": {},
- "help": {},
- "stars": {},
- "issues": {},
- "pulls": {},
- "commits": {},
- "repo": {},
- "template": {},
- "admin": {},
- "new": {},
- ".": {},
- "..": {},
- }
- reservedUsernamePatterns = []string{"*.keys"}
- )
- type ErrNameNotAllowed struct {
- args errutil.Args
- }
- func IsErrNameNotAllowed(err error) bool {
- _, ok := errors.Cause(err).(ErrNameNotAllowed)
- return ok
- }
- func (err ErrNameNotAllowed) Value() string {
- val, ok := err.args["name"].(string)
- if ok {
- return val
- }
- val, ok = err.args["pattern"].(string)
- if ok {
- return val
- }
- return "<value not found>"
- }
- func (err ErrNameNotAllowed) Error() string {
- return fmt.Sprintf("name is not allowed: %v", err.args)
- }
- func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
- name = strings.TrimSpace(strings.ToLower(name))
- if utf8.RuneCountInString(name) == 0 {
- return ErrNameNotAllowed{
- args: errutil.Args{
- "reason": "empty name",
- },
- }
- }
- if _, ok := names[name]; ok {
- return ErrNameNotAllowed{
- args: errutil.Args{
- "reason": "reserved",
- "name": name,
- },
- }
- }
- for _, pattern := range patterns {
- if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
- (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
- return ErrNameNotAllowed{
- args: errutil.Args{
- "reason": "reserved",
- "pattern": pattern,
- },
- }
- }
- }
- return nil
- }
- func isUsernameAllowed(name string) error {
- return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
- }
- type EmailAddress struct {
- ID int64 `gorm:"primaryKey"`
- UserID int64 `xorm:"uid INDEX NOT NULL" gorm:"column:uid;index;uniqueIndex:email_address_user_email_unique;not null"`
- Email string `xorm:"UNIQUE NOT NULL" gorm:"uniqueIndex:email_address_user_email_unique;not null;size:254"`
- IsActivated bool `gorm:"not null;default:FALSE"`
- IsPrimary bool `xorm:"-" gorm:"-" json:"-"`
- }
- type Follow struct {
- ID int64 `gorm:"primaryKey"`
- UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
- FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
- }
|