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