user.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. "crypto/sha256"
  8. "crypto/subtle"
  9. "encoding/hex"
  10. "fmt"
  11. "image"
  12. _ "image/jpeg"
  13. "image/png"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/nfnt/resize"
  20. "github.com/unknwon/com"
  21. "golang.org/x/crypto/pbkdf2"
  22. log "unknwon.dev/clog/v2"
  23. "xorm.io/xorm"
  24. "github.com/gogs/git-module"
  25. api "github.com/gogs/go-gogs-client"
  26. "gogs.io/gogs/internal/avatar"
  27. "gogs.io/gogs/internal/conf"
  28. "gogs.io/gogs/internal/db/errors"
  29. "gogs.io/gogs/internal/errutil"
  30. "gogs.io/gogs/internal/strutil"
  31. "gogs.io/gogs/internal/tool"
  32. )
  33. // USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
  34. const USER_AVATAR_URL_PREFIX = "avatars"
  35. type UserType int
  36. const (
  37. UserIndividual UserType = iota // Historic reason to make it starts at 0.
  38. UserOrganization
  39. )
  40. // User represents the object of individual and member of organization.
  41. type User struct {
  42. ID int64
  43. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"UNIQUE"`
  44. Name string `xorm:"UNIQUE NOT NULL" gorm:"NOT NULL"`
  45. FullName string
  46. // Email is the primary email address (to be used for communication)
  47. Email string `xorm:"NOT NULL" gorm:"NOT NULL"`
  48. Passwd string `xorm:"NOT NULL" gorm:"NOT NULL"`
  49. LoginType LoginType // TODO: Remove me https://github.com/gogs/gogs/issues/6117.
  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.LoginType <= LoginPlain
  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 len(seed) == 0 {
  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.GetFollwoers 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. has, err := HasAccess(u.ID, repo, AccessModeAdmin)
  319. if err != nil {
  320. log.Error("HasAccess: %v", err)
  321. }
  322. return has
  323. }
  324. // IsWriterOfRepo returns true if user has write access to given repository.
  325. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  326. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  327. if err != nil {
  328. log.Error("HasAccess: %v", err)
  329. }
  330. return has
  331. }
  332. // IsOrganization returns true if user is actually a organization.
  333. func (u *User) IsOrganization() bool {
  334. return u.Type == UserOrganization
  335. }
  336. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  337. func (u *User) IsUserOrgOwner(orgId int64) bool {
  338. return IsOrganizationOwner(orgId, u.ID)
  339. }
  340. // IsPublicMember returns true if user public his/her membership in give organization.
  341. func (u *User) IsPublicMember(orgId int64) bool {
  342. return IsPublicMembership(orgId, u.ID)
  343. }
  344. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  345. func (u *User) IsEnabledTwoFactor() bool {
  346. return TwoFactors.IsUserEnabled(u.ID)
  347. }
  348. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  349. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  350. }
  351. // GetOrganizationCount returns count of membership of organization of user.
  352. func (u *User) GetOrganizationCount() (int64, error) {
  353. return u.getOrganizationCount(x)
  354. }
  355. // GetRepositories returns repositories that user owns, including private repositories.
  356. func (u *User) GetRepositories(page, pageSize int) (err error) {
  357. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  358. UserID: u.ID,
  359. Private: true,
  360. Page: page,
  361. PageSize: pageSize,
  362. })
  363. return err
  364. }
  365. // GetRepositories returns mirror repositories that user owns, including private repositories.
  366. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  367. return GetUserMirrorRepositories(u.ID)
  368. }
  369. // GetOwnedOrganizations returns all organizations that user owns.
  370. func (u *User) GetOwnedOrganizations() (err error) {
  371. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  372. return err
  373. }
  374. // GetOrganizations returns all organizations that user belongs to.
  375. func (u *User) GetOrganizations(showPrivate bool) error {
  376. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  377. if err != nil {
  378. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  379. }
  380. if len(orgIDs) == 0 {
  381. return nil
  382. }
  383. u.Orgs = make([]*User, 0, len(orgIDs))
  384. if err = x.Where("type = ?", UserOrganization).In("id", orgIDs).Find(&u.Orgs); err != nil {
  385. return err
  386. }
  387. return nil
  388. }
  389. // DisplayName returns full name if it's not empty,
  390. // returns username otherwise.
  391. func (u *User) DisplayName() string {
  392. if len(u.FullName) > 0 {
  393. return u.FullName
  394. }
  395. return u.Name
  396. }
  397. func (u *User) ShortName(length int) string {
  398. return tool.EllipsisString(u.Name, length)
  399. }
  400. // IsMailable checks if a user is elegible
  401. // to receive emails.
  402. func (u *User) IsMailable() bool {
  403. return u.IsActive
  404. }
  405. // IsUserExist checks if given user name exist,
  406. // the user name should be noncased unique.
  407. // If uid is presented, then check will rule out that one,
  408. // it is used when update a user name in settings page.
  409. func IsUserExist(uid int64, name string) (bool, error) {
  410. if len(name) == 0 {
  411. return false, nil
  412. }
  413. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  414. }
  415. // GetUserSalt returns a random user salt token.
  416. func GetUserSalt() (string, error) {
  417. return strutil.RandomChars(10)
  418. }
  419. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  420. func NewGhostUser() *User {
  421. return &User{
  422. ID: -1,
  423. Name: "Ghost",
  424. LowerName: "ghost",
  425. }
  426. }
  427. var (
  428. 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", ".", ".."}
  429. reservedUserPatterns = []string{"*.keys"}
  430. )
  431. type ErrNameNotAllowed struct {
  432. args errutil.Args
  433. }
  434. func IsErrNameNotAllowed(err error) bool {
  435. _, ok := err.(ErrNameNotAllowed)
  436. return ok
  437. }
  438. func (err ErrNameNotAllowed) Value() string {
  439. val, ok := err.args["name"].(string)
  440. if ok {
  441. return val
  442. }
  443. val, ok = err.args["pattern"].(string)
  444. if ok {
  445. return val
  446. }
  447. return "<value not found>"
  448. }
  449. func (err ErrNameNotAllowed) Error() string {
  450. return fmt.Sprintf("name is not allowed: %v", err.args)
  451. }
  452. // isNameAllowed checks if name is reserved or pattern of name is not allowed
  453. // based on given reserved names and patterns.
  454. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  455. func isNameAllowed(names, patterns []string, name string) error {
  456. name = strings.TrimSpace(strings.ToLower(name))
  457. if utf8.RuneCountInString(name) == 0 {
  458. return ErrNameNotAllowed{args: errutil.Args{"reason": "empty name"}}
  459. }
  460. for i := range names {
  461. if name == names[i] {
  462. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "name": name}}
  463. }
  464. }
  465. for _, pat := range patterns {
  466. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  467. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  468. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": pat}}
  469. }
  470. }
  471. return nil
  472. }
  473. // isUsernameAllowed return an error if given name is a reserved name or pattern for users.
  474. func isUsernameAllowed(name string) error {
  475. return isNameAllowed(reservedUsernames, reservedUserPatterns, name)
  476. }
  477. // CreateUser creates record of a new user.
  478. // Deprecated: Use Users.Create instead.
  479. func CreateUser(u *User) (err error) {
  480. if err = isUsernameAllowed(u.Name); err != nil {
  481. return err
  482. }
  483. isExist, err := IsUserExist(0, u.Name)
  484. if err != nil {
  485. return err
  486. } else if isExist {
  487. return ErrUserAlreadyExist{args: errutil.Args{"name": u.Name}}
  488. }
  489. u.Email = strings.ToLower(u.Email)
  490. isExist, err = IsEmailUsed(u.Email)
  491. if err != nil {
  492. return err
  493. } else if isExist {
  494. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  495. }
  496. u.LowerName = strings.ToLower(u.Name)
  497. u.AvatarEmail = u.Email
  498. u.Avatar = tool.HashEmail(u.AvatarEmail)
  499. if u.Rands, err = GetUserSalt(); err != nil {
  500. return err
  501. }
  502. if u.Salt, err = GetUserSalt(); err != nil {
  503. return err
  504. }
  505. u.EncodePassword()
  506. u.MaxRepoCreation = -1
  507. sess := x.NewSession()
  508. defer sess.Close()
  509. if err = sess.Begin(); err != nil {
  510. return err
  511. }
  512. if _, err = sess.Insert(u); err != nil {
  513. return err
  514. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  515. return err
  516. }
  517. return sess.Commit()
  518. }
  519. func countUsers(e Engine) int64 {
  520. count, _ := e.Where("type=0").Count(new(User))
  521. return count
  522. }
  523. // CountUsers returns number of users.
  524. func CountUsers() int64 {
  525. return countUsers(x)
  526. }
  527. // Users returns number of users in given page.
  528. func ListUsers(page, pageSize int) ([]*User, error) {
  529. users := make([]*User, 0, pageSize)
  530. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  531. }
  532. // parseUserFromCode returns user by username encoded in code.
  533. // It returns nil if code or username is invalid.
  534. func parseUserFromCode(code string) (user *User) {
  535. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  536. return nil
  537. }
  538. // Use tail hex username to query user
  539. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  540. if b, err := hex.DecodeString(hexStr); err == nil {
  541. if user, err = GetUserByName(string(b)); user != nil {
  542. return user
  543. } else if !IsErrUserNotExist(err) {
  544. log.Error("Failed to get user by name %q: %v", string(b), err)
  545. }
  546. }
  547. return nil
  548. }
  549. // verify active code when active account
  550. func VerifyUserActiveCode(code string) (user *User) {
  551. minutes := conf.Auth.ActivateCodeLives
  552. if user = parseUserFromCode(code); user != nil {
  553. // time limit code
  554. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  555. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  556. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  557. return user
  558. }
  559. }
  560. return nil
  561. }
  562. // verify active code when active account
  563. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  564. minutes := conf.Auth.ActivateCodeLives
  565. if user := parseUserFromCode(code); user != nil {
  566. // time limit code
  567. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  568. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  569. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  570. emailAddress := &EmailAddress{Email: email}
  571. if has, _ := x.Get(emailAddress); has {
  572. return emailAddress
  573. }
  574. }
  575. }
  576. return nil
  577. }
  578. // ChangeUserName changes all corresponding setting from old user name to new one.
  579. func ChangeUserName(u *User, newUserName string) (err error) {
  580. if err = isUsernameAllowed(newUserName); err != nil {
  581. return err
  582. }
  583. isExist, err := IsUserExist(0, newUserName)
  584. if err != nil {
  585. return err
  586. } else if isExist {
  587. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  588. }
  589. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  590. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  591. }
  592. // Delete all local copies of repositories and wikis the user owns.
  593. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  594. repo := bean.(*Repository)
  595. deleteRepoLocalCopy(repo)
  596. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  597. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  598. return nil
  599. }); err != nil {
  600. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  601. }
  602. // Rename or create user base directory
  603. baseDir := UserPath(u.Name)
  604. newBaseDir := UserPath(newUserName)
  605. if com.IsExist(baseDir) {
  606. return os.Rename(baseDir, newBaseDir)
  607. }
  608. return os.MkdirAll(newBaseDir, os.ModePerm)
  609. }
  610. func updateUser(e Engine, u *User) error {
  611. // Organization does not need email
  612. if !u.IsOrganization() {
  613. u.Email = strings.ToLower(u.Email)
  614. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  615. if err != nil {
  616. return err
  617. } else if has {
  618. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  619. }
  620. if len(u.AvatarEmail) == 0 {
  621. u.AvatarEmail = u.Email
  622. }
  623. u.Avatar = tool.HashEmail(u.AvatarEmail)
  624. }
  625. u.LowerName = strings.ToLower(u.Name)
  626. u.Location = tool.TruncateString(u.Location, 255)
  627. u.Website = tool.TruncateString(u.Website, 255)
  628. u.Description = tool.TruncateString(u.Description, 255)
  629. _, err := e.ID(u.ID).AllCols().Update(u)
  630. return err
  631. }
  632. // UpdateUser updates user's information.
  633. func UpdateUser(u *User) error {
  634. return updateUser(x, u)
  635. }
  636. // deleteBeans deletes all given beans, beans should contain delete conditions.
  637. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  638. for i := range beans {
  639. if _, err = e.Delete(beans[i]); err != nil {
  640. return err
  641. }
  642. }
  643. return nil
  644. }
  645. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  646. func deleteUser(e *xorm.Session, u *User) error {
  647. // Note: A user owns any repository or belongs to any organization
  648. // cannot perform delete operation.
  649. // Check ownership of repository.
  650. count, err := getRepositoryCount(e, u)
  651. if err != nil {
  652. return fmt.Errorf("GetRepositoryCount: %v", err)
  653. } else if count > 0 {
  654. return ErrUserOwnRepos{UID: u.ID}
  655. }
  656. // Check membership of organization.
  657. count, err = u.getOrganizationCount(e)
  658. if err != nil {
  659. return fmt.Errorf("GetOrganizationCount: %v", err)
  660. } else if count > 0 {
  661. return ErrUserHasOrgs{UID: u.ID}
  662. }
  663. // ***** START: Watch *****
  664. watches := make([]*Watch, 0, 10)
  665. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  666. return fmt.Errorf("get all watches: %v", err)
  667. }
  668. for i := range watches {
  669. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  670. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  671. }
  672. }
  673. // ***** END: Watch *****
  674. // ***** START: Star *****
  675. stars := make([]*Star, 0, 10)
  676. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  677. return fmt.Errorf("get all stars: %v", err)
  678. }
  679. for i := range stars {
  680. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  681. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  682. }
  683. }
  684. // ***** END: Star *****
  685. // ***** START: Follow *****
  686. followers := make([]*Follow, 0, 10)
  687. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  688. return fmt.Errorf("get all followers: %v", err)
  689. }
  690. for i := range followers {
  691. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  692. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  693. }
  694. }
  695. // ***** END: Follow *****
  696. if err = deleteBeans(e,
  697. &AccessToken{UserID: u.ID},
  698. &Collaboration{UserID: u.ID},
  699. &Access{UserID: u.ID},
  700. &Watch{UserID: u.ID},
  701. &Star{UID: u.ID},
  702. &Follow{FollowID: u.ID},
  703. &Action{UserID: u.ID},
  704. &IssueUser{UID: u.ID},
  705. &EmailAddress{UID: u.ID},
  706. ); err != nil {
  707. return fmt.Errorf("deleteBeans: %v", err)
  708. }
  709. // ***** START: PublicKey *****
  710. keys := make([]*PublicKey, 0, 10)
  711. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  712. return fmt.Errorf("get all public keys: %v", err)
  713. }
  714. keyIDs := make([]int64, len(keys))
  715. for i := range keys {
  716. keyIDs[i] = keys[i].ID
  717. }
  718. if err = deletePublicKeys(e, keyIDs...); err != nil {
  719. return fmt.Errorf("deletePublicKeys: %v", err)
  720. }
  721. // ***** END: PublicKey *****
  722. // Clear assignee.
  723. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  724. return fmt.Errorf("clear assignee: %v", err)
  725. }
  726. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  727. return fmt.Errorf("Delete: %v", err)
  728. }
  729. // FIXME: system notice
  730. // Note: There are something just cannot be roll back,
  731. // so just keep error logs of those operations.
  732. _ = os.RemoveAll(UserPath(u.Name))
  733. _ = os.Remove(u.CustomAvatarPath())
  734. return nil
  735. }
  736. // DeleteUser completely and permanently deletes everything of a user,
  737. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  738. func DeleteUser(u *User) (err error) {
  739. sess := x.NewSession()
  740. defer sess.Close()
  741. if err = sess.Begin(); err != nil {
  742. return err
  743. }
  744. if err = deleteUser(sess, u); err != nil {
  745. // Note: don't wrapper error here.
  746. return err
  747. }
  748. if err = sess.Commit(); err != nil {
  749. return err
  750. }
  751. return RewriteAuthorizedKeys()
  752. }
  753. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  754. func DeleteInactivateUsers() (err error) {
  755. users := make([]*User, 0, 10)
  756. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  757. return fmt.Errorf("get all inactive users: %v", err)
  758. }
  759. // FIXME: should only update authorized_keys file once after all deletions.
  760. for _, u := range users {
  761. if err = DeleteUser(u); err != nil {
  762. // Ignore users that were set inactive by admin.
  763. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  764. continue
  765. }
  766. return err
  767. }
  768. }
  769. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  770. return err
  771. }
  772. // UserPath returns the path absolute path of user repositories.
  773. func UserPath(username string) string {
  774. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  775. }
  776. func GetUserByKeyID(keyID int64) (*User, error) {
  777. user := new(User)
  778. 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)
  779. if err != nil {
  780. return nil, err
  781. } else if !has {
  782. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  783. }
  784. return user, nil
  785. }
  786. func getUserByID(e Engine, id int64) (*User, error) {
  787. u := new(User)
  788. has, err := e.ID(id).Get(u)
  789. if err != nil {
  790. return nil, err
  791. } else if !has {
  792. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  793. }
  794. return u, nil
  795. }
  796. // GetUserByID returns the user object by given ID if exists.
  797. // Deprecated: Use Users.GetByID instead.
  798. func GetUserByID(id int64) (*User, error) {
  799. return getUserByID(x, id)
  800. }
  801. // GetAssigneeByID returns the user with write access of repository by given ID.
  802. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  803. has, err := HasAccess(userID, repo, AccessModeRead)
  804. if err != nil {
  805. return nil, err
  806. } else if !has {
  807. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  808. }
  809. return GetUserByID(userID)
  810. }
  811. // GetUserByName returns a user by given name.
  812. // Deprecated: Use Users.GetByUsername instead.
  813. func GetUserByName(name string) (*User, error) {
  814. if len(name) == 0 {
  815. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  816. }
  817. u := &User{LowerName: strings.ToLower(name)}
  818. has, err := x.Get(u)
  819. if err != nil {
  820. return nil, err
  821. } else if !has {
  822. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  823. }
  824. return u, nil
  825. }
  826. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  827. func GetUserEmailsByNames(names []string) []string {
  828. mails := make([]string, 0, len(names))
  829. for _, name := range names {
  830. u, err := GetUserByName(name)
  831. if err != nil {
  832. continue
  833. }
  834. if u.IsMailable() {
  835. mails = append(mails, u.Email)
  836. }
  837. }
  838. return mails
  839. }
  840. // GetUserIDsByNames returns a slice of ids corresponds to names.
  841. func GetUserIDsByNames(names []string) []int64 {
  842. ids := make([]int64, 0, len(names))
  843. for _, name := range names {
  844. u, err := GetUserByName(name)
  845. if err != nil {
  846. continue
  847. }
  848. ids = append(ids, u.ID)
  849. }
  850. return ids
  851. }
  852. // UserCommit represents a commit with validation of user.
  853. type UserCommit struct {
  854. User *User
  855. *git.Commit
  856. }
  857. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  858. func ValidateCommitWithEmail(c *git.Commit) *User {
  859. u, err := GetUserByEmail(c.Author.Email)
  860. if err != nil {
  861. return nil
  862. }
  863. return u
  864. }
  865. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  866. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  867. emails := make(map[string]*User)
  868. newCommits := make([]*UserCommit, len(oldCommits))
  869. for i := range oldCommits {
  870. var u *User
  871. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  872. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  873. emails[oldCommits[i].Author.Email] = u
  874. } else {
  875. u = v
  876. }
  877. newCommits[i] = &UserCommit{
  878. User: u,
  879. Commit: oldCommits[i],
  880. }
  881. }
  882. return newCommits
  883. }
  884. // GetUserByEmail returns the user object by given e-mail if exists.
  885. // Deprecated: Use Users.GetByEmail instead.
  886. func GetUserByEmail(email string) (*User, error) {
  887. if len(email) == 0 {
  888. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  889. }
  890. email = strings.ToLower(email)
  891. // First try to find the user by primary email
  892. user := &User{Email: email}
  893. has, err := x.Get(user)
  894. if err != nil {
  895. return nil, err
  896. }
  897. if has {
  898. return user, nil
  899. }
  900. // Otherwise, check in alternative list for activated email addresses
  901. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  902. has, err = x.Get(emailAddress)
  903. if err != nil {
  904. return nil, err
  905. }
  906. if has {
  907. return GetUserByID(emailAddress.UID)
  908. }
  909. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  910. }
  911. type SearchUserOptions struct {
  912. Keyword string
  913. Type UserType
  914. OrderBy string
  915. Page int
  916. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  917. }
  918. // SearchUserByName takes keyword and part of user name to search,
  919. // it returns results in given range and number of total results.
  920. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  921. if len(opts.Keyword) == 0 {
  922. return users, 0, nil
  923. }
  924. opts.Keyword = strings.ToLower(opts.Keyword)
  925. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  926. opts.PageSize = conf.UI.ExplorePagingNum
  927. }
  928. if opts.Page <= 0 {
  929. opts.Page = 1
  930. }
  931. searchQuery := "%" + opts.Keyword + "%"
  932. users = make([]*User, 0, opts.PageSize)
  933. // Append conditions
  934. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  935. Or("LOWER(full_name) LIKE ?", searchQuery).
  936. And("type = ?", opts.Type)
  937. countSess := *sess
  938. count, err := countSess.Count(new(User))
  939. if err != nil {
  940. return nil, 0, fmt.Errorf("Count: %v", err)
  941. }
  942. if len(opts.OrderBy) > 0 {
  943. sess.OrderBy(opts.OrderBy)
  944. }
  945. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  946. }
  947. // ___________ .__ .__
  948. // \_ _____/___ | | | | ______ _ __
  949. // | __)/ _ \| | | | / _ \ \/ \/ /
  950. // | \( <_> ) |_| |_( <_> ) /
  951. // \___ / \____/|____/____/\____/ \/\_/
  952. // \/
  953. // Follow represents relations of user and his/her followers.
  954. type Follow struct {
  955. ID int64
  956. UserID int64 `xorm:"UNIQUE(follow)"`
  957. FollowID int64 `xorm:"UNIQUE(follow)"`
  958. }
  959. func IsFollowing(userID, followID int64) bool {
  960. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  961. return has
  962. }
  963. // FollowUser marks someone be another's follower.
  964. func FollowUser(userID, followID int64) (err error) {
  965. if userID == followID || IsFollowing(userID, followID) {
  966. return nil
  967. }
  968. sess := x.NewSession()
  969. defer sess.Close()
  970. if err = sess.Begin(); err != nil {
  971. return err
  972. }
  973. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  974. return err
  975. }
  976. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  977. return err
  978. }
  979. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  980. return err
  981. }
  982. return sess.Commit()
  983. }
  984. // UnfollowUser unmarks someone be another's follower.
  985. func UnfollowUser(userID, followID int64) (err error) {
  986. if userID == followID || !IsFollowing(userID, followID) {
  987. return nil
  988. }
  989. sess := x.NewSession()
  990. defer sess.Close()
  991. if err = sess.Begin(); err != nil {
  992. return err
  993. }
  994. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  995. return err
  996. }
  997. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  998. return err
  999. }
  1000. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1001. return err
  1002. }
  1003. return sess.Commit()
  1004. }