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

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