user.go 32 KB

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