user.go 34 KB

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