You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 26 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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. // UpdateUser updates user's information.
  413. func UpdateUser(u *User) error {
  414. u.Email = strings.ToLower(u.Email)
  415. has, err := x.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  416. if err != nil {
  417. return err
  418. } else if has {
  419. return ErrEmailAlreadyUsed{u.Email}
  420. }
  421. u.LowerName = strings.ToLower(u.Name)
  422. if len(u.Location) > 255 {
  423. u.Location = u.Location[:255]
  424. }
  425. if len(u.Website) > 255 {
  426. u.Website = u.Website[:255]
  427. }
  428. if len(u.Description) > 255 {
  429. u.Description = u.Description[:255]
  430. }
  431. if u.AvatarEmail == "" {
  432. u.AvatarEmail = u.Email
  433. }
  434. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  435. u.FullName = base.Sanitizer.Sanitize(u.FullName)
  436. _, err = x.Id(u.Id).AllCols().Update(u)
  437. return err
  438. }
  439. // DeleteBeans deletes all given beans, beans should contain delete conditions.
  440. func DeleteBeans(e Engine, beans ...interface{}) (err error) {
  441. for i := range beans {
  442. if _, err = e.Delete(beans[i]); err != nil {
  443. return err
  444. }
  445. }
  446. return nil
  447. }
  448. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  449. // DeleteUser completely and permanently deletes everything of a user,
  450. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  451. func DeleteUser(u *User) error {
  452. // Note: A user owns any repository or belongs to any organization
  453. // cannot perform delete operation.
  454. // Check ownership of repository.
  455. count, err := GetRepositoryCount(u)
  456. if err != nil {
  457. return fmt.Errorf("GetRepositoryCount: %v", err)
  458. } else if count > 0 {
  459. return ErrUserOwnRepos{UID: u.Id}
  460. }
  461. // Check membership of organization.
  462. count, err = u.GetOrganizationCount()
  463. if err != nil {
  464. return fmt.Errorf("GetOrganizationCount: %v", err)
  465. } else if count > 0 {
  466. return ErrUserHasOrgs{UID: u.Id}
  467. }
  468. sess := x.NewSession()
  469. defer sessionRelease(sess)
  470. if err = sess.Begin(); err != nil {
  471. return err
  472. }
  473. // ***** START: Watch *****
  474. watches := make([]*Watch, 0, 10)
  475. if err = x.Find(&watches, &Watch{UserID: u.Id}); err != nil {
  476. return fmt.Errorf("get all watches: %v", err)
  477. }
  478. for i := range watches {
  479. if _, err = sess.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  480. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  481. }
  482. }
  483. // ***** END: Watch *****
  484. // ***** START: Star *****
  485. stars := make([]*Star, 0, 10)
  486. if err = x.Find(&stars, &Star{UID: u.Id}); err != nil {
  487. return fmt.Errorf("get all stars: %v", err)
  488. }
  489. for i := range stars {
  490. if _, err = sess.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  491. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  492. }
  493. }
  494. // ***** END: Star *****
  495. // ***** START: Follow *****
  496. followers := make([]*Follow, 0, 10)
  497. if err = x.Find(&followers, &Follow{UserID: u.Id}); err != nil {
  498. return fmt.Errorf("get all followers: %v", err)
  499. }
  500. for i := range followers {
  501. if _, err = sess.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  502. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  503. }
  504. }
  505. // ***** END: Follow *****
  506. if err = DeleteBeans(sess,
  507. &Oauth2{Uid: u.Id},
  508. &AccessToken{UID: u.Id},
  509. &Collaboration{UserID: u.Id},
  510. &Access{UserID: u.Id},
  511. &Watch{UserID: u.Id},
  512. &Star{UID: u.Id},
  513. &Follow{FollowID: u.Id},
  514. &Action{UserID: u.Id},
  515. &IssueUser{UID: u.Id},
  516. &EmailAddress{Uid: u.Id},
  517. ); err != nil {
  518. return fmt.Errorf("DeleteBeans: %v", err)
  519. }
  520. // ***** START: PublicKey *****
  521. keys := make([]*PublicKey, 0, 10)
  522. if err = sess.Find(&keys, &PublicKey{OwnerID: u.Id}); err != nil {
  523. return fmt.Errorf("get all public keys: %v", err)
  524. }
  525. for _, key := range keys {
  526. if err = deletePublicKey(sess, key.ID); err != nil {
  527. return fmt.Errorf("deletePublicKey: %v", err)
  528. }
  529. }
  530. // ***** END: PublicKey *****
  531. // Clear assignee.
  532. if _, err = sess.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.Id); err != nil {
  533. return fmt.Errorf("clear assignee: %v", err)
  534. }
  535. if _, err = sess.Delete(u); err != nil {
  536. return fmt.Errorf("Delete: %v", err)
  537. }
  538. if err = sess.Commit(); err != nil {
  539. return fmt.Errorf("Commit: %v", err)
  540. }
  541. // FIXME: system notice
  542. // Note: There are something just cannot be roll back,
  543. // so just keep error logs of those operations.
  544. RewriteAllPublicKeys()
  545. os.RemoveAll(UserPath(u.Name))
  546. os.Remove(u.CustomAvatarPath())
  547. return nil
  548. }
  549. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  550. func DeleteInactivateUsers() (err error) {
  551. users := make([]*User, 0, 10)
  552. if err = x.Where("is_active=?", false).Find(&users); err != nil {
  553. return fmt.Errorf("get all inactive users: %v", err)
  554. }
  555. for _, u := range users {
  556. if err = DeleteUser(u); err != nil {
  557. // Ignore users that were set inactive by admin.
  558. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  559. continue
  560. }
  561. return err
  562. }
  563. }
  564. _, err = x.Where("is_activated=?", false).Delete(new(EmailAddress))
  565. return err
  566. }
  567. // UserPath returns the path absolute path of user repositories.
  568. func UserPath(userName string) string {
  569. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  570. }
  571. func GetUserByKeyId(keyId int64) (*User, error) {
  572. user := new(User)
  573. 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)
  574. if err != nil {
  575. return nil, err
  576. } else if !has {
  577. return nil, ErrUserNotKeyOwner
  578. }
  579. return user, nil
  580. }
  581. func getUserByID(e Engine, id int64) (*User, error) {
  582. u := new(User)
  583. has, err := e.Id(id).Get(u)
  584. if err != nil {
  585. return nil, err
  586. } else if !has {
  587. return nil, ErrUserNotExist{id, ""}
  588. }
  589. return u, nil
  590. }
  591. // GetUserByID returns the user object by given ID if exists.
  592. func GetUserByID(id int64) (*User, error) {
  593. return getUserByID(x, id)
  594. }
  595. // GetAssigneeByID returns the user with write access of repository by given ID.
  596. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  597. has, err := HasAccess(&User{Id: userID}, repo, ACCESS_MODE_WRITE)
  598. if err != nil {
  599. return nil, err
  600. } else if !has {
  601. return nil, ErrUserNotExist{userID, ""}
  602. }
  603. return GetUserByID(userID)
  604. }
  605. // GetUserByName returns user by given name.
  606. func GetUserByName(name string) (*User, error) {
  607. if len(name) == 0 {
  608. return nil, ErrUserNotExist{0, name}
  609. }
  610. u := &User{LowerName: strings.ToLower(name)}
  611. has, err := x.Get(u)
  612. if err != nil {
  613. return nil, err
  614. } else if !has {
  615. return nil, ErrUserNotExist{0, name}
  616. }
  617. return u, nil
  618. }
  619. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  620. func GetUserEmailsByNames(names []string) []string {
  621. mails := make([]string, 0, len(names))
  622. for _, name := range names {
  623. u, err := GetUserByName(name)
  624. if err != nil {
  625. continue
  626. }
  627. mails = append(mails, u.Email)
  628. }
  629. return mails
  630. }
  631. // GetUserIdsByNames returns a slice of ids corresponds to names.
  632. func GetUserIdsByNames(names []string) []int64 {
  633. ids := make([]int64, 0, len(names))
  634. for _, name := range names {
  635. u, err := GetUserByName(name)
  636. if err != nil {
  637. continue
  638. }
  639. ids = append(ids, u.Id)
  640. }
  641. return ids
  642. }
  643. // GetEmailAddresses returns all e-mail addresses belongs to given user.
  644. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
  645. emails := make([]*EmailAddress, 0, 5)
  646. err := x.Where("uid=?", uid).Find(&emails)
  647. if err != nil {
  648. return nil, err
  649. }
  650. u, err := GetUserByID(uid)
  651. if err != nil {
  652. return nil, err
  653. }
  654. isPrimaryFound := false
  655. for _, email := range emails {
  656. if email.Email == u.Email {
  657. isPrimaryFound = true
  658. email.IsPrimary = true
  659. } else {
  660. email.IsPrimary = false
  661. }
  662. }
  663. // We alway want the primary email address displayed, even if it's not in
  664. // the emailaddress table (yet)
  665. if !isPrimaryFound {
  666. emails = append(emails, &EmailAddress{
  667. Email: u.Email,
  668. IsActivated: true,
  669. IsPrimary: true,
  670. })
  671. }
  672. return emails, nil
  673. }
  674. func AddEmailAddress(email *EmailAddress) error {
  675. email.Email = strings.ToLower(email.Email)
  676. used, err := IsEmailUsed(email.Email)
  677. if err != nil {
  678. return err
  679. } else if used {
  680. return ErrEmailAlreadyUsed{email.Email}
  681. }
  682. _, err = x.Insert(email)
  683. return err
  684. }
  685. func (email *EmailAddress) Activate() error {
  686. email.IsActivated = true
  687. if _, err := x.Id(email.Id).AllCols().Update(email); err != nil {
  688. return err
  689. }
  690. if user, err := GetUserByID(email.Uid); err != nil {
  691. return err
  692. } else {
  693. user.Rands = GetUserSalt()
  694. return UpdateUser(user)
  695. }
  696. }
  697. func DeleteEmailAddress(email *EmailAddress) error {
  698. has, err := x.Get(email)
  699. if err != nil {
  700. return err
  701. } else if !has {
  702. return ErrEmailNotExist
  703. }
  704. if _, err = x.Id(email.Id).Delete(email); err != nil {
  705. return err
  706. }
  707. return nil
  708. }
  709. func MakeEmailPrimary(email *EmailAddress) error {
  710. has, err := x.Get(email)
  711. if err != nil {
  712. return err
  713. } else if !has {
  714. return ErrEmailNotExist
  715. }
  716. if !email.IsActivated {
  717. return ErrEmailNotActivated
  718. }
  719. user := &User{Id: email.Uid}
  720. has, err = x.Get(user)
  721. if err != nil {
  722. return err
  723. } else if !has {
  724. return ErrUserNotExist{email.Uid, ""}
  725. }
  726. // Make sure the former primary email doesn't disappear
  727. former_primary_email := &EmailAddress{Email: user.Email}
  728. has, err = x.Get(former_primary_email)
  729. if err != nil {
  730. return err
  731. } else if !has {
  732. former_primary_email.Uid = user.Id
  733. former_primary_email.IsActivated = user.IsActive
  734. x.Insert(former_primary_email)
  735. }
  736. user.Email = email.Email
  737. _, err = x.Id(user.Id).AllCols().Update(user)
  738. return err
  739. }
  740. // UserCommit represents a commit with validation of user.
  741. type UserCommit struct {
  742. User *User
  743. *git.Commit
  744. }
  745. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  746. func ValidateCommitWithEmail(c *git.Commit) *User {
  747. u, err := GetUserByEmail(c.Author.Email)
  748. if err != nil {
  749. return nil
  750. }
  751. return u
  752. }
  753. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  754. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  755. var (
  756. u *User
  757. emails = map[string]*User{}
  758. newCommits = list.New()
  759. e = oldCommits.Front()
  760. )
  761. for e != nil {
  762. c := e.Value.(*git.Commit)
  763. if v, ok := emails[c.Author.Email]; !ok {
  764. u, _ = GetUserByEmail(c.Author.Email)
  765. emails[c.Author.Email] = u
  766. } else {
  767. u = v
  768. }
  769. newCommits.PushBack(UserCommit{
  770. User: u,
  771. Commit: c,
  772. })
  773. e = e.Next()
  774. }
  775. return newCommits
  776. }
  777. // GetUserByEmail returns the user object by given e-mail if exists.
  778. func GetUserByEmail(email string) (*User, error) {
  779. if len(email) == 0 {
  780. return nil, ErrUserNotExist{0, "email"}
  781. }
  782. email = strings.ToLower(email)
  783. // First try to find the user by primary email
  784. user := &User{Email: email}
  785. has, err := x.Get(user)
  786. if err != nil {
  787. return nil, err
  788. }
  789. if has {
  790. return user, nil
  791. }
  792. // Otherwise, check in alternative list for activated email addresses
  793. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  794. has, err = x.Get(emailAddress)
  795. if err != nil {
  796. return nil, err
  797. }
  798. if has {
  799. return GetUserByID(emailAddress.Uid)
  800. }
  801. return nil, ErrUserNotExist{0, "email"}
  802. }
  803. // SearchUserByName returns given number of users whose name contains keyword.
  804. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  805. if len(opt.Keyword) == 0 {
  806. return us, nil
  807. }
  808. opt.Keyword = strings.ToLower(opt.Keyword)
  809. us = make([]*User, 0, opt.Limit)
  810. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  811. return us, err
  812. }
  813. // Follow is connection request for receiving user notification.
  814. type Follow struct {
  815. ID int64 `xorm:"pk autoincr"`
  816. UserID int64 `xorm:"UNIQUE(follow)"`
  817. FollowID int64 `xorm:"UNIQUE(follow)"`
  818. }
  819. // FollowUser marks someone be another's follower.
  820. func FollowUser(userId int64, followId int64) (err error) {
  821. sess := x.NewSession()
  822. defer sess.Close()
  823. sess.Begin()
  824. if _, err = sess.Insert(&Follow{UserID: userId, FollowID: followId}); err != nil {
  825. sess.Rollback()
  826. return err
  827. }
  828. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  829. if _, err = sess.Exec(rawSql, followId); err != nil {
  830. sess.Rollback()
  831. return err
  832. }
  833. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  834. if _, err = sess.Exec(rawSql, userId); err != nil {
  835. sess.Rollback()
  836. return err
  837. }
  838. return sess.Commit()
  839. }
  840. // UnFollowUser unmarks someone be another's follower.
  841. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  842. session := x.NewSession()
  843. defer session.Close()
  844. session.Begin()
  845. if _, err = session.Delete(&Follow{UserID: userId, FollowID: unFollowId}); err != nil {
  846. session.Rollback()
  847. return err
  848. }
  849. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  850. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  851. session.Rollback()
  852. return err
  853. }
  854. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  855. if _, err = session.Exec(rawSql, userId); err != nil {
  856. session.Rollback()
  857. return err
  858. }
  859. return session.Commit()
  860. }
  861. func UpdateMentions(userNames []string, issueId int64) error {
  862. for i := range userNames {
  863. userNames[i] = strings.ToLower(userNames[i])
  864. }
  865. users := make([]*User, 0, len(userNames))
  866. if err := x.Where("lower_name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("lower_name ASC").Find(&users); err != nil {
  867. return err
  868. }
  869. ids := make([]int64, 0, len(userNames))
  870. for _, user := range users {
  871. ids = append(ids, user.Id)
  872. if !user.IsOrganization() {
  873. continue
  874. }
  875. if user.NumMembers == 0 {
  876. continue
  877. }
  878. tempIds := make([]int64, 0, user.NumMembers)
  879. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  880. if err != nil {
  881. return err
  882. }
  883. for _, orgUser := range orgUsers {
  884. tempIds = append(tempIds, orgUser.ID)
  885. }
  886. ids = append(ids, tempIds...)
  887. }
  888. if err := UpdateIssueUsersByMentions(ids, issueId); err != nil {
  889. return err
  890. }
  891. return nil
  892. }