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

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