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