user.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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. // isUsableName checks if name is reserved or pattern of name is not allowed
  463. // based on given reserved names and patterns.
  464. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  465. func isUsableName(names, patterns []string, name string) error {
  466. name = strings.TrimSpace(strings.ToLower(name))
  467. if utf8.RuneCountInString(name) == 0 {
  468. return errors.EmptyName{}
  469. }
  470. for i := range names {
  471. if name == names[i] {
  472. return ErrNameReserved{name}
  473. }
  474. }
  475. for _, pat := range patterns {
  476. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  477. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  478. return ErrNamePatternNotAllowed{pat}
  479. }
  480. }
  481. return nil
  482. }
  483. func IsUsableUsername(name string) error {
  484. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  485. }
  486. // CreateUser creates record of a new user.
  487. func CreateUser(u *User) (err error) {
  488. if err = IsUsableUsername(u.Name); err != nil {
  489. return err
  490. }
  491. isExist, err := IsUserExist(0, u.Name)
  492. if err != nil {
  493. return err
  494. } else if isExist {
  495. return ErrUserAlreadyExist{u.Name}
  496. }
  497. u.Email = strings.ToLower(u.Email)
  498. isExist, err = IsEmailUsed(u.Email)
  499. if err != nil {
  500. return err
  501. } else if isExist {
  502. return ErrEmailAlreadyUsed{u.Email}
  503. }
  504. if IsBlockedDomain(u.Email) {
  505. return ErrBlockedDomain{u.Email}
  506. }
  507. u.LowerName = strings.ToLower(u.Name)
  508. u.AvatarEmail = u.Email
  509. u.Avatar = tool.HashEmail(u.AvatarEmail)
  510. if u.Rands, err = GetUserSalt(); err != nil {
  511. return err
  512. }
  513. if u.Salt, err = GetUserSalt(); err != nil {
  514. return err
  515. }
  516. u.EncodePasswd()
  517. u.MaxRepoCreation = -1
  518. sess := x.NewSession()
  519. defer sess.Close()
  520. if err = sess.Begin(); err != nil {
  521. return err
  522. }
  523. if _, err = sess.Insert(u); err != nil {
  524. return err
  525. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  526. return err
  527. }
  528. return sess.Commit()
  529. }
  530. func countUsers(e Engine) int64 {
  531. count, _ := e.Where("type=0").Count(new(User))
  532. return count
  533. }
  534. // CountUsers returns number of users.
  535. func CountUsers() int64 {
  536. return countUsers(x)
  537. }
  538. // Users returns number of users in given page.
  539. func ListUsers(page, pageSize int) ([]*User, error) {
  540. users := make([]*User, 0, pageSize)
  541. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  542. }
  543. // parseUserFromCode returns user by username encoded in code.
  544. // It returns nil if code or username is invalid.
  545. func parseUserFromCode(code string) (user *User) {
  546. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  547. return nil
  548. }
  549. // Use tail hex username to query user
  550. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  551. if b, err := hex.DecodeString(hexStr); err == nil {
  552. if user, err = GetUserByName(string(b)); user != nil {
  553. return user
  554. } else if !IsErrUserNotExist(err) {
  555. log.Error("Failed to get user by name %q: %v", string(b), err)
  556. }
  557. }
  558. return nil
  559. }
  560. // verify active code when active account
  561. func VerifyUserActiveCode(code string) (user *User) {
  562. minutes := conf.Auth.ActivateCodeLives
  563. if user = parseUserFromCode(code); user != nil {
  564. // time limit code
  565. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  566. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  567. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  568. return user
  569. }
  570. }
  571. return nil
  572. }
  573. // verify active code when active account
  574. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  575. minutes := conf.Auth.ActivateCodeLives
  576. if user := parseUserFromCode(code); user != nil {
  577. // time limit code
  578. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  579. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  580. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  581. emailAddress := &EmailAddress{Email: email}
  582. if has, _ := x.Get(emailAddress); has {
  583. return emailAddress
  584. }
  585. }
  586. }
  587. return nil
  588. }
  589. // ChangeUserName changes all corresponding setting from old user name to new one.
  590. func ChangeUserName(u *User, newUserName string) (err error) {
  591. if err = IsUsableUsername(newUserName); err != nil {
  592. return err
  593. }
  594. isExist, err := IsUserExist(0, newUserName)
  595. if err != nil {
  596. return err
  597. } else if isExist {
  598. return ErrUserAlreadyExist{newUserName}
  599. }
  600. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  601. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  602. }
  603. // Delete all local copies of repositories and wikis the user owns.
  604. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  605. repo := bean.(*Repository)
  606. deleteRepoLocalCopy(repo)
  607. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  608. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  609. return nil
  610. }); err != nil {
  611. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  612. }
  613. // Rename or create user base directory
  614. baseDir := UserPath(u.Name)
  615. newBaseDir := UserPath(newUserName)
  616. if com.IsExist(baseDir) {
  617. return os.Rename(baseDir, newBaseDir)
  618. }
  619. return os.MkdirAll(newBaseDir, os.ModePerm)
  620. }
  621. func updateUser(e Engine, u *User) error {
  622. // Organization does not need email
  623. if !u.IsOrganization() {
  624. u.Email = strings.ToLower(u.Email)
  625. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  626. if err != nil {
  627. return err
  628. } else if has {
  629. return ErrEmailAlreadyUsed{u.Email}
  630. }
  631. if len(u.AvatarEmail) == 0 {
  632. u.AvatarEmail = u.Email
  633. }
  634. u.Avatar = tool.HashEmail(u.AvatarEmail)
  635. }
  636. u.LowerName = strings.ToLower(u.Name)
  637. u.Location = tool.TruncateString(u.Location, 255)
  638. u.Website = tool.TruncateString(u.Website, 255)
  639. u.Description = tool.TruncateString(u.Description, 255)
  640. _, err := e.ID(u.ID).AllCols().Update(u)
  641. return err
  642. }
  643. // UpdateUser updates user's information.
  644. func UpdateUser(u *User) error {
  645. return updateUser(x, u)
  646. }
  647. // deleteBeans deletes all given beans, beans should contain delete conditions.
  648. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  649. for i := range beans {
  650. if _, err = e.Delete(beans[i]); err != nil {
  651. return err
  652. }
  653. }
  654. return nil
  655. }
  656. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  657. func deleteUser(e *xorm.Session, u *User) error {
  658. // Note: A user owns any repository or belongs to any organization
  659. // cannot perform delete operation.
  660. // Check ownership of repository.
  661. count, err := getRepositoryCount(e, u)
  662. if err != nil {
  663. return fmt.Errorf("GetRepositoryCount: %v", err)
  664. } else if count > 0 {
  665. return ErrUserOwnRepos{UID: u.ID}
  666. }
  667. // Check membership of organization.
  668. count, err = u.getOrganizationCount(e)
  669. if err != nil {
  670. return fmt.Errorf("GetOrganizationCount: %v", err)
  671. } else if count > 0 {
  672. return ErrUserHasOrgs{UID: u.ID}
  673. }
  674. // ***** START: Watch *****
  675. watches := make([]*Watch, 0, 10)
  676. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  677. return fmt.Errorf("get all watches: %v", err)
  678. }
  679. for i := range watches {
  680. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  681. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  682. }
  683. }
  684. // ***** END: Watch *****
  685. // ***** START: Star *****
  686. stars := make([]*Star, 0, 10)
  687. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  688. return fmt.Errorf("get all stars: %v", err)
  689. }
  690. for i := range stars {
  691. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  692. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  693. }
  694. }
  695. // ***** END: Star *****
  696. // ***** START: Follow *****
  697. followers := make([]*Follow, 0, 10)
  698. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  699. return fmt.Errorf("get all followers: %v", err)
  700. }
  701. for i := range followers {
  702. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  703. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  704. }
  705. }
  706. // ***** END: Follow *****
  707. if err = deleteBeans(e,
  708. &AccessToken{UserID: u.ID},
  709. &Collaboration{UserID: u.ID},
  710. &Access{UserID: u.ID},
  711. &Watch{UserID: u.ID},
  712. &Star{UID: u.ID},
  713. &Follow{FollowID: u.ID},
  714. &Action{UserID: u.ID},
  715. &IssueUser{UID: u.ID},
  716. &EmailAddress{UID: u.ID},
  717. ); err != nil {
  718. return fmt.Errorf("deleteBeans: %v", err)
  719. }
  720. // ***** START: PublicKey *****
  721. keys := make([]*PublicKey, 0, 10)
  722. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  723. return fmt.Errorf("get all public keys: %v", err)
  724. }
  725. keyIDs := make([]int64, len(keys))
  726. for i := range keys {
  727. keyIDs[i] = keys[i].ID
  728. }
  729. if err = deletePublicKeys(e, keyIDs...); err != nil {
  730. return fmt.Errorf("deletePublicKeys: %v", err)
  731. }
  732. // ***** END: PublicKey *****
  733. // Clear assignee.
  734. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  735. return fmt.Errorf("clear assignee: %v", err)
  736. }
  737. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  738. return fmt.Errorf("Delete: %v", err)
  739. }
  740. // FIXME: system notice
  741. // Note: There are something just cannot be roll back,
  742. // so just keep error logs of those operations.
  743. _ = os.RemoveAll(UserPath(u.Name))
  744. _ = os.Remove(u.CustomAvatarPath())
  745. return nil
  746. }
  747. // DeleteUser completely and permanently deletes everything of a user,
  748. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  749. func DeleteUser(u *User) (err error) {
  750. sess := x.NewSession()
  751. defer sess.Close()
  752. if err = sess.Begin(); err != nil {
  753. return err
  754. }
  755. if err = deleteUser(sess, u); err != nil {
  756. // Note: don't wrapper error here.
  757. return err
  758. }
  759. if err = sess.Commit(); err != nil {
  760. return err
  761. }
  762. return RewriteAuthorizedKeys()
  763. }
  764. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  765. func DeleteInactivateUsers() (err error) {
  766. users := make([]*User, 0, 10)
  767. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  768. return fmt.Errorf("get all inactive users: %v", err)
  769. }
  770. // FIXME: should only update authorized_keys file once after all deletions.
  771. for _, u := range users {
  772. if err = DeleteUser(u); err != nil {
  773. // Ignore users that were set inactive by admin.
  774. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  775. continue
  776. }
  777. return err
  778. }
  779. }
  780. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  781. return err
  782. }
  783. // UserPath returns the path absolute path of user repositories.
  784. func UserPath(userName string) string {
  785. return filepath.Join(conf.Repository.Root, strings.ToLower(userName))
  786. }
  787. func GetUserByKeyID(keyID int64) (*User, error) {
  788. user := new(User)
  789. has, err := x.SQL("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  790. if err != nil {
  791. return nil, err
  792. } else if !has {
  793. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  794. }
  795. return user, nil
  796. }
  797. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  798. type ErrUserNotExist struct {
  799. args map[string]interface{}
  800. }
  801. func IsErrUserNotExist(err error) bool {
  802. _, ok := err.(ErrUserNotExist)
  803. return ok
  804. }
  805. func (err ErrUserNotExist) Error() string {
  806. return fmt.Sprintf("user does not exist: %v", err.args)
  807. }
  808. func (ErrUserNotExist) NotFound() bool {
  809. return true
  810. }
  811. func getUserByID(e Engine, id int64) (*User, error) {
  812. u := new(User)
  813. has, err := e.ID(id).Get(u)
  814. if err != nil {
  815. return nil, err
  816. } else if !has {
  817. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  818. }
  819. return u, nil
  820. }
  821. // GetUserByID returns the user object by given ID if exists.
  822. // Deprecated: Use Users.GetByID instead.
  823. func GetUserByID(id int64) (*User, error) {
  824. return getUserByID(x, id)
  825. }
  826. // GetAssigneeByID returns the user with write access of repository by given ID.
  827. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  828. has, err := HasAccess(userID, repo, AccessModeRead)
  829. if err != nil {
  830. return nil, err
  831. } else if !has {
  832. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  833. }
  834. return GetUserByID(userID)
  835. }
  836. // GetUserByName returns a user by given name.
  837. // Deprecated: Use Users.GetByUsername instead.
  838. func GetUserByName(name string) (*User, error) {
  839. if len(name) == 0 {
  840. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  841. }
  842. u := &User{LowerName: strings.ToLower(name)}
  843. has, err := x.Get(u)
  844. if err != nil {
  845. return nil, err
  846. } else if !has {
  847. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  848. }
  849. return u, nil
  850. }
  851. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  852. func GetUserEmailsByNames(names []string) []string {
  853. mails := make([]string, 0, len(names))
  854. for _, name := range names {
  855. u, err := GetUserByName(name)
  856. if err != nil {
  857. continue
  858. }
  859. if u.IsMailable() {
  860. mails = append(mails, u.Email)
  861. }
  862. }
  863. return mails
  864. }
  865. // GetUserIDsByNames returns a slice of ids corresponds to names.
  866. func GetUserIDsByNames(names []string) []int64 {
  867. ids := make([]int64, 0, len(names))
  868. for _, name := range names {
  869. u, err := GetUserByName(name)
  870. if err != nil {
  871. continue
  872. }
  873. ids = append(ids, u.ID)
  874. }
  875. return ids
  876. }
  877. // UserCommit represents a commit with validation of user.
  878. type UserCommit struct {
  879. User *User
  880. *git.Commit
  881. }
  882. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  883. func ValidateCommitWithEmail(c *git.Commit) *User {
  884. u, err := GetUserByEmail(c.Author.Email)
  885. if err != nil {
  886. return nil
  887. }
  888. return u
  889. }
  890. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  891. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  892. emails := make(map[string]*User)
  893. newCommits := make([]*UserCommit, len(oldCommits))
  894. for i := range oldCommits {
  895. var u *User
  896. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  897. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  898. emails[oldCommits[i].Author.Email] = u
  899. } else {
  900. u = v
  901. }
  902. newCommits[i] = &UserCommit{
  903. User: u,
  904. Commit: oldCommits[i],
  905. }
  906. }
  907. return newCommits
  908. }
  909. // GetUserByEmail returns the user object by given e-mail if exists.
  910. func GetUserByEmail(email string) (*User, error) {
  911. if len(email) == 0 {
  912. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  913. }
  914. email = strings.ToLower(email)
  915. // First try to find the user by primary email
  916. user := &User{Email: email}
  917. has, err := x.Get(user)
  918. if err != nil {
  919. return nil, err
  920. }
  921. if has {
  922. return user, nil
  923. }
  924. // Otherwise, check in alternative list for activated email addresses
  925. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  926. has, err = x.Get(emailAddress)
  927. if err != nil {
  928. return nil, err
  929. }
  930. if has {
  931. return GetUserByID(emailAddress.UID)
  932. }
  933. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  934. }
  935. type SearchUserOptions struct {
  936. Keyword string
  937. Type UserType
  938. OrderBy string
  939. Page int
  940. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  941. }
  942. // SearchUserByName takes keyword and part of user name to search,
  943. // it returns results in given range and number of total results.
  944. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  945. if len(opts.Keyword) == 0 {
  946. return users, 0, nil
  947. }
  948. opts.Keyword = strings.ToLower(opts.Keyword)
  949. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  950. opts.PageSize = conf.UI.ExplorePagingNum
  951. }
  952. if opts.Page <= 0 {
  953. opts.Page = 1
  954. }
  955. searchQuery := "%" + opts.Keyword + "%"
  956. users = make([]*User, 0, opts.PageSize)
  957. // Append conditions
  958. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  959. Or("LOWER(full_name) LIKE ?", searchQuery).
  960. And("type = ?", opts.Type)
  961. countSess := *sess
  962. count, err := countSess.Count(new(User))
  963. if err != nil {
  964. return nil, 0, fmt.Errorf("Count: %v", err)
  965. }
  966. if len(opts.OrderBy) > 0 {
  967. sess.OrderBy(opts.OrderBy)
  968. }
  969. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  970. }
  971. // ___________ .__ .__
  972. // \_ _____/___ | | | | ______ _ __
  973. // | __)/ _ \| | | | / _ \ \/ \/ /
  974. // | \( <_> ) |_| |_( <_> ) /
  975. // \___ / \____/|____/____/\____/ \/\_/
  976. // \/
  977. // Follow represents relations of user and his/her followers.
  978. type Follow struct {
  979. ID int64
  980. UserID int64 `xorm:"UNIQUE(follow)"`
  981. FollowID int64 `xorm:"UNIQUE(follow)"`
  982. }
  983. func IsFollowing(userID, followID int64) bool {
  984. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  985. return has
  986. }
  987. // FollowUser marks someone be another's follower.
  988. func FollowUser(userID, followID int64) (err error) {
  989. if userID == followID || IsFollowing(userID, followID) {
  990. return nil
  991. }
  992. sess := x.NewSession()
  993. defer sess.Close()
  994. if err = sess.Begin(); err != nil {
  995. return err
  996. }
  997. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  998. return err
  999. }
  1000. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1001. return err
  1002. }
  1003. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1004. return err
  1005. }
  1006. return sess.Commit()
  1007. }
  1008. // UnfollowUser unmarks someone be another's follower.
  1009. func UnfollowUser(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.Delete(&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. }