user.go 32 KB

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