user.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "fmt"
  12. "image"
  13. _ "image/jpeg"
  14. "image/png"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/nfnt/resize"
  21. "github.com/unknwon/com"
  22. "golang.org/x/crypto/pbkdf2"
  23. log "unknwon.dev/clog/v2"
  24. "xorm.io/xorm"
  25. "github.com/gogs/git-module"
  26. api "github.com/gogs/go-gogs-client"
  27. "gogs.io/gogs/internal/avatar"
  28. "gogs.io/gogs/internal/conf"
  29. "gogs.io/gogs/internal/db/errors"
  30. "gogs.io/gogs/internal/errutil"
  31. "gogs.io/gogs/internal/strutil"
  32. "gogs.io/gogs/internal/tool"
  33. )
  34. // USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
  35. const USER_AVATAR_URL_PREFIX = "avatars"
  36. type UserType int
  37. const (
  38. UserIndividual UserType = iota // Historic reason to make it starts at 0.
  39. UserOrganization
  40. )
  41. // User represents the object of individual and member of organization.
  42. type User struct {
  43. ID int64 `gorm:"primaryKey"`
  44. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  45. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  46. FullName string
  47. // Email is the primary email address (to be used for communication)
  48. Email string `xorm:"NOT NULL" gorm:"not null"`
  49. Passwd string `xorm:"NOT NULL" gorm:"not null"`
  50. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  51. LoginName string
  52. Type UserType
  53. OwnedOrgs []*User `xorm:"-" gorm:"-" json:"-"`
  54. Orgs []*User `xorm:"-" gorm:"-" json:"-"`
  55. Repos []*Repository `xorm:"-" gorm:"-" json:"-"`
  56. Location string
  57. Website string
  58. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  59. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  60. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  61. CreatedUnix int64
  62. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  63. UpdatedUnix int64
  64. // Remember visibility choice for convenience, true for private
  65. LastRepoVisibility bool
  66. // Maximum repository creation limit, -1 means use global default
  67. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  68. // Permissions
  69. IsActive bool // Activate primary email
  70. IsAdmin bool
  71. AllowGitHook bool
  72. AllowImportLocal bool // Allow migrate repository by local path
  73. ProhibitLogin bool
  74. // Avatar
  75. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  76. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  77. UseCustomAvatar bool
  78. // Counters
  79. NumFollowers int
  80. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  81. NumStars int
  82. NumRepos int
  83. // For organization
  84. Description string
  85. NumTeams int
  86. NumMembers int
  87. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  88. Members []*User `xorm:"-" gorm:"-" json:"-"`
  89. }
  90. func (u *User) BeforeInsert() {
  91. u.CreatedUnix = time.Now().Unix()
  92. u.UpdatedUnix = u.CreatedUnix
  93. }
  94. func (u *User) BeforeUpdate() {
  95. if u.MaxRepoCreation < -1 {
  96. u.MaxRepoCreation = -1
  97. }
  98. u.UpdatedUnix = time.Now().Unix()
  99. }
  100. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  101. switch colName {
  102. case "created_unix":
  103. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  104. case "updated_unix":
  105. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  106. }
  107. }
  108. func (u *User) APIFormat() *api.User {
  109. return &api.User{
  110. ID: u.ID,
  111. UserName: u.Name,
  112. Login: u.Name,
  113. FullName: u.FullName,
  114. Email: u.Email,
  115. AvatarUrl: u.AvatarLink(),
  116. }
  117. }
  118. func (u *User) RepoCreationNum() int {
  119. if u.MaxRepoCreation <= -1 {
  120. return conf.Repository.MaxCreationLimit
  121. }
  122. return u.MaxRepoCreation
  123. }
  124. func (u *User) CanCreateRepo() bool {
  125. if u.MaxRepoCreation <= -1 {
  126. if conf.Repository.MaxCreationLimit <= -1 {
  127. return true
  128. }
  129. return u.NumRepos < conf.Repository.MaxCreationLimit
  130. }
  131. return u.NumRepos < u.MaxRepoCreation
  132. }
  133. func (u *User) CanCreateOrganization() bool {
  134. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  135. }
  136. // CanEditGitHook returns true if user can edit Git hooks.
  137. func (u *User) CanEditGitHook() bool {
  138. return u.IsAdmin || u.AllowGitHook
  139. }
  140. // CanImportLocal returns true if user can migrate repository by local path.
  141. func (u *User) CanImportLocal() bool {
  142. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  143. }
  144. // DashboardLink returns the user dashboard page link.
  145. func (u *User) DashboardLink() string {
  146. if u.IsOrganization() {
  147. return conf.Server.Subpath + "/org/" + u.Name + "/dashboard/"
  148. }
  149. return conf.Server.Subpath + "/"
  150. }
  151. // HomeLink returns the user or organization home page link.
  152. func (u *User) HomeLink() string {
  153. return conf.Server.Subpath + "/" + u.Name
  154. }
  155. func (u *User) HTMLURL() string {
  156. return conf.Server.ExternalURL + u.Name
  157. }
  158. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  159. func (u *User) GenerateEmailActivateCode(email string) string {
  160. code := tool.CreateTimeLimitCode(
  161. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  162. conf.Auth.ActivateCodeLives, nil)
  163. // Add tail hex username
  164. code += hex.EncodeToString([]byte(u.LowerName))
  165. return code
  166. }
  167. // GenerateActivateCode generates an activate code based on user information.
  168. func (u *User) GenerateActivateCode() string {
  169. return u.GenerateEmailActivateCode(u.Email)
  170. }
  171. // CustomAvatarPath returns user custom avatar file path.
  172. func (u *User) CustomAvatarPath() string {
  173. return filepath.Join(conf.Picture.AvatarUploadPath, com.ToStr(u.ID))
  174. }
  175. // GenerateRandomAvatar generates a random avatar for user.
  176. func (u *User) GenerateRandomAvatar() error {
  177. seed := u.Email
  178. if seed == "" {
  179. seed = u.Name
  180. }
  181. img, err := avatar.RandomImage([]byte(seed))
  182. if err != nil {
  183. return fmt.Errorf("RandomImage: %v", err)
  184. }
  185. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  186. return fmt.Errorf("MkdirAll: %v", err)
  187. }
  188. fw, err := os.Create(u.CustomAvatarPath())
  189. if err != nil {
  190. return fmt.Errorf("Create: %v", err)
  191. }
  192. defer fw.Close()
  193. if err = png.Encode(fw, img); err != nil {
  194. return fmt.Errorf("Encode: %v", err)
  195. }
  196. log.Info("New random avatar created: %d", u.ID)
  197. return nil
  198. }
  199. // RelAvatarLink returns relative avatar link to the site domain,
  200. // which includes app sub-url as prefix. However, it is possible
  201. // to return full URL if user enables Gravatar-like service.
  202. func (u *User) RelAvatarLink() string {
  203. defaultImgUrl := conf.Server.Subpath + "/img/avatar_default.png"
  204. if u.ID == -1 {
  205. return defaultImgUrl
  206. }
  207. switch {
  208. case u.UseCustomAvatar:
  209. if !com.IsExist(u.CustomAvatarPath()) {
  210. return defaultImgUrl
  211. }
  212. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  213. case conf.Picture.DisableGravatar:
  214. if !com.IsExist(u.CustomAvatarPath()) {
  215. if err := u.GenerateRandomAvatar(); err != nil {
  216. log.Error("GenerateRandomAvatar: %v", err)
  217. }
  218. }
  219. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  220. }
  221. return tool.AvatarLink(u.AvatarEmail)
  222. }
  223. // AvatarLink returns user avatar absolute link.
  224. func (u *User) AvatarLink() string {
  225. link := u.RelAvatarLink()
  226. if link[0] == '/' && link[1] != '/' {
  227. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  228. }
  229. return link
  230. }
  231. // User.GetFollowers returns range of user's followers.
  232. func (u *User) GetFollowers(page int) ([]*User, error) {
  233. users := make([]*User, 0, ItemsPerPage)
  234. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  235. if conf.UsePostgreSQL {
  236. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  237. } else {
  238. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  239. }
  240. return users, sess.Find(&users)
  241. }
  242. func (u *User) IsFollowing(followID int64) bool {
  243. return IsFollowing(u.ID, followID)
  244. }
  245. // GetFollowing returns range of user's following.
  246. func (u *User) GetFollowing(page int) ([]*User, error) {
  247. users := make([]*User, 0, ItemsPerPage)
  248. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  249. if conf.UsePostgreSQL {
  250. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  251. } else {
  252. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  253. }
  254. return users, sess.Find(&users)
  255. }
  256. // NewGitSig generates and returns the signature of given user.
  257. func (u *User) NewGitSig() *git.Signature {
  258. return &git.Signature{
  259. Name: u.DisplayName(),
  260. Email: u.Email,
  261. When: time.Now(),
  262. }
  263. }
  264. // EncodePassword encodes password to safe format.
  265. func (u *User) EncodePassword() {
  266. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  267. u.Passwd = fmt.Sprintf("%x", newPasswd)
  268. }
  269. // ValidatePassword checks if given password matches the one belongs to the user.
  270. func (u *User) ValidatePassword(passwd string) bool {
  271. newUser := &User{Passwd: passwd, Salt: u.Salt}
  272. newUser.EncodePassword()
  273. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  274. }
  275. // UploadAvatar saves custom avatar for user.
  276. // FIXME: split uploads to different subdirs in case we have massive number of users.
  277. func (u *User) UploadAvatar(data []byte) error {
  278. img, _, err := image.Decode(bytes.NewReader(data))
  279. if err != nil {
  280. return fmt.Errorf("decode image: %v", err)
  281. }
  282. _ = os.MkdirAll(conf.Picture.AvatarUploadPath, os.ModePerm)
  283. fw, err := os.Create(u.CustomAvatarPath())
  284. if err != nil {
  285. return fmt.Errorf("create custom avatar directory: %v", err)
  286. }
  287. defer fw.Close()
  288. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  289. if err = png.Encode(fw, m); err != nil {
  290. return fmt.Errorf("encode image: %v", err)
  291. }
  292. return nil
  293. }
  294. // DeleteAvatar deletes the user's custom avatar.
  295. func (u *User) DeleteAvatar() error {
  296. log.Trace("DeleteAvatar [%d]: %s", u.ID, u.CustomAvatarPath())
  297. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  298. return err
  299. }
  300. u.UseCustomAvatar = false
  301. return UpdateUser(u)
  302. }
  303. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  304. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  305. return Perms.Authorize(context.TODO(), u.ID, repo.ID, AccessModeAdmin,
  306. AccessModeOptions{
  307. OwnerID: repo.OwnerID,
  308. Private: repo.IsPrivate,
  309. },
  310. )
  311. }
  312. // IsWriterOfRepo returns true if user has write access to given repository.
  313. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  314. return Perms.Authorize(context.TODO(), u.ID, repo.ID, AccessModeWrite,
  315. AccessModeOptions{
  316. OwnerID: repo.OwnerID,
  317. Private: repo.IsPrivate,
  318. },
  319. )
  320. }
  321. // IsOrganization returns true if user is actually a organization.
  322. func (u *User) IsOrganization() bool {
  323. return u.Type == UserOrganization
  324. }
  325. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  326. func (u *User) IsUserOrgOwner(orgId int64) bool {
  327. return IsOrganizationOwner(orgId, u.ID)
  328. }
  329. // IsPublicMember returns true if user public his/her membership in give organization.
  330. func (u *User) IsPublicMember(orgId int64) bool {
  331. return IsPublicMembership(orgId, u.ID)
  332. }
  333. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  334. func (u *User) IsEnabledTwoFactor() bool {
  335. return TwoFactors.IsUserEnabled(context.TODO(), u.ID)
  336. }
  337. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  338. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  339. }
  340. // GetOrganizationCount returns count of membership of organization of user.
  341. func (u *User) GetOrganizationCount() (int64, error) {
  342. return u.getOrganizationCount(x)
  343. }
  344. // GetRepositories returns repositories that user owns, including private repositories.
  345. func (u *User) GetRepositories(page, pageSize int) (err error) {
  346. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  347. UserID: u.ID,
  348. Private: true,
  349. Page: page,
  350. PageSize: pageSize,
  351. })
  352. return err
  353. }
  354. // GetRepositories returns mirror repositories that user owns, including private repositories.
  355. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  356. return GetUserMirrorRepositories(u.ID)
  357. }
  358. // GetOwnedOrganizations returns all organizations that user owns.
  359. func (u *User) GetOwnedOrganizations() (err error) {
  360. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  361. return err
  362. }
  363. // GetOrganizations returns all organizations that user belongs to.
  364. func (u *User) GetOrganizations(showPrivate bool) error {
  365. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  366. if err != nil {
  367. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  368. }
  369. if len(orgIDs) == 0 {
  370. return nil
  371. }
  372. u.Orgs = make([]*User, 0, len(orgIDs))
  373. if err = x.Where("type = ?", UserOrganization).In("id", orgIDs).Find(&u.Orgs); err != nil {
  374. return err
  375. }
  376. return nil
  377. }
  378. // DisplayName returns full name if it's not empty,
  379. // returns username otherwise.
  380. func (u *User) DisplayName() string {
  381. if len(u.FullName) > 0 {
  382. return u.FullName
  383. }
  384. return u.Name
  385. }
  386. func (u *User) ShortName(length int) string {
  387. return strutil.Ellipsis(u.Name, length)
  388. }
  389. // IsMailable checks if a user is eligible
  390. // to receive emails.
  391. func (u *User) IsMailable() bool {
  392. return u.IsActive
  393. }
  394. // IsUserExist checks if given user name exist,
  395. // the user name should be noncased unique.
  396. // If uid is presented, then check will rule out that one,
  397. // it is used when update a user name in settings page.
  398. func IsUserExist(uid int64, name string) (bool, error) {
  399. if name == "" {
  400. return false, nil
  401. }
  402. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  403. }
  404. // GetUserSalt returns a random user salt token.
  405. func GetUserSalt() (string, error) {
  406. return strutil.RandomChars(10)
  407. }
  408. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  409. func NewGhostUser() *User {
  410. return &User{
  411. ID: -1,
  412. Name: "Ghost",
  413. LowerName: "ghost",
  414. }
  415. }
  416. var (
  417. reservedUsernames = []string{"-", "explore", "create", "assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  418. reservedUserPatterns = []string{"*.keys"}
  419. )
  420. type ErrNameNotAllowed struct {
  421. args errutil.Args
  422. }
  423. func IsErrNameNotAllowed(err error) bool {
  424. _, ok := err.(ErrNameNotAllowed)
  425. return ok
  426. }
  427. func (err ErrNameNotAllowed) Value() string {
  428. val, ok := err.args["name"].(string)
  429. if ok {
  430. return val
  431. }
  432. val, ok = err.args["pattern"].(string)
  433. if ok {
  434. return val
  435. }
  436. return "<value not found>"
  437. }
  438. func (err ErrNameNotAllowed) Error() string {
  439. return fmt.Sprintf("name is not allowed: %v", err.args)
  440. }
  441. // isNameAllowed checks if name is reserved or pattern of name is not allowed
  442. // based on given reserved names and patterns.
  443. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  444. func isNameAllowed(names, patterns []string, name string) error {
  445. name = strings.TrimSpace(strings.ToLower(name))
  446. if utf8.RuneCountInString(name) == 0 {
  447. return ErrNameNotAllowed{args: errutil.Args{"reason": "empty name"}}
  448. }
  449. for i := range names {
  450. if name == names[i] {
  451. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "name": name}}
  452. }
  453. }
  454. for _, pat := range patterns {
  455. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  456. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  457. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": pat}}
  458. }
  459. }
  460. return nil
  461. }
  462. // isUsernameAllowed return an error if given name is a reserved name or pattern for users.
  463. func isUsernameAllowed(name string) error {
  464. return isNameAllowed(reservedUsernames, reservedUserPatterns, name)
  465. }
  466. // CreateUser creates record of a new user.
  467. // Deprecated: Use Users.Create instead.
  468. func CreateUser(u *User) (err error) {
  469. if err = isUsernameAllowed(u.Name); err != nil {
  470. return err
  471. }
  472. isExist, err := IsUserExist(0, u.Name)
  473. if err != nil {
  474. return err
  475. } else if isExist {
  476. return ErrUserAlreadyExist{args: errutil.Args{"name": u.Name}}
  477. }
  478. u.Email = strings.ToLower(u.Email)
  479. isExist, err = IsEmailUsed(u.Email)
  480. if err != nil {
  481. return err
  482. } else if isExist {
  483. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  484. }
  485. u.LowerName = strings.ToLower(u.Name)
  486. u.AvatarEmail = u.Email
  487. u.Avatar = tool.HashEmail(u.AvatarEmail)
  488. if u.Rands, err = GetUserSalt(); err != nil {
  489. return err
  490. }
  491. if u.Salt, err = GetUserSalt(); err != nil {
  492. return err
  493. }
  494. u.EncodePassword()
  495. u.MaxRepoCreation = -1
  496. sess := x.NewSession()
  497. defer sess.Close()
  498. if err = sess.Begin(); err != nil {
  499. return err
  500. }
  501. if _, err = sess.Insert(u); err != nil {
  502. return err
  503. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  504. return err
  505. }
  506. return sess.Commit()
  507. }
  508. func countUsers(e Engine) int64 {
  509. count, _ := e.Where("type=0").Count(new(User))
  510. return count
  511. }
  512. // CountUsers returns number of users.
  513. func CountUsers() int64 {
  514. return countUsers(x)
  515. }
  516. // Users returns number of users in given page.
  517. func ListUsers(page, pageSize int) ([]*User, error) {
  518. users := make([]*User, 0, pageSize)
  519. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  520. }
  521. // parseUserFromCode returns user by username encoded in code.
  522. // It returns nil if code or username is invalid.
  523. func parseUserFromCode(code string) (user *User) {
  524. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  525. return nil
  526. }
  527. // Use tail hex username to query user
  528. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  529. if b, err := hex.DecodeString(hexStr); err == nil {
  530. if user, err = GetUserByName(string(b)); user != nil {
  531. return user
  532. } else if !IsErrUserNotExist(err) {
  533. log.Error("Failed to get user by name %q: %v", string(b), err)
  534. }
  535. }
  536. return nil
  537. }
  538. // verify active code when active account
  539. func VerifyUserActiveCode(code string) (user *User) {
  540. minutes := conf.Auth.ActivateCodeLives
  541. if user = parseUserFromCode(code); user != nil {
  542. // time limit code
  543. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  544. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  545. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  546. return user
  547. }
  548. }
  549. return nil
  550. }
  551. // verify active code when active account
  552. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  553. minutes := conf.Auth.ActivateCodeLives
  554. if user := parseUserFromCode(code); user != nil {
  555. // time limit code
  556. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  557. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  558. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  559. emailAddress := &EmailAddress{Email: email}
  560. if has, _ := x.Get(emailAddress); has {
  561. return emailAddress
  562. }
  563. }
  564. }
  565. return nil
  566. }
  567. // ChangeUserName changes all corresponding setting from old user name to new one.
  568. func ChangeUserName(u *User, newUserName string) (err error) {
  569. if err = isUsernameAllowed(newUserName); err != nil {
  570. return err
  571. }
  572. isExist, err := IsUserExist(0, newUserName)
  573. if err != nil {
  574. return err
  575. } else if isExist {
  576. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  577. }
  578. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  579. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  580. }
  581. // Delete all local copies of repositories and wikis the user owns.
  582. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  583. repo := bean.(*Repository)
  584. deleteRepoLocalCopy(repo)
  585. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  586. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  587. return nil
  588. }); err != nil {
  589. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  590. }
  591. // Rename or create user base directory
  592. baseDir := UserPath(u.Name)
  593. newBaseDir := UserPath(newUserName)
  594. if com.IsExist(baseDir) {
  595. return os.Rename(baseDir, newBaseDir)
  596. }
  597. return os.MkdirAll(newBaseDir, os.ModePerm)
  598. }
  599. func updateUser(e Engine, u *User) error {
  600. // Organization does not need email
  601. if !u.IsOrganization() {
  602. u.Email = strings.ToLower(u.Email)
  603. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  604. if err != nil {
  605. return err
  606. } else if has {
  607. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  608. }
  609. if u.AvatarEmail == "" {
  610. u.AvatarEmail = u.Email
  611. }
  612. u.Avatar = tool.HashEmail(u.AvatarEmail)
  613. }
  614. u.LowerName = strings.ToLower(u.Name)
  615. u.Location = tool.TruncateString(u.Location, 255)
  616. u.Website = tool.TruncateString(u.Website, 255)
  617. u.Description = tool.TruncateString(u.Description, 255)
  618. _, err := e.ID(u.ID).AllCols().Update(u)
  619. return err
  620. }
  621. // UpdateUser updates user's information.
  622. func UpdateUser(u *User) error {
  623. return updateUser(x, u)
  624. }
  625. // deleteBeans deletes all given beans, beans should contain delete conditions.
  626. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  627. for i := range beans {
  628. if _, err = e.Delete(beans[i]); err != nil {
  629. return err
  630. }
  631. }
  632. return nil
  633. }
  634. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  635. func deleteUser(e *xorm.Session, u *User) error {
  636. // Note: A user owns any repository or belongs to any organization
  637. // cannot perform delete operation.
  638. // Check ownership of repository.
  639. count, err := getRepositoryCount(e, u)
  640. if err != nil {
  641. return fmt.Errorf("GetRepositoryCount: %v", err)
  642. } else if count > 0 {
  643. return ErrUserOwnRepos{UID: u.ID}
  644. }
  645. // Check membership of organization.
  646. count, err = u.getOrganizationCount(e)
  647. if err != nil {
  648. return fmt.Errorf("GetOrganizationCount: %v", err)
  649. } else if count > 0 {
  650. return ErrUserHasOrgs{UID: u.ID}
  651. }
  652. // ***** START: Watch *****
  653. watches := make([]*Watch, 0, 10)
  654. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  655. return fmt.Errorf("get all watches: %v", err)
  656. }
  657. for i := range watches {
  658. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  659. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  660. }
  661. }
  662. // ***** END: Watch *****
  663. // ***** START: Star *****
  664. stars := make([]*Star, 0, 10)
  665. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  666. return fmt.Errorf("get all stars: %v", err)
  667. }
  668. for i := range stars {
  669. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  670. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  671. }
  672. }
  673. // ***** END: Star *****
  674. // ***** START: Follow *****
  675. followers := make([]*Follow, 0, 10)
  676. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  677. return fmt.Errorf("get all followers: %v", err)
  678. }
  679. for i := range followers {
  680. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  681. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  682. }
  683. }
  684. // ***** END: Follow *****
  685. if err = deleteBeans(e,
  686. &AccessToken{UserID: u.ID},
  687. &Collaboration{UserID: u.ID},
  688. &Access{UserID: u.ID},
  689. &Watch{UserID: u.ID},
  690. &Star{UID: u.ID},
  691. &Follow{FollowID: u.ID},
  692. &Action{UserID: u.ID},
  693. &IssueUser{UID: u.ID},
  694. &EmailAddress{UID: u.ID},
  695. ); err != nil {
  696. return fmt.Errorf("deleteBeans: %v", err)
  697. }
  698. // ***** START: PublicKey *****
  699. keys := make([]*PublicKey, 0, 10)
  700. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  701. return fmt.Errorf("get all public keys: %v", err)
  702. }
  703. keyIDs := make([]int64, len(keys))
  704. for i := range keys {
  705. keyIDs[i] = keys[i].ID
  706. }
  707. if err = deletePublicKeys(e, keyIDs...); err != nil {
  708. return fmt.Errorf("deletePublicKeys: %v", err)
  709. }
  710. // ***** END: PublicKey *****
  711. // Clear assignee.
  712. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  713. return fmt.Errorf("clear assignee: %v", err)
  714. }
  715. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  716. return fmt.Errorf("Delete: %v", err)
  717. }
  718. // FIXME: system notice
  719. // Note: There are something just cannot be roll back,
  720. // so just keep error logs of those operations.
  721. _ = os.RemoveAll(UserPath(u.Name))
  722. _ = os.Remove(u.CustomAvatarPath())
  723. return nil
  724. }
  725. // DeleteUser completely and permanently deletes everything of a user,
  726. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  727. func DeleteUser(u *User) (err error) {
  728. sess := x.NewSession()
  729. defer sess.Close()
  730. if err = sess.Begin(); err != nil {
  731. return err
  732. }
  733. if err = deleteUser(sess, u); err != nil {
  734. // Note: don't wrapper error here.
  735. return err
  736. }
  737. if err = sess.Commit(); err != nil {
  738. return err
  739. }
  740. return RewriteAuthorizedKeys()
  741. }
  742. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  743. func DeleteInactivateUsers() (err error) {
  744. users := make([]*User, 0, 10)
  745. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  746. return fmt.Errorf("get all inactive users: %v", err)
  747. }
  748. // FIXME: should only update authorized_keys file once after all deletions.
  749. for _, u := range users {
  750. if err = DeleteUser(u); err != nil {
  751. // Ignore users that were set inactive by admin.
  752. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  753. continue
  754. }
  755. return err
  756. }
  757. }
  758. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  759. return err
  760. }
  761. // UserPath returns the path absolute path of user repositories.
  762. //
  763. // Deprecated: Use repoutil.UserPath instead.
  764. func UserPath(username string) string {
  765. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  766. }
  767. func GetUserByKeyID(keyID int64) (*User, error) {
  768. user := new(User)
  769. has, err := x.SQL("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  770. if err != nil {
  771. return nil, err
  772. } else if !has {
  773. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  774. }
  775. return user, nil
  776. }
  777. func getUserByID(e Engine, id int64) (*User, error) {
  778. u := new(User)
  779. has, err := e.ID(id).Get(u)
  780. if err != nil {
  781. return nil, err
  782. } else if !has {
  783. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  784. }
  785. return u, nil
  786. }
  787. // GetUserByID returns the user object by given ID if exists.
  788. // Deprecated: Use Users.GetByID instead.
  789. func GetUserByID(id int64) (*User, error) {
  790. return getUserByID(x, id)
  791. }
  792. // GetAssigneeByID returns the user with read access of repository by given ID.
  793. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  794. ctx := context.TODO()
  795. if !Perms.Authorize(ctx, userID, repo.ID, AccessModeRead,
  796. AccessModeOptions{
  797. OwnerID: repo.OwnerID,
  798. Private: repo.IsPrivate,
  799. },
  800. ) {
  801. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  802. }
  803. return Users.GetByID(ctx, userID)
  804. }
  805. // GetUserByName returns a user by given name.
  806. // Deprecated: Use Users.GetByUsername instead.
  807. func GetUserByName(name string) (*User, error) {
  808. if name == "" {
  809. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  810. }
  811. u := &User{LowerName: strings.ToLower(name)}
  812. has, err := x.Get(u)
  813. if err != nil {
  814. return nil, err
  815. } else if !has {
  816. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  817. }
  818. return u, nil
  819. }
  820. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  821. func GetUserEmailsByNames(names []string) []string {
  822. mails := make([]string, 0, len(names))
  823. for _, name := range names {
  824. u, err := GetUserByName(name)
  825. if err != nil {
  826. continue
  827. }
  828. if u.IsMailable() {
  829. mails = append(mails, u.Email)
  830. }
  831. }
  832. return mails
  833. }
  834. // GetUserIDsByNames returns a slice of ids corresponds to names.
  835. func GetUserIDsByNames(names []string) []int64 {
  836. ids := make([]int64, 0, len(names))
  837. for _, name := range names {
  838. u, err := GetUserByName(name)
  839. if err != nil {
  840. continue
  841. }
  842. ids = append(ids, u.ID)
  843. }
  844. return ids
  845. }
  846. // UserCommit represents a commit with validation of user.
  847. type UserCommit struct {
  848. User *User
  849. *git.Commit
  850. }
  851. // ValidateCommitWithEmail checks if author's e-mail of commit is corresponding to a user.
  852. func ValidateCommitWithEmail(c *git.Commit) *User {
  853. u, err := GetUserByEmail(c.Author.Email)
  854. if err != nil {
  855. return nil
  856. }
  857. return u
  858. }
  859. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  860. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  861. emails := make(map[string]*User)
  862. newCommits := make([]*UserCommit, len(oldCommits))
  863. for i := range oldCommits {
  864. var u *User
  865. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  866. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  867. emails[oldCommits[i].Author.Email] = u
  868. } else {
  869. u = v
  870. }
  871. newCommits[i] = &UserCommit{
  872. User: u,
  873. Commit: oldCommits[i],
  874. }
  875. }
  876. return newCommits
  877. }
  878. // GetUserByEmail returns the user object by given e-mail if exists.
  879. // Deprecated: Use Users.GetByEmail instead.
  880. func GetUserByEmail(email string) (*User, error) {
  881. if email == "" {
  882. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  883. }
  884. email = strings.ToLower(email)
  885. // First try to find the user by primary email
  886. user := &User{Email: email}
  887. has, err := x.Get(user)
  888. if err != nil {
  889. return nil, err
  890. }
  891. if has {
  892. return user, nil
  893. }
  894. // Otherwise, check in alternative list for activated email addresses
  895. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  896. has, err = x.Get(emailAddress)
  897. if err != nil {
  898. return nil, err
  899. }
  900. if has {
  901. return GetUserByID(emailAddress.UID)
  902. }
  903. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  904. }
  905. type SearchUserOptions struct {
  906. Keyword string
  907. Type UserType
  908. OrderBy string
  909. Page int
  910. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  911. }
  912. // SearchUserByName takes keyword and part of user name to search,
  913. // it returns results in given range and number of total results.
  914. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  915. if opts.Keyword == "" {
  916. return users, 0, nil
  917. }
  918. opts.Keyword = strings.ToLower(opts.Keyword)
  919. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  920. opts.PageSize = conf.UI.ExplorePagingNum
  921. }
  922. if opts.Page <= 0 {
  923. opts.Page = 1
  924. }
  925. searchQuery := "%" + opts.Keyword + "%"
  926. users = make([]*User, 0, opts.PageSize)
  927. // Append conditions
  928. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  929. Or("LOWER(full_name) LIKE ?", searchQuery).
  930. And("type = ?", opts.Type)
  931. countSess := *sess
  932. count, err := countSess.Count(new(User))
  933. if err != nil {
  934. return nil, 0, fmt.Errorf("Count: %v", err)
  935. }
  936. if len(opts.OrderBy) > 0 {
  937. sess.OrderBy(opts.OrderBy)
  938. }
  939. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  940. }
  941. // ___________ .__ .__
  942. // \_ _____/___ | | | | ______ _ __
  943. // | __)/ _ \| | | | / _ \ \/ \/ /
  944. // | \( <_> ) |_| |_( <_> ) /
  945. // \___ / \____/|____/____/\____/ \/\_/
  946. // \/
  947. // Follow represents relations of user and his/her followers.
  948. type Follow struct {
  949. ID int64
  950. UserID int64 `xorm:"UNIQUE(follow)"`
  951. FollowID int64 `xorm:"UNIQUE(follow)"`
  952. }
  953. func IsFollowing(userID, followID int64) bool {
  954. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  955. return has
  956. }
  957. // FollowUser marks someone be another's follower.
  958. func FollowUser(userID, followID int64) (err error) {
  959. if userID == followID || IsFollowing(userID, followID) {
  960. return nil
  961. }
  962. sess := x.NewSession()
  963. defer sess.Close()
  964. if err = sess.Begin(); err != nil {
  965. return err
  966. }
  967. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  968. return err
  969. }
  970. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  971. return err
  972. }
  973. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  974. return err
  975. }
  976. return sess.Commit()
  977. }
  978. // UnfollowUser unmarks someone be another's follower.
  979. func UnfollowUser(userID, followID int64) (err error) {
  980. if userID == followID || !IsFollowing(userID, followID) {
  981. return nil
  982. }
  983. sess := x.NewSession()
  984. defer sess.Close()
  985. if err = sess.Begin(); err != nil {
  986. return err
  987. }
  988. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  989. return err
  990. }
  991. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  992. return err
  993. }
  994. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  995. return err
  996. }
  997. return sess.Commit()
  998. }
  999. // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
  1000. func (u *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
  1001. accesses := make([]*Access, 0, 10)
  1002. if err := x.Find(&accesses, &Access{UserID: u.ID}); err != nil {
  1003. return nil, err
  1004. }
  1005. repos := make(map[*Repository]AccessMode, len(accesses))
  1006. for _, access := range accesses {
  1007. repo, err := GetRepositoryByID(access.RepoID)
  1008. if err != nil {
  1009. if IsErrRepoNotExist(err) {
  1010. log.Error("Failed to get repository by ID: %v", err)
  1011. continue
  1012. }
  1013. return nil, err
  1014. }
  1015. if repo.OwnerID == u.ID {
  1016. continue
  1017. }
  1018. repos[repo] = access.Mode
  1019. }
  1020. return repos, nil
  1021. }
  1022. // GetAccessibleRepositories finds repositories which the user has access but does not own.
  1023. // If limit is smaller than 1 means returns all found results.
  1024. func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
  1025. sess := x.Where("owner_id !=? ", user.ID).Desc("updated_unix")
  1026. if limit > 0 {
  1027. sess.Limit(limit)
  1028. repos = make([]*Repository, 0, limit)
  1029. } else {
  1030. repos = make([]*Repository, 0, 10)
  1031. }
  1032. return repos, sess.Join("INNER", "access", "access.user_id = ? AND access.repo_id = repository.id", user.ID).Find(&repos)
  1033. }