user.go 32 KB

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