123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590 |
- package database
- 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 struct {
- db *gorm.DB
- }
- func newUsersStore(db *gorm.DB) *UsersStore {
- return &UsersStore{db: db}
- }
- type ErrLoginSourceMismatch struct {
- args errutil.Args
- }
- func IsErrLoginSourceMismatch(err error) bool {
- return errors.As(err, &ErrLoginSourceMismatch{})
- }
- func (err ErrLoginSourceMismatch) Error() string {
- return fmt.Sprintf("login source mismatch: %v", err.args)
- }
- func (s *UsersStore) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
- login = strings.ToLower(login)
- query := s.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 && !errors.Is(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 := newLoginSourcesStore(s.db, loadedLoginSourceFilesStore).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 s.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 (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
- err := isUsernameAllowed(newUsername)
- if err != nil {
- return err
- }
- if s.IsUsernameUsed(ctx, newUsername, userID) {
- return ErrUserAlreadyExist{
- args: errutil.Args{
- "name": newUsername,
- },
- }
- }
- user, err := s.GetByID(ctx, userID)
- if err != nil {
- return errors.Wrap(err, "get user")
- }
- return s.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 (s *UsersStore) Count(ctx context.Context) int64 {
- var count int64
- s.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 (s *UsersStore) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
- err := isUsernameAllowed(username)
- if err != nil {
- return nil, err
- }
- if s.IsUsernameUsed(ctx, username, 0) {
- return nil, ErrUserAlreadyExist{
- args: errutil.Args{
- "name": username,
- },
- }
- }
- email = strings.ToLower(strings.TrimSpace(email))
- _, err = s.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, s.db.WithContext(ctx).Create(user).Error
- }
- func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error {
- _ = os.Remove(userutil.CustomAvatarPath(userID))
- return s.db.WithContext(ctx).
- Model(&User{}).
- Where("id = ?", userID).
- Updates(map[string]any{
- "use_custom_avatar": false,
- "updated_unix": s.db.NowFunc().Unix(),
- }).
- Error
- }
- type ErrUserOwnRepos struct {
- args errutil.Args
- }
- func IsErrUserOwnRepos(err error) bool {
- return errors.As(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 {
- return errors.As(err, &ErrUserHasOrgs{})
- }
- func (err ErrUserHasOrgs) Error() string {
- return fmt.Sprintf("user still has organization membership: %v", err.args)
- }
- func (s *UsersStore) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
- user, err := s.GetByID(ctx, userID)
- if err != nil {
- if IsErrUserNotExist(err) {
- return nil
- }
- return errors.Wrap(err, "get user")
- }
-
-
- var count int64
- err = s.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 = s.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 = s.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(s.db).RewriteAuthorizedKeys()
- if err != nil {
- return errors.Wrap(err, `rewrite "authorized_keys" file`)
- }
- }
- return nil
- }
- func (s *UsersStore) DeleteInactivated() error {
- var userIDs []int64
- err := s.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 = s.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(s.db).RewriteAuthorizedKeys()
- if err != nil {
- return errors.Wrap(err, `rewrite "authorized_keys" file`)
- }
- return nil
- }
- func (*UsersStore) 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 (s *UsersStore) Follow(ctx context.Context, userID, followID int64) error {
- if userID == followID {
- return nil
- }
- return s.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 s.recountFollows(tx, userID, followID)
- })
- }
- func (s *UsersStore) Unfollow(ctx context.Context, userID, followID int64) error {
- if userID == followID {
- return nil
- }
- return s.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 s.recountFollows(tx, userID, followID)
- })
- }
- func (s *UsersStore) IsFollowing(ctx context.Context, userID, followID int64) bool {
- return s.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 {
- _, ok := errors.Cause(err).(ErrUserNotExist)
- return ok
- }
- func (err ErrUserNotExist) Error() string {
- return fmt.Sprintf("user does not exist: %v", err.args)
- }
- func (ErrUserNotExist) NotFound() bool {
- return true
- }
- func (s *UsersStore) 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 := s.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(s.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 (s *UsersStore) GetByID(ctx context.Context, id int64) (*User, error) {
- user := new(User)
- err := s.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 (s *UsersStore) GetByUsername(ctx context.Context, username string) (*User, error) {
- user := new(User)
- err := s.db.WithContext(ctx).Where("lower_name = ?", 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 (s *UsersStore) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
- user := new(User)
- err := s.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 (s *UsersStore) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
- emails := make([]string, 0, len(usernames))
- return emails, s.db.WithContext(ctx).
- Model(&User{}).
- Select("email").
- Where("lower_name IN (?) AND is_active = ?", usernames, true).
- Find(&emails).Error
- }
- func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserID int64) bool {
- if username == "" {
- return false
- }
- return s.db.WithContext(ctx).
- Select("id").
- Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserID).
- First(&User{}).
- Error != gorm.ErrRecordNotFound
- }
- func (s *UsersStore) List(ctx context.Context, page, pageSize int) ([]*User, error) {
- users := make([]*User, 0, pageSize)
- return users, s.db.WithContext(ctx).
- Where("type = ?", UserTypeIndividual).
- Limit(pageSize).Offset((page - 1) * pageSize).
- Order("id ASC").
- Find(&users).
- Error
- }
- func (s *UsersStore) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
-
- users := make([]*User, 0, pageSize)
- return users, s.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 (s *UsersStore) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
-
- users := make([]*User, 0, pageSize)
- return users, s.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 (s *UsersStore) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
- return searchUserByName(ctx, s.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 (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
- updates := map[string]any{
- "updated_unix": s.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 := s.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 s.db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
- }
- func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
- err := userutil.SaveAvatar(userID, avatar)
- if err != nil {
- return errors.Wrap(err, "save avatar")
- }
- return s.db.WithContext(ctx).
- Model(&User{}).
- Where("id = ?", userID).
- Updates(map[string]any{
- "use_custom_avatar": true,
- "updated_unix": s.db.NowFunc().Unix(),
- }).
- Error
- }
- func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
- email = strings.ToLower(strings.TrimSpace(email))
- _, err := s.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 s.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 (s *UsersStore) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
- tx := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
- if needsActivated {
- tx = tx.Where("is_activated = ?", true)
- }
- emailAddress := new(EmailAddress)
- err := tx.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 (s *UsersStore) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
- user, err := s.GetByID(ctx, userID)
- if err != nil {
- return nil, errors.Wrap(err, "get user")
- }
- var emails []*EmailAddress
- err = s.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 (s *UsersStore) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
- return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- err := s.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 (s *UsersStore) MarkEmailPrimary(ctx context.Context, userID int64, email string) error {
- var emailAddress EmailAddress
- err := s.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 := s.GetByID(ctx, userID)
- if err != nil {
- return errors.Wrap(err, "get user")
- }
- return s.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 (s *UsersStore) DeleteEmail(ctx context.Context, userID int64, email string) error {
- return s.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:"-"`
- Members []*User `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 Handle.Users().IsFollowing(context.TODO(), u.ID, followID)
- }
- func (u *User) IsUserOrgOwner(orgID int64) bool {
- return IsOrganizationOwner(orgID, u.ID)
- }
- func (u *User) IsPublicMember(orgID int64) bool {
- return IsPublicMembership(orgID, u.ID)
- }
- func (u *User) GetOrganizationCount() (int64, error) {
- return Handle.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"`
- }
|