user.go 29 KB

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