user.go 30 KB

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