user.go 31 KB

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