user.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. "github.com/G-Node/gogs/internal/avatar"
  27. "github.com/G-Node/gogs/internal/conf"
  28. "github.com/G-Node/gogs/internal/db/errors"
  29. "github.com/G-Node/gogs/internal/errutil"
  30. "github.com/G-Node/gogs/internal/strutil"
  31. "github.com/G-Node/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. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"NOT NULL;DEFAULT:0"`
  50. LoginName string
  51. Type UserType
  52. OwnedOrgs []*User `xorm:"-" gorm:"-" json:"-"`
  53. Orgs []*User `xorm:"-" gorm:"-" json:"-"`
  54. Repos []*Repository `xorm:"-" gorm:"-" json:"-"`
  55. Location string
  56. Website string
  57. Rands string `xorm:"VARCHAR(10)" gorm:"TYPE:VARCHAR(10)"`
  58. Salt string `xorm:"VARCHAR(10)" gorm:"TYPE:VARCHAR(10)"`
  59. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  60. CreatedUnix int64
  61. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  62. UpdatedUnix int64
  63. // Remember visibility choice for convenience, true for private
  64. LastRepoVisibility bool
  65. // Maximum repository creation limit, -1 means use global default
  66. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"NOT NULL;DEFAULT:-1"`
  67. // Permissions
  68. IsActive bool // Activate primary email
  69. IsAdmin bool
  70. AllowGitHook bool
  71. AllowImportLocal bool // Allow migrate repository by local path
  72. ProhibitLogin bool
  73. // Avatar
  74. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"TYPE:VARCHAR(2048);NOT NULL"`
  75. AvatarEmail string `xorm:"NOT NULL" gorm:"NOT NULL"`
  76. UseCustomAvatar bool
  77. // Counters
  78. NumFollowers int
  79. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"NOT NULL;DEFAULT:0"`
  80. NumStars int
  81. NumRepos int
  82. // For organization
  83. Description string
  84. NumTeams int
  85. NumMembers int
  86. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  87. Members []*User `xorm:"-" gorm:"-" json:"-"`
  88. }
  89. func (u *User) BeforeInsert() {
  90. u.CreatedUnix = time.Now().Unix()
  91. u.UpdatedUnix = u.CreatedUnix
  92. }
  93. func (u *User) BeforeUpdate() {
  94. if u.MaxRepoCreation < -1 {
  95. u.MaxRepoCreation = -1
  96. }
  97. u.UpdatedUnix = time.Now().Unix()
  98. }
  99. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  100. switch colName {
  101. case "created_unix":
  102. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  103. case "updated_unix":
  104. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  105. }
  106. }
  107. // IDStr returns string representation of user's ID.
  108. func (u *User) IDStr() string {
  109. return com.ToStr(u.ID)
  110. }
  111. func (u *User) APIFormat() *api.User {
  112. return &api.User{
  113. ID: u.ID,
  114. UserName: u.Name,
  115. Login: u.Name,
  116. FullName: u.FullName,
  117. Email: u.Email,
  118. AvatarUrl: u.AvatarLink(),
  119. }
  120. }
  121. // returns true if user login type is LoginPlain.
  122. func (u *User) IsLocal() bool {
  123. return u.LoginSource <= 0
  124. }
  125. // HasForkedRepo checks if user has already forked a repository with given ID.
  126. func (u *User) HasForkedRepo(repoID int64) bool {
  127. _, has, _ := HasForkedRepo(u.ID, repoID)
  128. return has
  129. }
  130. func (u *User) RepoCreationNum() int {
  131. if u.MaxRepoCreation <= -1 {
  132. return conf.Repository.MaxCreationLimit
  133. }
  134. return u.MaxRepoCreation
  135. }
  136. func (u *User) CanCreateRepo() bool {
  137. if u.MaxRepoCreation <= -1 {
  138. if conf.Repository.MaxCreationLimit <= -1 {
  139. return true
  140. }
  141. return u.NumRepos < conf.Repository.MaxCreationLimit
  142. }
  143. return u.NumRepos < u.MaxRepoCreation
  144. }
  145. func (u *User) CanCreateOrganization() bool {
  146. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  147. }
  148. // CanEditGitHook returns true if user can edit Git hooks.
  149. func (u *User) CanEditGitHook() bool {
  150. return u.IsAdmin || u.AllowGitHook
  151. }
  152. // CanImportLocal returns true if user can migrate repository by local path.
  153. func (u *User) CanImportLocal() bool {
  154. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  155. }
  156. // DashboardLink returns the user dashboard page link.
  157. func (u *User) DashboardLink() string {
  158. if u.IsOrganization() {
  159. return conf.Server.Subpath + "/org/" + u.Name + "/dashboard/"
  160. }
  161. return conf.Server.Subpath + "/"
  162. }
  163. // HomeLink returns the user or organization home page link.
  164. func (u *User) HomeLink() string {
  165. return conf.Server.Subpath + "/" + u.Name
  166. }
  167. func (u *User) HTMLURL() string {
  168. return conf.Server.ExternalURL + u.Name
  169. }
  170. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  171. func (u *User) GenerateEmailActivateCode(email string) string {
  172. code := tool.CreateTimeLimitCode(
  173. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  174. conf.Auth.ActivateCodeLives, nil)
  175. // Add tail hex username
  176. code += hex.EncodeToString([]byte(u.LowerName))
  177. return code
  178. }
  179. // GenerateActivateCode generates an activate code based on user information.
  180. func (u *User) GenerateActivateCode() string {
  181. return u.GenerateEmailActivateCode(u.Email)
  182. }
  183. // CustomAvatarPath returns user custom avatar file path.
  184. func (u *User) CustomAvatarPath() string {
  185. return filepath.Join(conf.Picture.AvatarUploadPath, com.ToStr(u.ID))
  186. }
  187. // GenerateRandomAvatar generates a random avatar for user.
  188. func (u *User) GenerateRandomAvatar() error {
  189. seed := u.Email
  190. if len(seed) == 0 {
  191. seed = u.Name
  192. }
  193. img, err := avatar.RandomImage([]byte(seed))
  194. if err != nil {
  195. return fmt.Errorf("RandomImage: %v", err)
  196. }
  197. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  198. return fmt.Errorf("MkdirAll: %v", err)
  199. }
  200. fw, err := os.Create(u.CustomAvatarPath())
  201. if err != nil {
  202. return fmt.Errorf("Create: %v", err)
  203. }
  204. defer fw.Close()
  205. if err = png.Encode(fw, img); err != nil {
  206. return fmt.Errorf("Encode: %v", err)
  207. }
  208. log.Info("New random avatar created: %d", u.ID)
  209. return nil
  210. }
  211. // RelAvatarLink returns relative avatar link to the site domain,
  212. // which includes app sub-url as prefix. However, it is possible
  213. // to return full URL if user enables Gravatar-like service.
  214. func (u *User) RelAvatarLink() string {
  215. defaultImgUrl := conf.Server.Subpath + "/img/avatar_default.png"
  216. if u.ID == -1 {
  217. return defaultImgUrl
  218. }
  219. switch {
  220. case u.UseCustomAvatar:
  221. if !com.IsExist(u.CustomAvatarPath()) {
  222. return defaultImgUrl
  223. }
  224. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  225. case conf.Picture.DisableGravatar:
  226. if !com.IsExist(u.CustomAvatarPath()) {
  227. if err := u.GenerateRandomAvatar(); err != nil {
  228. log.Error("GenerateRandomAvatar: %v", err)
  229. }
  230. }
  231. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  232. }
  233. return tool.AvatarLink(u.AvatarEmail)
  234. }
  235. // AvatarLink returns user avatar absolute link.
  236. func (u *User) AvatarLink() string {
  237. link := u.RelAvatarLink()
  238. if link[0] == '/' && link[1] != '/' {
  239. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  240. }
  241. return link
  242. }
  243. // User.GetFollwoers returns range of user's followers.
  244. func (u *User) GetFollowers(page int) ([]*User, error) {
  245. users := make([]*User, 0, ItemsPerPage)
  246. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  247. if conf.UsePostgreSQL {
  248. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  249. } else {
  250. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  251. }
  252. return users, sess.Find(&users)
  253. }
  254. func (u *User) IsFollowing(followID int64) bool {
  255. return IsFollowing(u.ID, followID)
  256. }
  257. // GetFollowing returns range of user's following.
  258. func (u *User) GetFollowing(page int) ([]*User, error) {
  259. users := make([]*User, 0, ItemsPerPage)
  260. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  261. if conf.UsePostgreSQL {
  262. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  263. } else {
  264. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  265. }
  266. return users, sess.Find(&users)
  267. }
  268. // NewGitSig generates and returns the signature of given user.
  269. func (u *User) NewGitSig() *git.Signature {
  270. return &git.Signature{
  271. Name: u.DisplayName(),
  272. Email: u.Email,
  273. When: time.Now(),
  274. }
  275. }
  276. // EncodePassword encodes password to safe format.
  277. func (u *User) EncodePassword() {
  278. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  279. u.Passwd = fmt.Sprintf("%x", newPasswd)
  280. }
  281. // ValidatePassword checks if given password matches the one belongs to the user.
  282. func (u *User) ValidatePassword(passwd string) bool {
  283. if u.OldGinVerifyPassword(passwd) {
  284. return true
  285. }
  286. newUser := &User{Passwd: passwd, Salt: u.Salt}
  287. newUser.EncodePassword()
  288. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  289. }
  290. // UploadAvatar saves custom avatar for user.
  291. // FIXME: split uploads to different subdirs in case we have massive number of users.
  292. func (u *User) UploadAvatar(data []byte) error {
  293. img, _, err := image.Decode(bytes.NewReader(data))
  294. if err != nil {
  295. return fmt.Errorf("decode image: %v", err)
  296. }
  297. _ = os.MkdirAll(conf.Picture.AvatarUploadPath, os.ModePerm)
  298. fw, err := os.Create(u.CustomAvatarPath())
  299. if err != nil {
  300. return fmt.Errorf("create custom avatar directory: %v", err)
  301. }
  302. defer fw.Close()
  303. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  304. if err = png.Encode(fw, m); err != nil {
  305. return fmt.Errorf("encode image: %v", err)
  306. }
  307. return nil
  308. }
  309. // DeleteAvatar deletes the user's custom avatar.
  310. func (u *User) DeleteAvatar() error {
  311. log.Trace("DeleteAvatar [%d]: %s", u.ID, u.CustomAvatarPath())
  312. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  313. return err
  314. }
  315. u.UseCustomAvatar = false
  316. return UpdateUser(u)
  317. }
  318. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  319. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  320. has, err := HasAccess(u.ID, repo, AccessModeAdmin)
  321. if err != nil {
  322. log.Error("HasAccess: %v", err)
  323. }
  324. return has
  325. }
  326. // IsWriterOfRepo returns true if user has write access to given repository.
  327. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  328. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  329. if err != nil {
  330. log.Error("HasAccess: %v", err)
  331. }
  332. return has
  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(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 tool.EllipsisString(u.Name, length)
  401. }
  402. // IsMailable checks if a user is elegible
  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 len(name) == 0 {
  413. return false, nil
  414. }
  415. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  416. }
  417. // GetUserSalt returns a ramdom 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. if !isAddressAllowed(u.Email) {
  499. return ErrBlockedDomain{u.Email}
  500. }
  501. u.LowerName = strings.ToLower(u.Name)
  502. u.AvatarEmail = u.Email
  503. u.Avatar = tool.HashEmail(u.AvatarEmail)
  504. if u.Rands, err = GetUserSalt(); err != nil {
  505. return err
  506. }
  507. if u.Salt, err = GetUserSalt(); err != nil {
  508. return err
  509. }
  510. u.EncodePassword()
  511. u.MaxRepoCreation = -1
  512. sess := x.NewSession()
  513. defer sess.Close()
  514. if err = sess.Begin(); err != nil {
  515. return err
  516. }
  517. if _, err = sess.Insert(u); err != nil {
  518. return err
  519. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  520. return err
  521. }
  522. return sess.Commit()
  523. }
  524. func countUsers(e Engine) int64 {
  525. count, _ := e.Where("type=0").Count(new(User))
  526. return count
  527. }
  528. // CountUsers returns number of users.
  529. func CountUsers() int64 {
  530. return countUsers(x)
  531. }
  532. // Users returns number of users in given page.
  533. func ListUsers(page, pageSize int) ([]*User, error) {
  534. users := make([]*User, 0, pageSize)
  535. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  536. }
  537. // parseUserFromCode returns user by username encoded in code.
  538. // It returns nil if code or username is invalid.
  539. func parseUserFromCode(code string) (user *User) {
  540. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  541. return nil
  542. }
  543. // Use tail hex username to query user
  544. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  545. if b, err := hex.DecodeString(hexStr); err == nil {
  546. if user, err = GetUserByName(string(b)); user != nil {
  547. return user
  548. } else if !IsErrUserNotExist(err) {
  549. log.Error("Failed to get user by name %q: %v", string(b), err)
  550. }
  551. }
  552. return nil
  553. }
  554. // verify active code when active account
  555. func VerifyUserActiveCode(code string) (user *User) {
  556. minutes := conf.Auth.ActivateCodeLives
  557. if user = parseUserFromCode(code); user != nil {
  558. // time limit code
  559. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  560. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  561. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  562. return user
  563. }
  564. }
  565. return nil
  566. }
  567. // verify active code when active account
  568. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  569. minutes := conf.Auth.ActivateCodeLives
  570. if user := parseUserFromCode(code); user != nil {
  571. // time limit code
  572. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  573. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  574. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  575. emailAddress := &EmailAddress{Email: email}
  576. if has, _ := x.Get(emailAddress); has {
  577. return emailAddress
  578. }
  579. }
  580. }
  581. return nil
  582. }
  583. // ChangeUserName changes all corresponding setting from old user name to new one.
  584. func ChangeUserName(u *User, newUserName string) (err error) {
  585. if err = isUsernameAllowed(newUserName); err != nil {
  586. return err
  587. }
  588. isExist, err := IsUserExist(0, newUserName)
  589. if err != nil {
  590. return err
  591. } else if isExist {
  592. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  593. }
  594. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  595. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  596. }
  597. // Delete all local copies of repositories and wikis the user owns.
  598. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  599. repo := bean.(*Repository)
  600. deleteRepoLocalCopy(repo)
  601. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  602. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  603. return nil
  604. }); err != nil {
  605. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  606. }
  607. // Rename or create user base directory
  608. baseDir := UserPath(u.Name)
  609. newBaseDir := UserPath(newUserName)
  610. if com.IsExist(baseDir) {
  611. return os.Rename(baseDir, newBaseDir)
  612. }
  613. return os.MkdirAll(newBaseDir, os.ModePerm)
  614. }
  615. func updateUser(e Engine, u *User) error {
  616. // Organization does not need email
  617. if !u.IsOrganization() {
  618. u.Email = strings.ToLower(u.Email)
  619. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  620. if err != nil {
  621. return err
  622. } else if has {
  623. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  624. }
  625. if len(u.AvatarEmail) == 0 {
  626. u.AvatarEmail = u.Email
  627. }
  628. u.Avatar = tool.HashEmail(u.AvatarEmail)
  629. }
  630. u.LowerName = strings.ToLower(u.Name)
  631. u.Location = tool.TruncateString(u.Location, 255)
  632. u.Website = tool.TruncateString(u.Website, 255)
  633. u.Description = tool.TruncateString(u.Description, 255)
  634. _, err := e.ID(u.ID).AllCols().Update(u)
  635. return err
  636. }
  637. // UpdateUser updates user's information.
  638. func UpdateUser(u *User) error {
  639. return updateUser(x, u)
  640. }
  641. // deleteBeans deletes all given beans, beans should contain delete conditions.
  642. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  643. for i := range beans {
  644. if _, err = e.Delete(beans[i]); err != nil {
  645. return err
  646. }
  647. }
  648. return nil
  649. }
  650. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  651. func deleteUser(e *xorm.Session, u *User) error {
  652. // Note: A user owns any repository or belongs to any organization
  653. // cannot perform delete operation.
  654. // Check ownership of repository.
  655. count, err := getRepositoryCount(e, u)
  656. if err != nil {
  657. return fmt.Errorf("GetRepositoryCount: %v", err)
  658. } else if count > 0 {
  659. return ErrUserOwnRepos{UID: u.ID}
  660. }
  661. // Check membership of organization.
  662. count, err = u.getOrganizationCount(e)
  663. if err != nil {
  664. return fmt.Errorf("GetOrganizationCount: %v", err)
  665. } else if count > 0 {
  666. return ErrUserHasOrgs{UID: u.ID}
  667. }
  668. // ***** START: Watch *****
  669. watches := make([]*Watch, 0, 10)
  670. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  671. return fmt.Errorf("get all watches: %v", err)
  672. }
  673. for i := range watches {
  674. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  675. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  676. }
  677. }
  678. // ***** END: Watch *****
  679. // ***** START: Star *****
  680. stars := make([]*Star, 0, 10)
  681. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  682. return fmt.Errorf("get all stars: %v", err)
  683. }
  684. for i := range stars {
  685. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  686. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  687. }
  688. }
  689. // ***** END: Star *****
  690. // ***** START: Follow *****
  691. followers := make([]*Follow, 0, 10)
  692. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  693. return fmt.Errorf("get all followers: %v", err)
  694. }
  695. for i := range followers {
  696. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  697. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  698. }
  699. }
  700. // ***** END: Follow *****
  701. if err = deleteBeans(e,
  702. &AccessToken{UserID: u.ID},
  703. &Collaboration{UserID: u.ID},
  704. &Access{UserID: u.ID},
  705. &Watch{UserID: u.ID},
  706. &Star{UID: u.ID},
  707. &Follow{FollowID: u.ID},
  708. &Action{UserID: u.ID},
  709. &IssueUser{UID: u.ID},
  710. &EmailAddress{UID: u.ID},
  711. ); err != nil {
  712. return fmt.Errorf("deleteBeans: %v", err)
  713. }
  714. // ***** START: PublicKey *****
  715. keys := make([]*PublicKey, 0, 10)
  716. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  717. return fmt.Errorf("get all public keys: %v", err)
  718. }
  719. keyIDs := make([]int64, len(keys))
  720. for i := range keys {
  721. keyIDs[i] = keys[i].ID
  722. }
  723. if err = deletePublicKeys(e, keyIDs...); err != nil {
  724. return fmt.Errorf("deletePublicKeys: %v", err)
  725. }
  726. // ***** END: PublicKey *****
  727. // Clear assignee.
  728. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  729. return fmt.Errorf("clear assignee: %v", err)
  730. }
  731. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  732. return fmt.Errorf("Delete: %v", err)
  733. }
  734. // FIXME: system notice
  735. // Note: There are something just cannot be roll back,
  736. // so just keep error logs of those operations.
  737. _ = os.RemoveAll(UserPath(u.Name))
  738. _ = os.Remove(u.CustomAvatarPath())
  739. return nil
  740. }
  741. // DeleteUser completely and permanently deletes everything of a user,
  742. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  743. func DeleteUser(u *User) (err error) {
  744. sess := x.NewSession()
  745. defer sess.Close()
  746. if err = sess.Begin(); err != nil {
  747. return err
  748. }
  749. if err = deleteUser(sess, u); err != nil {
  750. // Note: don't wrapper error here.
  751. return err
  752. }
  753. if err = sess.Commit(); err != nil {
  754. return err
  755. }
  756. return RewriteAuthorizedKeys()
  757. }
  758. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  759. func DeleteInactivateUsers() (err error) {
  760. users := make([]*User, 0, 10)
  761. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  762. return fmt.Errorf("get all inactive users: %v", err)
  763. }
  764. // FIXME: should only update authorized_keys file once after all deletions.
  765. for _, u := range users {
  766. if err = DeleteUser(u); err != nil {
  767. // Ignore users that were set inactive by admin.
  768. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  769. continue
  770. }
  771. return err
  772. }
  773. }
  774. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  775. return err
  776. }
  777. // UserPath returns the path absolute path of user repositories.
  778. func UserPath(username string) string {
  779. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  780. }
  781. func GetUserByKeyID(keyID int64) (*User, error) {
  782. user := new(User)
  783. 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)
  784. if err != nil {
  785. return nil, err
  786. } else if !has {
  787. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  788. }
  789. return user, nil
  790. }
  791. func getUserByID(e Engine, id int64) (*User, error) {
  792. u := new(User)
  793. has, err := e.ID(id).Get(u)
  794. if err != nil {
  795. return nil, err
  796. } else if !has {
  797. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  798. }
  799. return u, nil
  800. }
  801. // GetUserByID returns the user object by given ID if exists.
  802. // Deprecated: Use Users.GetByID instead.
  803. func GetUserByID(id int64) (*User, error) {
  804. return getUserByID(x, id)
  805. }
  806. // GetAssigneeByID returns the user with write access of repository by given ID.
  807. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  808. has, err := HasAccess(userID, repo, AccessModeRead)
  809. if err != nil {
  810. return nil, err
  811. } else if !has {
  812. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  813. }
  814. return GetUserByID(userID)
  815. }
  816. // GetUserByName returns a user by given name.
  817. // Deprecated: Use Users.GetByUsername instead.
  818. func GetUserByName(name string) (*User, error) {
  819. if len(name) == 0 {
  820. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  821. }
  822. u := &User{LowerName: strings.ToLower(name)}
  823. has, err := x.Get(u)
  824. if err != nil {
  825. return nil, err
  826. } else if !has {
  827. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  828. }
  829. return u, nil
  830. }
  831. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  832. func GetUserEmailsByNames(names []string) []string {
  833. mails := make([]string, 0, len(names))
  834. for _, name := range names {
  835. u, err := GetUserByName(name)
  836. if err != nil {
  837. continue
  838. }
  839. if u.IsMailable() {
  840. mails = append(mails, u.Email)
  841. }
  842. }
  843. return mails
  844. }
  845. // GetUserIDsByNames returns a slice of ids corresponds to names.
  846. func GetUserIDsByNames(names []string) []int64 {
  847. ids := make([]int64, 0, len(names))
  848. for _, name := range names {
  849. u, err := GetUserByName(name)
  850. if err != nil {
  851. continue
  852. }
  853. ids = append(ids, u.ID)
  854. }
  855. return ids
  856. }
  857. // UserCommit represents a commit with validation of user.
  858. type UserCommit struct {
  859. User *User
  860. *git.Commit
  861. }
  862. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  863. func ValidateCommitWithEmail(c *git.Commit) *User {
  864. u, err := GetUserByEmail(c.Author.Email)
  865. if err != nil {
  866. return nil
  867. }
  868. return u
  869. }
  870. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  871. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  872. emails := make(map[string]*User)
  873. newCommits := make([]*UserCommit, len(oldCommits))
  874. for i := range oldCommits {
  875. var u *User
  876. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  877. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  878. emails[oldCommits[i].Author.Email] = u
  879. } else {
  880. u = v
  881. }
  882. newCommits[i] = &UserCommit{
  883. User: u,
  884. Commit: oldCommits[i],
  885. }
  886. }
  887. return newCommits
  888. }
  889. // GetUserByEmail returns the user object by given e-mail if exists.
  890. // Deprecated: Use Users.GetByEmail instead.
  891. func GetUserByEmail(email string) (*User, error) {
  892. if len(email) == 0 {
  893. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  894. }
  895. email = strings.ToLower(email)
  896. // First try to find the user by primary email
  897. user := &User{Email: email}
  898. has, err := x.Get(user)
  899. if err != nil {
  900. return nil, err
  901. }
  902. if has {
  903. return user, nil
  904. }
  905. // Otherwise, check in alternative list for activated email addresses
  906. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  907. has, err = x.Get(emailAddress)
  908. if err != nil {
  909. return nil, err
  910. }
  911. if has {
  912. return GetUserByID(emailAddress.UID)
  913. }
  914. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  915. }
  916. type SearchUserOptions struct {
  917. Keyword string
  918. Type UserType
  919. OrderBy string
  920. Page int
  921. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  922. }
  923. // SearchUserByName takes keyword and part of user name to search,
  924. // it returns results in given range and number of total results.
  925. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  926. if len(opts.Keyword) == 0 {
  927. return users, 0, nil
  928. }
  929. opts.Keyword = strings.ToLower(opts.Keyword)
  930. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  931. opts.PageSize = conf.UI.ExplorePagingNum
  932. }
  933. if opts.Page <= 0 {
  934. opts.Page = 1
  935. }
  936. searchQuery := "%" + opts.Keyword + "%"
  937. users = make([]*User, 0, opts.PageSize)
  938. // Append conditions
  939. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  940. Or("LOWER(full_name) LIKE ?", searchQuery).
  941. And("type = ?", opts.Type)
  942. countSess := *sess
  943. count, err := countSess.Count(new(User))
  944. if err != nil {
  945. return nil, 0, fmt.Errorf("Count: %v", err)
  946. }
  947. if len(opts.OrderBy) > 0 {
  948. sess.OrderBy(opts.OrderBy)
  949. }
  950. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  951. }
  952. // ___________ .__ .__
  953. // \_ _____/___ | | | | ______ _ __
  954. // | __)/ _ \| | | | / _ \ \/ \/ /
  955. // | \( <_> ) |_| |_( <_> ) /
  956. // \___ / \____/|____/____/\____/ \/\_/
  957. // \/
  958. // Follow represents relations of user and his/her followers.
  959. type Follow struct {
  960. ID int64
  961. UserID int64 `xorm:"UNIQUE(follow)"`
  962. FollowID int64 `xorm:"UNIQUE(follow)"`
  963. }
  964. func IsFollowing(userID, followID int64) bool {
  965. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  966. return has
  967. }
  968. // FollowUser marks someone be another's follower.
  969. func FollowUser(userID, followID int64) (err error) {
  970. if userID == followID || IsFollowing(userID, followID) {
  971. return nil
  972. }
  973. sess := x.NewSession()
  974. defer sess.Close()
  975. if err = sess.Begin(); err != nil {
  976. return err
  977. }
  978. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  979. return err
  980. }
  981. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  982. return err
  983. }
  984. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  985. return err
  986. }
  987. return sess.Commit()
  988. }
  989. // UnfollowUser unmarks someone be another's follower.
  990. func UnfollowUser(userID, followID int64) (err error) {
  991. if userID == followID || !IsFollowing(userID, followID) {
  992. return nil
  993. }
  994. sess := x.NewSession()
  995. defer sess.Close()
  996. if err = sess.Begin(); err != nil {
  997. return err
  998. }
  999. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1000. return err
  1001. }
  1002. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1003. return err
  1004. }
  1005. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1006. return err
  1007. }
  1008. return sess.Commit()
  1009. }