user.go 31 KB

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