user.go 30 KB

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