user.go 33 KB

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