user.go 30 KB

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