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

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