user.go 32 KB

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