2
0

user.go 32 KB

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