user.go 32 KB

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