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

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