user.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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 models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "errors"
  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/Unknwon/com"
  21. "github.com/go-xorm/xorm"
  22. "github.com/nfnt/resize"
  23. "github.com/gogits/git-module"
  24. "github.com/gogits/gogs/modules/avatar"
  25. "github.com/gogits/gogs/modules/base"
  26. "github.com/gogits/gogs/modules/log"
  27. "github.com/gogits/gogs/modules/markdown"
  28. "github.com/gogits/gogs/modules/setting"
  29. )
  30. type UserType int
  31. const (
  32. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  33. USER_TYPE_ORGANIZATION
  34. )
  35. var (
  36. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  37. ErrEmailNotExist = errors.New("E-mail does not exist")
  38. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  39. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  40. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  41. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  42. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  43. )
  44. // User represents the object of individual and member of organization.
  45. type User struct {
  46. ID int64 `xorm:"pk autoincr"`
  47. LowerName string `xorm:"UNIQUE NOT NULL"`
  48. Name string `xorm:"UNIQUE NOT NULL"`
  49. FullName string
  50. // Email is the primary email address (to be used for communication)
  51. Email string `xorm:"NOT NULL"`
  52. ShowEmail bool
  53. Passwd string `xorm:"NOT NULL"`
  54. LoginType LoginType
  55. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  56. LoginName string
  57. Type UserType
  58. OwnedOrgs []*User `xorm:"-"`
  59. Orgs []*User `xorm:"-"`
  60. Repos []*Repository `xorm:"-"`
  61. Location string
  62. Website string
  63. Rands string `xorm:"VARCHAR(10)"`
  64. Salt string `xorm:"VARCHAR(10)"`
  65. Created time.Time `xorm:"-"`
  66. CreatedUnix int64
  67. Updated time.Time `xorm:"-"`
  68. UpdatedUnix int64
  69. // Remember visibility choice for convenience, true for private
  70. LastRepoVisibility bool
  71. // Maximum repository creation limit, -1 means use gloabl default
  72. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  73. // Permissions
  74. IsActive bool // Activate primary email
  75. IsAdmin bool
  76. AllowGitHook bool
  77. AllowImportLocal bool // Allow migrate repository by local path
  78. ProhibitLogin bool
  79. // Avatar
  80. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  81. AvatarEmail string `xorm:"NOT NULL"`
  82. UseCustomAvatar bool
  83. // Counters
  84. NumFollowers int
  85. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  86. NumStars int
  87. NumRepos int
  88. // For organization
  89. Description string
  90. NumTeams int
  91. NumMembers int
  92. Teams []*Team `xorm:"-"`
  93. Members []*User `xorm:"-"`
  94. }
  95. func (u *User) BeforeInsert() {
  96. u.CreatedUnix = time.Now().Unix()
  97. u.UpdatedUnix = u.CreatedUnix
  98. }
  99. func (u *User) BeforeUpdate() {
  100. if u.MaxRepoCreation < -1 {
  101. u.MaxRepoCreation = -1
  102. }
  103. u.UpdatedUnix = time.Now().Unix()
  104. }
  105. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  106. switch colName {
  107. case "full_name":
  108. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  109. case "created_unix":
  110. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  111. case "updated_unix":
  112. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  113. }
  114. }
  115. // returns true if user login type is LOGIN_PLAIN.
  116. func (u *User) IsLocal() bool {
  117. return u.LoginType <= LOGIN_PLAIN
  118. }
  119. // HasForkedRepo checks if user has already forked a repository with given ID.
  120. func (u *User) HasForkedRepo(repoID int64) bool {
  121. _, has := HasForkedRepo(u.ID, repoID)
  122. return has
  123. }
  124. func (u *User) RepoCreationNum() int {
  125. if u.MaxRepoCreation <= -1 {
  126. return setting.Repository.MaxCreationLimit
  127. }
  128. return u.MaxRepoCreation
  129. }
  130. func (u *User) CanCreateRepo() bool {
  131. if u.MaxRepoCreation <= -1 {
  132. if setting.Repository.MaxCreationLimit <= -1 {
  133. return true
  134. }
  135. return u.NumRepos < setting.Repository.MaxCreationLimit
  136. }
  137. return u.NumRepos < u.MaxRepoCreation
  138. }
  139. // CanEditGitHook returns true if user can edit Git hooks.
  140. func (u *User) CanEditGitHook() bool {
  141. return u.IsAdmin || u.AllowGitHook
  142. }
  143. // CanImportLocal returns true if user can migrate repository by local path.
  144. func (u *User) CanImportLocal() bool {
  145. return u.IsAdmin || u.AllowImportLocal
  146. }
  147. // DashboardLink returns the user dashboard page link.
  148. func (u *User) DashboardLink() string {
  149. if u.IsOrganization() {
  150. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  151. }
  152. return setting.AppSubUrl + "/"
  153. }
  154. // HomeLink returns the user or organization home page link.
  155. func (u *User) HomeLink() string {
  156. return setting.AppSubUrl + "/" + 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 := base.CreateTimeLimitCode(
  161. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  162. setting.Service.ActiveCodeLives, 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(setting.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 len(seed) == 0 {
  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. func (u *User) RelAvatarLink() string {
  200. defaultImgUrl := "/img/avatar_default.png"
  201. if u.ID == -1 {
  202. return defaultImgUrl
  203. }
  204. switch {
  205. case u.UseCustomAvatar:
  206. if !com.IsExist(u.CustomAvatarPath()) {
  207. return defaultImgUrl
  208. }
  209. return "/avatars/" + com.ToStr(u.ID)
  210. case setting.DisableGravatar, setting.OfflineMode:
  211. if !com.IsExist(u.CustomAvatarPath()) {
  212. if err := u.GenerateRandomAvatar(); err != nil {
  213. log.Error(3, "GenerateRandomAvatar: %v", err)
  214. }
  215. }
  216. return "/avatars/" + com.ToStr(u.ID)
  217. }
  218. return setting.GravatarSource + u.Avatar
  219. }
  220. // AvatarLink returns user avatar link.
  221. func (u *User) AvatarLink() string {
  222. link := u.RelAvatarLink()
  223. if link[0] == '/' && link[1] != '/' {
  224. return strings.TrimSuffix(setting.AppUrl, "/") + link
  225. }
  226. return link
  227. }
  228. // User.GetFollwoers returns range of user's followers.
  229. func (u *User) GetFollowers(page int) ([]*User, error) {
  230. users := make([]*User, 0, ItemsPerPage)
  231. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  232. if setting.UsePostgreSQL {
  233. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  234. } else {
  235. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  236. }
  237. return users, sess.Find(&users)
  238. }
  239. func (u *User) IsFollowing(followID int64) bool {
  240. return IsFollowing(u.ID, followID)
  241. }
  242. // GetFollowing returns range of user's following.
  243. func (u *User) GetFollowing(page int) ([]*User, error) {
  244. users := make([]*User, 0, ItemsPerPage)
  245. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  246. if setting.UsePostgreSQL {
  247. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  248. } else {
  249. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  250. }
  251. return users, sess.Find(&users)
  252. }
  253. // NewGitSig generates and returns the signature of given user.
  254. func (u *User) NewGitSig() *git.Signature {
  255. return &git.Signature{
  256. Name: u.Name,
  257. Email: u.Email,
  258. When: time.Now(),
  259. }
  260. }
  261. // EncodePasswd encodes password to safe format.
  262. func (u *User) EncodePasswd() {
  263. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  264. u.Passwd = fmt.Sprintf("%x", newPasswd)
  265. }
  266. // ValidatePassword checks if given password matches the one belongs to the user.
  267. func (u *User) ValidatePassword(passwd string) bool {
  268. newUser := &User{Passwd: passwd, Salt: u.Salt}
  269. newUser.EncodePasswd()
  270. return u.Passwd == newUser.Passwd
  271. }
  272. // UploadAvatar saves custom avatar for user.
  273. // FIXME: split uploads to different subdirs in case we have massive users.
  274. func (u *User) UploadAvatar(data []byte) error {
  275. img, _, err := image.Decode(bytes.NewReader(data))
  276. if err != nil {
  277. return fmt.Errorf("Decode: %v", err)
  278. }
  279. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  280. sess := x.NewSession()
  281. defer sessionRelease(sess)
  282. if err = sess.Begin(); err != nil {
  283. return err
  284. }
  285. u.UseCustomAvatar = true
  286. if err = updateUser(sess, u); err != nil {
  287. return fmt.Errorf("updateUser: %v", err)
  288. }
  289. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  290. fw, err := os.Create(u.CustomAvatarPath())
  291. if err != nil {
  292. return fmt.Errorf("Create: %v", err)
  293. }
  294. defer fw.Close()
  295. if err = png.Encode(fw, m); err != nil {
  296. return fmt.Errorf("Encode: %v", err)
  297. }
  298. return sess.Commit()
  299. }
  300. // DeleteAvatar deletes the user's custom avatar.
  301. func (u *User) DeleteAvatar() error {
  302. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  303. os.Remove(u.CustomAvatarPath())
  304. u.UseCustomAvatar = false
  305. if err := UpdateUser(u); err != nil {
  306. return fmt.Errorf("UpdateUser: %v", err)
  307. }
  308. return nil
  309. }
  310. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  311. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  312. has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
  313. if err != nil {
  314. log.Error(3, "HasAccess: %v", err)
  315. }
  316. return has
  317. }
  318. // IsWriterOfRepo returns true if user has write access to given repository.
  319. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  320. has, err := HasAccess(u, repo, ACCESS_MODE_WRITE)
  321. if err != nil {
  322. log.Error(3, "HasAccess: %v", err)
  323. }
  324. return has
  325. }
  326. // IsOrganization returns true if user is actually a organization.
  327. func (u *User) IsOrganization() bool {
  328. return u.Type == USER_TYPE_ORGANIZATION
  329. }
  330. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  331. func (u *User) IsUserOrgOwner(orgId int64) bool {
  332. return IsOrganizationOwner(orgId, u.ID)
  333. }
  334. // IsPublicMember returns true if user public his/her membership in give organization.
  335. func (u *User) IsPublicMember(orgId int64) bool {
  336. return IsPublicMembership(orgId, u.ID)
  337. }
  338. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  339. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  340. }
  341. // GetOrganizationCount returns count of membership of organization of user.
  342. func (u *User) GetOrganizationCount() (int64, error) {
  343. return u.getOrganizationCount(x)
  344. }
  345. // GetRepositories returns repositories that user owns, including private repositories.
  346. func (u *User) GetRepositories(page, pageSize int) (err error) {
  347. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize)
  348. return err
  349. }
  350. // GetRepositories returns mirror repositories that user owns, including private repositories.
  351. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  352. return GetUserMirrorRepositories(u.ID)
  353. }
  354. // GetOwnedOrganizations returns all organizations that user owns.
  355. func (u *User) GetOwnedOrganizations() (err error) {
  356. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  357. return err
  358. }
  359. // GetOrganizations returns all organizations that user belongs to.
  360. func (u *User) GetOrganizations(all bool) error {
  361. ous, err := GetOrgUsersByUserID(u.ID, all)
  362. if err != nil {
  363. return err
  364. }
  365. u.Orgs = make([]*User, len(ous))
  366. for i, ou := range ous {
  367. u.Orgs[i], err = GetUserByID(ou.OrgID)
  368. if err != nil {
  369. return err
  370. }
  371. }
  372. return nil
  373. }
  374. // DisplayName returns full name if it's not empty,
  375. // returns username otherwise.
  376. func (u *User) DisplayName() string {
  377. if len(u.FullName) > 0 {
  378. return u.FullName
  379. }
  380. return u.Name
  381. }
  382. func (u *User) ShortName(length int) string {
  383. return base.EllipsisString(u.Name, length)
  384. }
  385. // IsUserExist checks if given user name exist,
  386. // the user name should be noncased unique.
  387. // If uid is presented, then check will rule out that one,
  388. // it is used when update a user name in settings page.
  389. func IsUserExist(uid int64, name string) (bool, error) {
  390. if len(name) == 0 {
  391. return false, nil
  392. }
  393. return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)})
  394. }
  395. // GetUserSalt returns a ramdom user salt token.
  396. func GetUserSalt() string {
  397. return base.GetRandomString(10)
  398. }
  399. // NewFakeUser creates and returns a fake user for someone has deleted his/her account.
  400. func NewFakeUser() *User {
  401. return &User{
  402. ID: -1,
  403. Name: "Someone",
  404. LowerName: "someone",
  405. }
  406. }
  407. var (
  408. reversedUsernames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", "..", "*.about", "*.outages", "*.tos"}
  409. reversedUserPatterns = []string{"*.keys"}
  410. )
  411. // isUsableName checks if name is reserved or pattern of name is not allowed
  412. // based on given reversed names and patterns.
  413. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  414. func isUsableName(names, patterns []string, name string) error {
  415. name = strings.TrimSpace(strings.ToLower(name))
  416. if utf8.RuneCountInString(name) == 0 {
  417. return ErrNameEmpty
  418. }
  419. for i := range names {
  420. if name == names[i] {
  421. return ErrNameReserved{name}
  422. }
  423. }
  424. for _, pat := range patterns {
  425. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  426. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  427. return ErrNamePatternNotAllowed{pat}
  428. }
  429. }
  430. return nil
  431. }
  432. func IsUsableUsername(name string) error {
  433. return isUsableName(reversedUsernames, reversedUserPatterns, name)
  434. }
  435. // CreateUser creates record of a new user.
  436. func CreateUser(u *User) (err error) {
  437. if err = IsUsableUsername(u.Name); err != nil {
  438. return err
  439. }
  440. isExist, err := IsUserExist(0, u.Name)
  441. if err != nil {
  442. return err
  443. } else if isExist {
  444. return ErrUserAlreadyExist{u.Name}
  445. }
  446. u.Email = strings.ToLower(u.Email)
  447. u.ShowEmail = false
  448. isExist, err = IsEmailUsed(u.Email)
  449. if err != nil {
  450. return err
  451. } else if isExist {
  452. return ErrEmailAlreadyUsed{u.Email}
  453. }
  454. u.LowerName = strings.ToLower(u.Name)
  455. u.AvatarEmail = u.Email
  456. u.Avatar = base.HashEmail(u.AvatarEmail)
  457. u.Rands = GetUserSalt()
  458. u.Salt = GetUserSalt()
  459. u.EncodePasswd()
  460. u.MaxRepoCreation = -1
  461. sess := x.NewSession()
  462. defer sessionRelease(sess)
  463. if err = sess.Begin(); err != nil {
  464. return err
  465. }
  466. if _, err = sess.Insert(u); err != nil {
  467. return err
  468. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  469. return err
  470. }
  471. return sess.Commit()
  472. }
  473. func countUsers(e Engine) int64 {
  474. count, _ := e.Where("type=0").Count(new(User))
  475. return count
  476. }
  477. // CountUsers returns number of users.
  478. func CountUsers() int64 {
  479. return countUsers(x)
  480. }
  481. // Users returns number of users in given page.
  482. func Users(page, pageSize int) ([]*User, error) {
  483. users := make([]*User, 0, pageSize)
  484. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  485. }
  486. // get user by erify code
  487. func getVerifyUser(code string) (user *User) {
  488. if len(code) <= base.TimeLimitCodeLength {
  489. return nil
  490. }
  491. // use tail hex username query user
  492. hexStr := code[base.TimeLimitCodeLength:]
  493. if b, err := hex.DecodeString(hexStr); err == nil {
  494. if user, err = GetUserByName(string(b)); user != nil {
  495. return user
  496. }
  497. log.Error(4, "user.getVerifyUser: %v", err)
  498. }
  499. return nil
  500. }
  501. // verify active code when active account
  502. func VerifyUserActiveCode(code string) (user *User) {
  503. minutes := setting.Service.ActiveCodeLives
  504. if user = getVerifyUser(code); user != nil {
  505. // time limit code
  506. prefix := code[:base.TimeLimitCodeLength]
  507. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  508. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  509. return user
  510. }
  511. }
  512. return nil
  513. }
  514. // verify active code when active account
  515. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  516. minutes := setting.Service.ActiveCodeLives
  517. if user := getVerifyUser(code); user != nil {
  518. // time limit code
  519. prefix := code[:base.TimeLimitCodeLength]
  520. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  521. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  522. emailAddress := &EmailAddress{Email: email}
  523. if has, _ := x.Get(emailAddress); has {
  524. return emailAddress
  525. }
  526. }
  527. }
  528. return nil
  529. }
  530. // ChangeUserName changes all corresponding setting from old user name to new one.
  531. func ChangeUserName(u *User, newUserName string) (err error) {
  532. if err = IsUsableUsername(newUserName); err != nil {
  533. return err
  534. }
  535. isExist, err := IsUserExist(0, newUserName)
  536. if err != nil {
  537. return err
  538. } else if isExist {
  539. return ErrUserAlreadyExist{newUserName}
  540. }
  541. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  542. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  543. }
  544. // Delete all local copies of repository wiki that user owns.
  545. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  546. repo := bean.(*Repository)
  547. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  548. return nil
  549. }); err != nil {
  550. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  551. }
  552. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  553. }
  554. func updateUser(e Engine, u *User) error {
  555. // Organization does not need email
  556. if !u.IsOrganization() {
  557. u.Email = strings.ToLower(u.Email)
  558. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  559. if err != nil {
  560. return err
  561. } else if has {
  562. return ErrEmailAlreadyUsed{u.Email}
  563. }
  564. if len(u.AvatarEmail) == 0 {
  565. u.AvatarEmail = u.Email
  566. }
  567. u.Avatar = base.HashEmail(u.AvatarEmail)
  568. }
  569. u.LowerName = strings.ToLower(u.Name)
  570. u.Location = base.TruncateString(u.Location, 255)
  571. u.Website = base.TruncateString(u.Website, 255)
  572. u.Description = base.TruncateString(u.Description, 255)
  573. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  574. _, err := e.Id(u.ID).AllCols().Update(u)
  575. return err
  576. }
  577. // UpdateUser updates user's information.
  578. func UpdateUser(u *User) error {
  579. return updateUser(x, u)
  580. }
  581. // deleteBeans deletes all given beans, beans should contain delete conditions.
  582. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  583. for i := range beans {
  584. if _, err = e.Delete(beans[i]); err != nil {
  585. return err
  586. }
  587. }
  588. return nil
  589. }
  590. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  591. func deleteUser(e *xorm.Session, u *User) error {
  592. // Note: A user owns any repository or belongs to any organization
  593. // cannot perform delete operation.
  594. // Check ownership of repository.
  595. count, err := getRepositoryCount(e, u)
  596. if err != nil {
  597. return fmt.Errorf("GetRepositoryCount: %v", err)
  598. } else if count > 0 {
  599. return ErrUserOwnRepos{UID: u.ID}
  600. }
  601. // Check membership of organization.
  602. count, err = u.getOrganizationCount(e)
  603. if err != nil {
  604. return fmt.Errorf("GetOrganizationCount: %v", err)
  605. } else if count > 0 {
  606. return ErrUserHasOrgs{UID: u.ID}
  607. }
  608. // ***** START: Watch *****
  609. watches := make([]*Watch, 0, 10)
  610. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  611. return fmt.Errorf("get all watches: %v", err)
  612. }
  613. for i := range watches {
  614. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  615. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  616. }
  617. }
  618. // ***** END: Watch *****
  619. // ***** START: Star *****
  620. stars := make([]*Star, 0, 10)
  621. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  622. return fmt.Errorf("get all stars: %v", err)
  623. }
  624. for i := range stars {
  625. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  626. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  627. }
  628. }
  629. // ***** END: Star *****
  630. // ***** START: Follow *****
  631. followers := make([]*Follow, 0, 10)
  632. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  633. return fmt.Errorf("get all followers: %v", err)
  634. }
  635. for i := range followers {
  636. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  637. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  638. }
  639. }
  640. // ***** END: Follow *****
  641. if err = deleteBeans(e,
  642. &AccessToken{UID: u.ID},
  643. &Collaboration{UserID: u.ID},
  644. &Access{UserID: u.ID},
  645. &Watch{UserID: u.ID},
  646. &Star{UID: u.ID},
  647. &Follow{FollowID: u.ID},
  648. &Action{UserID: u.ID},
  649. &IssueUser{UID: u.ID},
  650. &EmailAddress{UID: u.ID},
  651. ); err != nil {
  652. return fmt.Errorf("deleteBeans: %v", err)
  653. }
  654. // ***** START: PublicKey *****
  655. keys := make([]*PublicKey, 0, 10)
  656. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  657. return fmt.Errorf("get all public keys: %v", err)
  658. }
  659. keyIDs := make([]int64, len(keys))
  660. for i := range keys {
  661. keyIDs[i] = keys[i].ID
  662. }
  663. if err = deletePublicKeys(e, keyIDs...); err != nil {
  664. return fmt.Errorf("deletePublicKeys: %v", err)
  665. }
  666. // ***** END: PublicKey *****
  667. // Clear assignee.
  668. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  669. return fmt.Errorf("clear assignee: %v", err)
  670. }
  671. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  672. return fmt.Errorf("Delete: %v", err)
  673. }
  674. // FIXME: system notice
  675. // Note: There are something just cannot be roll back,
  676. // so just keep error logs of those operations.
  677. os.RemoveAll(UserPath(u.Name))
  678. os.Remove(u.CustomAvatarPath())
  679. return nil
  680. }
  681. // DeleteUser completely and permanently deletes everything of a user,
  682. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  683. func DeleteUser(u *User) (err error) {
  684. sess := x.NewSession()
  685. defer sessionRelease(sess)
  686. if err = sess.Begin(); err != nil {
  687. return err
  688. }
  689. if err = deleteUser(sess, u); err != nil {
  690. // Note: don't wrapper error here.
  691. return err
  692. }
  693. if err = sess.Commit(); err != nil {
  694. return err
  695. }
  696. return RewriteAllPublicKeys()
  697. }
  698. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  699. func DeleteInactivateUsers() (err error) {
  700. users := make([]*User, 0, 10)
  701. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  702. return fmt.Errorf("get all inactive users: %v", err)
  703. }
  704. // FIXME: should only update authorized_keys file once after all deletions.
  705. for _, u := range users {
  706. if err = DeleteUser(u); err != nil {
  707. // Ignore users that were set inactive by admin.
  708. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  709. continue
  710. }
  711. return err
  712. }
  713. }
  714. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  715. return err
  716. }
  717. // UserPath returns the path absolute path of user repositories.
  718. func UserPath(userName string) string {
  719. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  720. }
  721. func GetUserByKeyID(keyID int64) (*User, error) {
  722. user := new(User)
  723. 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)
  724. if err != nil {
  725. return nil, err
  726. } else if !has {
  727. return nil, ErrUserNotKeyOwner
  728. }
  729. return user, nil
  730. }
  731. func getUserByID(e Engine, id int64) (*User, error) {
  732. u := new(User)
  733. has, err := e.Id(id).Get(u)
  734. if err != nil {
  735. return nil, err
  736. } else if !has {
  737. return nil, ErrUserNotExist{id, ""}
  738. }
  739. return u, nil
  740. }
  741. // GetUserByID returns the user object by given ID if exists.
  742. func GetUserByID(id int64) (*User, error) {
  743. return getUserByID(x, id)
  744. }
  745. // GetAssigneeByID returns the user with write access of repository by given ID.
  746. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  747. has, err := HasAccess(&User{ID: userID}, repo, ACCESS_MODE_WRITE)
  748. if err != nil {
  749. return nil, err
  750. } else if !has {
  751. return nil, ErrUserNotExist{userID, ""}
  752. }
  753. return GetUserByID(userID)
  754. }
  755. // GetUserByName returns user by given name.
  756. func GetUserByName(name string) (*User, error) {
  757. if len(name) == 0 {
  758. return nil, ErrUserNotExist{0, name}
  759. }
  760. u := &User{LowerName: strings.ToLower(name)}
  761. has, err := x.Get(u)
  762. if err != nil {
  763. return nil, err
  764. } else if !has {
  765. return nil, ErrUserNotExist{0, name}
  766. }
  767. return u, nil
  768. }
  769. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  770. func GetUserEmailsByNames(names []string) []string {
  771. mails := make([]string, 0, len(names))
  772. for _, name := range names {
  773. u, err := GetUserByName(name)
  774. if err != nil {
  775. continue
  776. }
  777. mails = append(mails, u.Email)
  778. }
  779. return mails
  780. }
  781. // GetUserIDsByNames returns a slice of ids corresponds to names.
  782. func GetUserIDsByNames(names []string) []int64 {
  783. ids := make([]int64, 0, len(names))
  784. for _, name := range names {
  785. u, err := GetUserByName(name)
  786. if err != nil {
  787. continue
  788. }
  789. ids = append(ids, u.ID)
  790. }
  791. return ids
  792. }
  793. // UserCommit represents a commit with validation of user.
  794. type UserCommit struct {
  795. User *User
  796. *git.Commit
  797. }
  798. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  799. func ValidateCommitWithEmail(c *git.Commit) *User {
  800. u, err := GetUserByEmail(c.Author.Email)
  801. if err != nil {
  802. return nil
  803. }
  804. return u
  805. }
  806. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  807. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  808. var (
  809. u *User
  810. emails = map[string]*User{}
  811. newCommits = list.New()
  812. e = oldCommits.Front()
  813. )
  814. for e != nil {
  815. c := e.Value.(*git.Commit)
  816. if v, ok := emails[c.Author.Email]; !ok {
  817. u, _ = GetUserByEmail(c.Author.Email)
  818. emails[c.Author.Email] = u
  819. } else {
  820. u = v
  821. }
  822. newCommits.PushBack(UserCommit{
  823. User: u,
  824. Commit: c,
  825. })
  826. e = e.Next()
  827. }
  828. return newCommits
  829. }
  830. // GetUserByEmail returns the user object by given e-mail if exists.
  831. func GetUserByEmail(email string) (*User, error) {
  832. if len(email) == 0 {
  833. return nil, ErrUserNotExist{0, "email"}
  834. }
  835. email = strings.ToLower(email)
  836. // First try to find the user by primary email
  837. user := &User{Email: email}
  838. has, err := x.Get(user)
  839. if err != nil {
  840. return nil, err
  841. }
  842. if has {
  843. return user, nil
  844. }
  845. // Otherwise, check in alternative list for activated email addresses
  846. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  847. has, err = x.Get(emailAddress)
  848. if err != nil {
  849. return nil, err
  850. }
  851. if has {
  852. return GetUserByID(emailAddress.UID)
  853. }
  854. return nil, ErrUserNotExist{0, email}
  855. }
  856. type SearchUserOptions struct {
  857. Keyword string
  858. Type UserType
  859. OrderBy string
  860. Page int
  861. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  862. }
  863. // SearchUserByName takes keyword and part of user name to search,
  864. // it returns results in given range and number of total results.
  865. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  866. if len(opts.Keyword) == 0 {
  867. return users, 0, nil
  868. }
  869. opts.Keyword = strings.ToLower(opts.Keyword)
  870. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  871. opts.PageSize = setting.UI.ExplorePagingNum
  872. }
  873. if opts.Page <= 0 {
  874. opts.Page = 1
  875. }
  876. searchQuery := "%" + opts.Keyword + "%"
  877. users = make([]*User, 0, opts.PageSize)
  878. // Append conditions
  879. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  880. Or("LOWER(full_name) LIKE ?", searchQuery).
  881. And("type = ?", opts.Type)
  882. var countSess xorm.Session
  883. countSess = *sess
  884. count, err := countSess.Count(new(User))
  885. if err != nil {
  886. return nil, 0, fmt.Errorf("Count: %v", err)
  887. }
  888. if len(opts.OrderBy) > 0 {
  889. sess.OrderBy(opts.OrderBy)
  890. }
  891. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  892. }
  893. // ___________ .__ .__
  894. // \_ _____/___ | | | | ______ _ __
  895. // | __)/ _ \| | | | / _ \ \/ \/ /
  896. // | \( <_> ) |_| |_( <_> ) /
  897. // \___ / \____/|____/____/\____/ \/\_/
  898. // \/
  899. // Follow represents relations of user and his/her followers.
  900. type Follow struct {
  901. ID int64 `xorm:"pk autoincr"`
  902. UserID int64 `xorm:"UNIQUE(follow)"`
  903. FollowID int64 `xorm:"UNIQUE(follow)"`
  904. }
  905. func IsFollowing(userID, followID int64) bool {
  906. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  907. return has
  908. }
  909. // FollowUser marks someone be another's follower.
  910. func FollowUser(userID, followID int64) (err error) {
  911. if userID == followID || IsFollowing(userID, followID) {
  912. return nil
  913. }
  914. sess := x.NewSession()
  915. defer sessionRelease(sess)
  916. if err = sess.Begin(); err != nil {
  917. return err
  918. }
  919. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  920. return err
  921. }
  922. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  923. return err
  924. }
  925. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  926. return err
  927. }
  928. return sess.Commit()
  929. }
  930. // UnfollowUser unmarks someone be another's follower.
  931. func UnfollowUser(userID, followID int64) (err error) {
  932. if userID == followID || !IsFollowing(userID, followID) {
  933. return nil
  934. }
  935. sess := x.NewSession()
  936. defer sessionRelease(sess)
  937. if err = sess.Begin(); err != nil {
  938. return err
  939. }
  940. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  941. return err
  942. }
  943. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  944. return err
  945. }
  946. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  947. return err
  948. }
  949. return sess.Commit()
  950. }