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