You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 30KB

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