user.go 28 KB

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