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