user.go 33 KB

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