user.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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/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 LoginPlain.
  125. func (u *User) IsLocal() bool {
  126. return u.LoginType <= LoginPlain
  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, AccessModeAdmin)
  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, AccessModeWrite)
  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 TwoFactors.IsUserEnabled(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 ListUsers(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 !IsErrUserNotExist(err) {
  554. log.Error("Failed to get user by name %q: %v", string(b), 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{UserID: 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. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  797. type ErrUserNotExist struct {
  798. args map[string]interface{}
  799. }
  800. func IsErrUserNotExist(err error) bool {
  801. _, ok := err.(ErrUserNotExist)
  802. return ok
  803. }
  804. func (err ErrUserNotExist) Error() string {
  805. return fmt.Sprintf("user does not exist: %v", err.args)
  806. }
  807. func (ErrUserNotExist) NotFound() bool {
  808. return true
  809. }
  810. func getUserByID(e Engine, id int64) (*User, error) {
  811. u := new(User)
  812. has, err := e.ID(id).Get(u)
  813. if err != nil {
  814. return nil, err
  815. } else if !has {
  816. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  817. }
  818. return u, nil
  819. }
  820. // GetUserByID returns the user object by given ID if exists.
  821. // Deprecated: Use Users.GetByID instead.
  822. func GetUserByID(id int64) (*User, error) {
  823. return getUserByID(x, id)
  824. }
  825. // GetAssigneeByID returns the user with write access of repository by given ID.
  826. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  827. has, err := HasAccess(userID, repo, AccessModeRead)
  828. if err != nil {
  829. return nil, err
  830. } else if !has {
  831. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  832. }
  833. return GetUserByID(userID)
  834. }
  835. // GetUserByName returns a user by given name.
  836. // Deprecated: Use Users.GetByUsername instead.
  837. func GetUserByName(name string) (*User, error) {
  838. if len(name) == 0 {
  839. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  840. }
  841. u := &User{LowerName: strings.ToLower(name)}
  842. has, err := x.Get(u)
  843. if err != nil {
  844. return nil, err
  845. } else if !has {
  846. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  847. }
  848. return u, nil
  849. }
  850. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  851. func GetUserEmailsByNames(names []string) []string {
  852. mails := make([]string, 0, len(names))
  853. for _, name := range names {
  854. u, err := GetUserByName(name)
  855. if err != nil {
  856. continue
  857. }
  858. if u.IsMailable() {
  859. mails = append(mails, u.Email)
  860. }
  861. }
  862. return mails
  863. }
  864. // GetUserIDsByNames returns a slice of ids corresponds to names.
  865. func GetUserIDsByNames(names []string) []int64 {
  866. ids := make([]int64, 0, len(names))
  867. for _, name := range names {
  868. u, err := GetUserByName(name)
  869. if err != nil {
  870. continue
  871. }
  872. ids = append(ids, u.ID)
  873. }
  874. return ids
  875. }
  876. // UserCommit represents a commit with validation of user.
  877. type UserCommit struct {
  878. User *User
  879. *git.Commit
  880. }
  881. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  882. func ValidateCommitWithEmail(c *git.Commit) *User {
  883. u, err := GetUserByEmail(c.Author.Email)
  884. if err != nil {
  885. return nil
  886. }
  887. return u
  888. }
  889. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  890. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  891. emails := make(map[string]*User)
  892. newCommits := make([]*UserCommit, len(oldCommits))
  893. for i := range oldCommits {
  894. var u *User
  895. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  896. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  897. emails[oldCommits[i].Author.Email] = u
  898. } else {
  899. u = v
  900. }
  901. newCommits[i] = &UserCommit{
  902. User: u,
  903. Commit: oldCommits[i],
  904. }
  905. }
  906. return newCommits
  907. }
  908. // GetUserByEmail returns the user object by given e-mail if exists.
  909. func GetUserByEmail(email string) (*User, error) {
  910. if len(email) == 0 {
  911. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  912. }
  913. email = strings.ToLower(email)
  914. // First try to find the user by primary email
  915. user := &User{Email: email}
  916. has, err := x.Get(user)
  917. if err != nil {
  918. return nil, err
  919. }
  920. if has {
  921. return user, nil
  922. }
  923. // Otherwise, check in alternative list for activated email addresses
  924. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  925. has, err = x.Get(emailAddress)
  926. if err != nil {
  927. return nil, err
  928. }
  929. if has {
  930. return GetUserByID(emailAddress.UID)
  931. }
  932. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  933. }
  934. type SearchUserOptions struct {
  935. Keyword string
  936. Type UserType
  937. OrderBy string
  938. Page int
  939. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  940. }
  941. // SearchUserByName takes keyword and part of user name to search,
  942. // it returns results in given range and number of total results.
  943. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  944. if len(opts.Keyword) == 0 {
  945. return users, 0, nil
  946. }
  947. opts.Keyword = strings.ToLower(opts.Keyword)
  948. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  949. opts.PageSize = conf.UI.ExplorePagingNum
  950. }
  951. if opts.Page <= 0 {
  952. opts.Page = 1
  953. }
  954. searchQuery := "%" + opts.Keyword + "%"
  955. users = make([]*User, 0, opts.PageSize)
  956. // Append conditions
  957. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  958. Or("LOWER(full_name) LIKE ?", searchQuery).
  959. And("type = ?", opts.Type)
  960. countSess := *sess
  961. count, err := countSess.Count(new(User))
  962. if err != nil {
  963. return nil, 0, fmt.Errorf("Count: %v", err)
  964. }
  965. if len(opts.OrderBy) > 0 {
  966. sess.OrderBy(opts.OrderBy)
  967. }
  968. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  969. }
  970. // ___________ .__ .__
  971. // \_ _____/___ | | | | ______ _ __
  972. // | __)/ _ \| | | | / _ \ \/ \/ /
  973. // | \( <_> ) |_| |_( <_> ) /
  974. // \___ / \____/|____/____/\____/ \/\_/
  975. // \/
  976. // Follow represents relations of user and his/her followers.
  977. type Follow struct {
  978. ID int64
  979. UserID int64 `xorm:"UNIQUE(follow)"`
  980. FollowID int64 `xorm:"UNIQUE(follow)"`
  981. }
  982. func IsFollowing(userID, followID int64) bool {
  983. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  984. return has
  985. }
  986. // FollowUser marks someone be another's follower.
  987. func FollowUser(userID, followID int64) (err error) {
  988. if userID == followID || IsFollowing(userID, followID) {
  989. return nil
  990. }
  991. sess := x.NewSession()
  992. defer sess.Close()
  993. if err = sess.Begin(); err != nil {
  994. return err
  995. }
  996. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  997. return err
  998. }
  999. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1000. return err
  1001. }
  1002. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1003. return err
  1004. }
  1005. return sess.Commit()
  1006. }
  1007. // UnfollowUser unmarks someone be another's follower.
  1008. func UnfollowUser(userID, followID int64) (err error) {
  1009. if userID == followID || !IsFollowing(userID, followID) {
  1010. return nil
  1011. }
  1012. sess := x.NewSession()
  1013. defer sess.Close()
  1014. if err = sess.Begin(); err != nil {
  1015. return err
  1016. }
  1017. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1018. return err
  1019. }
  1020. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1021. return err
  1022. }
  1023. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1024. return err
  1025. }
  1026. return sess.Commit()
  1027. }