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

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