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 28KB

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