user.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. "errors"
  12. "fmt"
  13. "image"
  14. _ "image/jpeg"
  15. "image/png"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. "github.com/nfnt/resize"
  24. "golang.org/x/crypto/pbkdf2"
  25. "github.com/gogits/git-module"
  26. api "github.com/gogits/go-gogs-client"
  27. "github.com/gogits/gogs/modules/avatar"
  28. "github.com/gogits/gogs/modules/base"
  29. "github.com/gogits/gogs/modules/log"
  30. "github.com/gogits/gogs/modules/markdown"
  31. "github.com/gogits/gogs/modules/setting"
  32. )
  33. type UserType int
  34. const (
  35. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  36. USER_TYPE_ORGANIZATION
  37. )
  38. var (
  39. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  40. ErrEmailNotExist = errors.New("E-mail does not exist")
  41. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  42. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  43. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  44. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  45. )
  46. // User represents the object of individual and member of organization.
  47. type User struct {
  48. ID int64 `xorm:"pk autoincr"`
  49. LowerName string `xorm:"UNIQUE NOT NULL"`
  50. Name string `xorm:"UNIQUE NOT NULL"`
  51. FullName string
  52. // Email is the primary email address (to be used for communication)
  53. Email string `xorm:"NOT NULL"`
  54. Passwd string `xorm:"NOT NULL"`
  55. LoginType LoginType
  56. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  57. LoginName string
  58. Type UserType
  59. OwnedOrgs []*User `xorm:"-"`
  60. Orgs []*User `xorm:"-"`
  61. Repos []*Repository `xorm:"-"`
  62. Location string
  63. Website string
  64. Rands string `xorm:"VARCHAR(10)"`
  65. Salt string `xorm:"VARCHAR(10)"`
  66. Created time.Time `xorm:"-"`
  67. CreatedUnix int64
  68. Updated time.Time `xorm:"-"`
  69. UpdatedUnix int64
  70. // Remember visibility choice for convenience, true for private
  71. LastRepoVisibility bool
  72. // Maximum repository creation limit, -1 means use gloabl default
  73. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  74. // Permissions
  75. IsActive bool // Activate primary email
  76. IsAdmin bool
  77. AllowGitHook bool
  78. AllowImportLocal bool // Allow migrate repository by local path
  79. ProhibitLogin bool
  80. // Avatar
  81. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  82. AvatarEmail string `xorm:"NOT NULL"`
  83. UseCustomAvatar bool
  84. // Counters
  85. NumFollowers int
  86. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  87. NumStars int
  88. NumRepos int
  89. // For organization
  90. Description string
  91. NumTeams int
  92. NumMembers int
  93. Teams []*Team `xorm:"-"`
  94. Members []*User `xorm:"-"`
  95. }
  96. func (u *User) BeforeInsert() {
  97. u.CreatedUnix = time.Now().Unix()
  98. u.UpdatedUnix = u.CreatedUnix
  99. }
  100. func (u *User) BeforeUpdate() {
  101. if u.MaxRepoCreation < -1 {
  102. u.MaxRepoCreation = -1
  103. }
  104. u.UpdatedUnix = time.Now().Unix()
  105. }
  106. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  107. switch colName {
  108. case "full_name":
  109. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  110. case "created_unix":
  111. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  112. case "updated_unix":
  113. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  114. }
  115. }
  116. func (u *User) APIFormat() *api.User {
  117. return &api.User{
  118. ID: u.ID,
  119. UserName: u.Name,
  120. FullName: u.FullName,
  121. Email: u.Email,
  122. AvatarUrl: u.AvatarLink(),
  123. }
  124. }
  125. // returns true if user login type is LOGIN_PLAIN.
  126. func (u *User) IsLocal() bool {
  127. return u.LoginType <= LOGIN_PLAIN
  128. }
  129. // HasForkedRepo checks if user has already forked a repository with given ID.
  130. func (u *User) HasForkedRepo(repoID int64) bool {
  131. _, has := HasForkedRepo(u.ID, repoID)
  132. return has
  133. }
  134. func (u *User) RepoCreationNum() int {
  135. if u.MaxRepoCreation <= -1 {
  136. return setting.Repository.MaxCreationLimit
  137. }
  138. return u.MaxRepoCreation
  139. }
  140. func (u *User) CanCreateRepo() bool {
  141. if u.MaxRepoCreation <= -1 {
  142. if setting.Repository.MaxCreationLimit <= -1 {
  143. return true
  144. }
  145. return u.NumRepos < setting.Repository.MaxCreationLimit
  146. }
  147. return u.NumRepos < u.MaxRepoCreation
  148. }
  149. // CanEditGitHook returns true if user can edit Git hooks.
  150. func (u *User) CanEditGitHook() bool {
  151. return u.IsAdmin || u.AllowGitHook
  152. }
  153. // CanImportLocal returns true if user can migrate repository by local path.
  154. func (u *User) CanImportLocal() bool {
  155. return setting.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  156. }
  157. // DashboardLink returns the user dashboard page link.
  158. func (u *User) DashboardLink() string {
  159. if u.IsOrganization() {
  160. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  161. }
  162. return setting.AppSubUrl + "/"
  163. }
  164. // HomeLink returns the user or organization home page link.
  165. func (u *User) HomeLink() string {
  166. return setting.AppSubUrl + "/" + u.Name
  167. }
  168. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  169. func (u *User) GenerateEmailActivateCode(email string) string {
  170. code := base.CreateTimeLimitCode(
  171. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  172. setting.Service.ActiveCodeLives, nil)
  173. // Add tail hex username
  174. code += hex.EncodeToString([]byte(u.LowerName))
  175. return code
  176. }
  177. // GenerateActivateCode generates an activate code based on user information.
  178. func (u *User) GenerateActivateCode() string {
  179. return u.GenerateEmailActivateCode(u.Email)
  180. }
  181. // CustomAvatarPath returns user custom avatar file path.
  182. func (u *User) CustomAvatarPath() string {
  183. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.ID))
  184. }
  185. // GenerateRandomAvatar generates a random avatar for user.
  186. func (u *User) GenerateRandomAvatar() error {
  187. seed := u.Email
  188. if len(seed) == 0 {
  189. seed = u.Name
  190. }
  191. img, err := avatar.RandomImage([]byte(seed))
  192. if err != nil {
  193. return fmt.Errorf("RandomImage: %v", err)
  194. }
  195. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  196. return fmt.Errorf("MkdirAll: %v", err)
  197. }
  198. fw, err := os.Create(u.CustomAvatarPath())
  199. if err != nil {
  200. return fmt.Errorf("Create: %v", err)
  201. }
  202. defer fw.Close()
  203. if err = png.Encode(fw, img); err != nil {
  204. return fmt.Errorf("Encode: %v", err)
  205. }
  206. log.Info("New random avatar created: %d", u.ID)
  207. return nil
  208. }
  209. // RelAvatarLink returns relative avatar link to the site domain,
  210. // which includes app sub-url as prefix. However, it is possible
  211. // to return full URL if user enables Gravatar-like service.
  212. func (u *User) RelAvatarLink() string {
  213. defaultImgUrl := setting.AppSubUrl + "/img/avatar_default.png"
  214. if u.ID == -1 {
  215. return defaultImgUrl
  216. }
  217. switch {
  218. case u.UseCustomAvatar:
  219. if !com.IsExist(u.CustomAvatarPath()) {
  220. return defaultImgUrl
  221. }
  222. return setting.AppSubUrl + "/avatars/" + com.ToStr(u.ID)
  223. case setting.DisableGravatar, setting.OfflineMode:
  224. if !com.IsExist(u.CustomAvatarPath()) {
  225. if err := u.GenerateRandomAvatar(); err != nil {
  226. log.Error(3, "GenerateRandomAvatar: %v", err)
  227. }
  228. }
  229. return setting.AppSubUrl + "/avatars/" + com.ToStr(u.ID)
  230. }
  231. return base.AvatarLink(u.AvatarEmail)
  232. }
  233. // AvatarLink returns user avatar absolute link.
  234. func (u *User) AvatarLink() string {
  235. link := u.RelAvatarLink()
  236. if link[0] == '/' && link[1] != '/' {
  237. return setting.AppUrl + strings.TrimPrefix(link, setting.AppSubUrl)[1:]
  238. }
  239. return link
  240. }
  241. // User.GetFollwoers returns range of user's followers.
  242. func (u *User) GetFollowers(page int) ([]*User, error) {
  243. users := make([]*User, 0, ItemsPerPage)
  244. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  245. if setting.UsePostgreSQL {
  246. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  247. } else {
  248. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  249. }
  250. return users, sess.Find(&users)
  251. }
  252. func (u *User) IsFollowing(followID int64) bool {
  253. return IsFollowing(u.ID, followID)
  254. }
  255. // GetFollowing returns range of user's following.
  256. func (u *User) GetFollowing(page int) ([]*User, error) {
  257. users := make([]*User, 0, ItemsPerPage)
  258. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  259. if setting.UsePostgreSQL {
  260. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  261. } else {
  262. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  263. }
  264. return users, sess.Find(&users)
  265. }
  266. // NewGitSig generates and returns the signature of given user.
  267. func (u *User) NewGitSig() *git.Signature {
  268. return &git.Signature{
  269. Name: u.DisplayName(),
  270. Email: u.Email,
  271. When: time.Now(),
  272. }
  273. }
  274. // EncodePasswd encodes password to safe format.
  275. func (u *User) EncodePasswd() {
  276. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  277. u.Passwd = fmt.Sprintf("%x", newPasswd)
  278. }
  279. // ValidatePassword checks if given password matches the one belongs to the user.
  280. func (u *User) ValidatePassword(passwd string) bool {
  281. newUser := &User{Passwd: passwd, Salt: u.Salt}
  282. newUser.EncodePasswd()
  283. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  284. }
  285. // UploadAvatar saves custom avatar for user.
  286. // FIXME: split uploads to different subdirs in case we have massive users.
  287. func (u *User) UploadAvatar(data []byte) error {
  288. img, _, err := image.Decode(bytes.NewReader(data))
  289. if err != nil {
  290. return fmt.Errorf("Decode: %v", err)
  291. }
  292. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  293. sess := x.NewSession()
  294. defer sessionRelease(sess)
  295. if err = sess.Begin(); err != nil {
  296. return err
  297. }
  298. u.UseCustomAvatar = true
  299. if err = updateUser(sess, u); err != nil {
  300. return fmt.Errorf("updateUser: %v", err)
  301. }
  302. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  303. fw, err := os.Create(u.CustomAvatarPath())
  304. if err != nil {
  305. return fmt.Errorf("Create: %v", err)
  306. }
  307. defer fw.Close()
  308. if err = png.Encode(fw, m); err != nil {
  309. return fmt.Errorf("Encode: %v", err)
  310. }
  311. return sess.Commit()
  312. }
  313. // DeleteAvatar deletes the user's custom avatar.
  314. func (u *User) DeleteAvatar() error {
  315. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  316. os.Remove(u.CustomAvatarPath())
  317. u.UseCustomAvatar = false
  318. if err := UpdateUser(u); err != nil {
  319. return fmt.Errorf("UpdateUser: %v", err)
  320. }
  321. return nil
  322. }
  323. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  324. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  325. has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
  326. if err != nil {
  327. log.Error(3, "HasAccess: %v", err)
  328. }
  329. return has
  330. }
  331. // IsWriterOfRepo returns true if user has write access to given repository.
  332. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  333. has, err := HasAccess(u, repo, ACCESS_MODE_WRITE)
  334. if err != nil {
  335. log.Error(3, "HasAccess: %v", err)
  336. }
  337. return has
  338. }
  339. // IsOrganization returns true if user is actually a organization.
  340. func (u *User) IsOrganization() bool {
  341. return u.Type == USER_TYPE_ORGANIZATION
  342. }
  343. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  344. func (u *User) IsUserOrgOwner(orgId int64) bool {
  345. return IsOrganizationOwner(orgId, u.ID)
  346. }
  347. // IsPublicMember returns true if user public his/her membership in give organization.
  348. func (u *User) IsPublicMember(orgId int64) bool {
  349. return IsPublicMembership(orgId, u.ID)
  350. }
  351. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  352. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  353. }
  354. // GetOrganizationCount returns count of membership of organization of user.
  355. func (u *User) GetOrganizationCount() (int64, error) {
  356. return u.getOrganizationCount(x)
  357. }
  358. // GetRepositories returns repositories that user owns, including private repositories.
  359. func (u *User) GetRepositories(page, pageSize int) (err error) {
  360. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  361. UserID: u.ID,
  362. Private: true,
  363. Page: page,
  364. PageSize: pageSize,
  365. })
  366. return err
  367. }
  368. // GetRepositories returns mirror repositories that user owns, including private repositories.
  369. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  370. return GetUserMirrorRepositories(u.ID)
  371. }
  372. // GetOwnedOrganizations returns all organizations that user owns.
  373. func (u *User) GetOwnedOrganizations() (err error) {
  374. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  375. return err
  376. }
  377. // GetOrganizations returns all organizations that user belongs to.
  378. func (u *User) GetOrganizations(all bool) error {
  379. ous, err := GetOrgUsersByUserID(u.ID, all)
  380. if err != nil {
  381. return err
  382. }
  383. u.Orgs = make([]*User, len(ous))
  384. for i, ou := range ous {
  385. u.Orgs[i], err = GetUserByID(ou.OrgID)
  386. if err != nil {
  387. return err
  388. }
  389. }
  390. return nil
  391. }
  392. // DisplayName returns full name if it's not empty,
  393. // returns username otherwise.
  394. func (u *User) DisplayName() string {
  395. if len(u.FullName) > 0 {
  396. return u.FullName
  397. }
  398. return u.Name
  399. }
  400. func (u *User) ShortName(length int) string {
  401. return base.EllipsisString(u.Name, length)
  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 ErrNameEmpty
  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. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  574. }
  575. func updateUser(e Engine, u *User) error {
  576. // Organization does not need email
  577. if !u.IsOrganization() {
  578. u.Email = strings.ToLower(u.Email)
  579. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  580. if err != nil {
  581. return err
  582. } else if has {
  583. return ErrEmailAlreadyUsed{u.Email}
  584. }
  585. if len(u.AvatarEmail) == 0 {
  586. u.AvatarEmail = u.Email
  587. }
  588. u.Avatar = base.HashEmail(u.AvatarEmail)
  589. }
  590. u.LowerName = strings.ToLower(u.Name)
  591. u.Location = base.TruncateString(u.Location, 255)
  592. u.Website = base.TruncateString(u.Website, 255)
  593. u.Description = base.TruncateString(u.Description, 255)
  594. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  595. _, err := e.Id(u.ID).AllCols().Update(u)
  596. return err
  597. }
  598. // UpdateUser updates user's information.
  599. func UpdateUser(u *User) error {
  600. return updateUser(x, u)
  601. }
  602. // deleteBeans deletes all given beans, beans should contain delete conditions.
  603. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  604. for i := range beans {
  605. if _, err = e.Delete(beans[i]); err != nil {
  606. return err
  607. }
  608. }
  609. return nil
  610. }
  611. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  612. func deleteUser(e *xorm.Session, u *User) error {
  613. // Note: A user owns any repository or belongs to any organization
  614. // cannot perform delete operation.
  615. // Check ownership of repository.
  616. count, err := getRepositoryCount(e, u)
  617. if err != nil {
  618. return fmt.Errorf("GetRepositoryCount: %v", err)
  619. } else if count > 0 {
  620. return ErrUserOwnRepos{UID: u.ID}
  621. }
  622. // Check membership of organization.
  623. count, err = u.getOrganizationCount(e)
  624. if err != nil {
  625. return fmt.Errorf("GetOrganizationCount: %v", err)
  626. } else if count > 0 {
  627. return ErrUserHasOrgs{UID: u.ID}
  628. }
  629. // ***** START: Watch *****
  630. watches := make([]*Watch, 0, 10)
  631. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  632. return fmt.Errorf("get all watches: %v", err)
  633. }
  634. for i := range watches {
  635. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  636. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  637. }
  638. }
  639. // ***** END: Watch *****
  640. // ***** START: Star *****
  641. stars := make([]*Star, 0, 10)
  642. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  643. return fmt.Errorf("get all stars: %v", err)
  644. }
  645. for i := range stars {
  646. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  647. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  648. }
  649. }
  650. // ***** END: Star *****
  651. // ***** START: Follow *****
  652. followers := make([]*Follow, 0, 10)
  653. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  654. return fmt.Errorf("get all followers: %v", err)
  655. }
  656. for i := range followers {
  657. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  658. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  659. }
  660. }
  661. // ***** END: Follow *****
  662. if err = deleteBeans(e,
  663. &AccessToken{UID: u.ID},
  664. &Collaboration{UserID: u.ID},
  665. &Access{UserID: u.ID},
  666. &Watch{UserID: u.ID},
  667. &Star{UID: u.ID},
  668. &Follow{FollowID: u.ID},
  669. &Action{UserID: u.ID},
  670. &IssueUser{UID: u.ID},
  671. &EmailAddress{UID: u.ID},
  672. ); err != nil {
  673. return fmt.Errorf("deleteBeans: %v", err)
  674. }
  675. // ***** START: PublicKey *****
  676. keys := make([]*PublicKey, 0, 10)
  677. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  678. return fmt.Errorf("get all public keys: %v", err)
  679. }
  680. keyIDs := make([]int64, len(keys))
  681. for i := range keys {
  682. keyIDs[i] = keys[i].ID
  683. }
  684. if err = deletePublicKeys(e, keyIDs...); err != nil {
  685. return fmt.Errorf("deletePublicKeys: %v", err)
  686. }
  687. // ***** END: PublicKey *****
  688. // Clear assignee.
  689. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  690. return fmt.Errorf("clear assignee: %v", err)
  691. }
  692. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  693. return fmt.Errorf("Delete: %v", err)
  694. }
  695. // FIXME: system notice
  696. // Note: There are something just cannot be roll back,
  697. // so just keep error logs of those operations.
  698. os.RemoveAll(UserPath(u.Name))
  699. os.Remove(u.CustomAvatarPath())
  700. return nil
  701. }
  702. // DeleteUser completely and permanently deletes everything of a user,
  703. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  704. func DeleteUser(u *User) (err error) {
  705. sess := x.NewSession()
  706. defer sessionRelease(sess)
  707. if err = sess.Begin(); err != nil {
  708. return err
  709. }
  710. if err = deleteUser(sess, u); err != nil {
  711. // Note: don't wrapper error here.
  712. return err
  713. }
  714. if err = sess.Commit(); err != nil {
  715. return err
  716. }
  717. return RewriteAllPublicKeys()
  718. }
  719. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  720. func DeleteInactivateUsers() (err error) {
  721. users := make([]*User, 0, 10)
  722. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  723. return fmt.Errorf("get all inactive users: %v", err)
  724. }
  725. // FIXME: should only update authorized_keys file once after all deletions.
  726. for _, u := range users {
  727. if err = DeleteUser(u); err != nil {
  728. // Ignore users that were set inactive by admin.
  729. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  730. continue
  731. }
  732. return err
  733. }
  734. }
  735. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  736. return err
  737. }
  738. // UserPath returns the path absolute path of user repositories.
  739. func UserPath(userName string) string {
  740. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  741. }
  742. func GetUserByKeyID(keyID int64) (*User, error) {
  743. user := new(User)
  744. 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)
  745. if err != nil {
  746. return nil, err
  747. } else if !has {
  748. return nil, ErrUserNotKeyOwner
  749. }
  750. return user, nil
  751. }
  752. func getUserByID(e Engine, id int64) (*User, error) {
  753. u := new(User)
  754. has, err := e.Id(id).Get(u)
  755. if err != nil {
  756. return nil, err
  757. } else if !has {
  758. return nil, ErrUserNotExist{id, ""}
  759. }
  760. return u, nil
  761. }
  762. // GetUserByID returns the user object by given ID if exists.
  763. func GetUserByID(id int64) (*User, error) {
  764. return getUserByID(x, id)
  765. }
  766. // GetAssigneeByID returns the user with write access of repository by given ID.
  767. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  768. has, err := HasAccess(&User{ID: userID}, repo, ACCESS_MODE_WRITE)
  769. if err != nil {
  770. return nil, err
  771. } else if !has {
  772. return nil, ErrUserNotExist{userID, ""}
  773. }
  774. return GetUserByID(userID)
  775. }
  776. // GetUserByName returns user by given name.
  777. func GetUserByName(name string) (*User, error) {
  778. if len(name) == 0 {
  779. return nil, ErrUserNotExist{0, name}
  780. }
  781. u := &User{LowerName: strings.ToLower(name)}
  782. has, err := x.Get(u)
  783. if err != nil {
  784. return nil, err
  785. } else if !has {
  786. return nil, ErrUserNotExist{0, name}
  787. }
  788. return u, nil
  789. }
  790. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  791. func GetUserEmailsByNames(names []string) []string {
  792. mails := make([]string, 0, len(names))
  793. for _, name := range names {
  794. u, err := GetUserByName(name)
  795. if err != nil {
  796. continue
  797. }
  798. mails = append(mails, u.Email)
  799. }
  800. return mails
  801. }
  802. // GetUserIDsByNames returns a slice of ids corresponds to names.
  803. func GetUserIDsByNames(names []string) []int64 {
  804. ids := make([]int64, 0, len(names))
  805. for _, name := range names {
  806. u, err := GetUserByName(name)
  807. if err != nil {
  808. continue
  809. }
  810. ids = append(ids, u.ID)
  811. }
  812. return ids
  813. }
  814. // UserCommit represents a commit with validation of user.
  815. type UserCommit struct {
  816. User *User
  817. *git.Commit
  818. }
  819. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  820. func ValidateCommitWithEmail(c *git.Commit) *User {
  821. u, err := GetUserByEmail(c.Author.Email)
  822. if err != nil {
  823. return nil
  824. }
  825. return u
  826. }
  827. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  828. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  829. var (
  830. u *User
  831. emails = map[string]*User{}
  832. newCommits = list.New()
  833. e = oldCommits.Front()
  834. )
  835. for e != nil {
  836. c := e.Value.(*git.Commit)
  837. if v, ok := emails[c.Author.Email]; !ok {
  838. u, _ = GetUserByEmail(c.Author.Email)
  839. emails[c.Author.Email] = u
  840. } else {
  841. u = v
  842. }
  843. newCommits.PushBack(UserCommit{
  844. User: u,
  845. Commit: c,
  846. })
  847. e = e.Next()
  848. }
  849. return newCommits
  850. }
  851. // GetUserByEmail returns the user object by given e-mail if exists.
  852. func GetUserByEmail(email string) (*User, error) {
  853. if len(email) == 0 {
  854. return nil, ErrUserNotExist{0, "email"}
  855. }
  856. email = strings.ToLower(email)
  857. // First try to find the user by primary email
  858. user := &User{Email: email}
  859. has, err := x.Get(user)
  860. if err != nil {
  861. return nil, err
  862. }
  863. if has {
  864. return user, nil
  865. }
  866. // Otherwise, check in alternative list for activated email addresses
  867. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  868. has, err = x.Get(emailAddress)
  869. if err != nil {
  870. return nil, err
  871. }
  872. if has {
  873. return GetUserByID(emailAddress.UID)
  874. }
  875. return nil, ErrUserNotExist{0, email}
  876. }
  877. type SearchUserOptions struct {
  878. Keyword string
  879. Type UserType
  880. OrderBy string
  881. Page int
  882. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  883. }
  884. // SearchUserByName takes keyword and part of user name to search,
  885. // it returns results in given range and number of total results.
  886. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  887. if len(opts.Keyword) == 0 {
  888. return users, 0, nil
  889. }
  890. opts.Keyword = strings.ToLower(opts.Keyword)
  891. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  892. opts.PageSize = setting.UI.ExplorePagingNum
  893. }
  894. if opts.Page <= 0 {
  895. opts.Page = 1
  896. }
  897. searchQuery := "%" + opts.Keyword + "%"
  898. users = make([]*User, 0, opts.PageSize)
  899. // Append conditions
  900. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  901. Or("LOWER(full_name) LIKE ?", searchQuery).
  902. And("type = ?", opts.Type)
  903. var countSess xorm.Session
  904. countSess = *sess
  905. count, err := countSess.Count(new(User))
  906. if err != nil {
  907. return nil, 0, fmt.Errorf("Count: %v", err)
  908. }
  909. if len(opts.OrderBy) > 0 {
  910. sess.OrderBy(opts.OrderBy)
  911. }
  912. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  913. }
  914. // ___________ .__ .__
  915. // \_ _____/___ | | | | ______ _ __
  916. // | __)/ _ \| | | | / _ \ \/ \/ /
  917. // | \( <_> ) |_| |_( <_> ) /
  918. // \___ / \____/|____/____/\____/ \/\_/
  919. // \/
  920. // Follow represents relations of user and his/her followers.
  921. type Follow struct {
  922. ID int64 `xorm:"pk autoincr"`
  923. UserID int64 `xorm:"UNIQUE(follow)"`
  924. FollowID int64 `xorm:"UNIQUE(follow)"`
  925. }
  926. func IsFollowing(userID, followID int64) bool {
  927. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  928. return has
  929. }
  930. // FollowUser marks someone be another's follower.
  931. func FollowUser(userID, followID int64) (err error) {
  932. if userID == followID || IsFollowing(userID, followID) {
  933. return nil
  934. }
  935. sess := x.NewSession()
  936. defer sessionRelease(sess)
  937. if err = sess.Begin(); err != nil {
  938. return err
  939. }
  940. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  941. return err
  942. }
  943. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  944. return err
  945. }
  946. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  947. return err
  948. }
  949. return sess.Commit()
  950. }
  951. // UnfollowUser unmarks someone be another's follower.
  952. func UnfollowUser(userID, followID int64) (err error) {
  953. if userID == followID || !IsFollowing(userID, followID) {
  954. return nil
  955. }
  956. sess := x.NewSession()
  957. defer sessionRelease(sess)
  958. if err = sess.Begin(); err != nil {
  959. return err
  960. }
  961. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  962. return err
  963. }
  964. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  965. return err
  966. }
  967. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  968. return err
  969. }
  970. return sess.Commit()
  971. }