user.go 32 KB

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