user.go 31 KB

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