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