user.go 32 KB

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