user.go 32 KB

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