user.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. "context"
  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/errutil"
  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 seed == "" {
  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.GetFollowers 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. return Perms.Authorize(context.TODO(), u.ID, repo.ID, AccessModeAdmin,
  319. AccessModeOptions{
  320. OwnerID: repo.OwnerID,
  321. Private: repo.IsPrivate,
  322. },
  323. )
  324. }
  325. // IsWriterOfRepo returns true if user has write access to given repository.
  326. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  327. return Perms.Authorize(context.TODO(), u.ID, repo.ID, AccessModeWrite,
  328. AccessModeOptions{
  329. OwnerID: repo.OwnerID,
  330. Private: repo.IsPrivate,
  331. },
  332. )
  333. }
  334. // IsOrganization returns true if user is actually a organization.
  335. func (u *User) IsOrganization() bool {
  336. return u.Type == UserOrganization
  337. }
  338. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  339. func (u *User) IsUserOrgOwner(orgId int64) bool {
  340. return IsOrganizationOwner(orgId, u.ID)
  341. }
  342. // IsPublicMember returns true if user public his/her membership in give organization.
  343. func (u *User) IsPublicMember(orgId int64) bool {
  344. return IsPublicMembership(orgId, u.ID)
  345. }
  346. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  347. func (u *User) IsEnabledTwoFactor() bool {
  348. return TwoFactors.IsUserEnabled(u.ID)
  349. }
  350. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  351. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  352. }
  353. // GetOrganizationCount returns count of membership of organization of user.
  354. func (u *User) GetOrganizationCount() (int64, error) {
  355. return u.getOrganizationCount(x)
  356. }
  357. // GetRepositories returns repositories that user owns, including private repositories.
  358. func (u *User) GetRepositories(page, pageSize int) (err error) {
  359. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  360. UserID: u.ID,
  361. Private: true,
  362. Page: page,
  363. PageSize: pageSize,
  364. })
  365. return err
  366. }
  367. // GetRepositories returns mirror repositories that user owns, including private repositories.
  368. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  369. return GetUserMirrorRepositories(u.ID)
  370. }
  371. // GetOwnedOrganizations returns all organizations that user owns.
  372. func (u *User) GetOwnedOrganizations() (err error) {
  373. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  374. return err
  375. }
  376. // GetOrganizations returns all organizations that user belongs to.
  377. func (u *User) GetOrganizations(showPrivate bool) error {
  378. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  379. if err != nil {
  380. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  381. }
  382. if len(orgIDs) == 0 {
  383. return nil
  384. }
  385. u.Orgs = make([]*User, 0, len(orgIDs))
  386. if err = x.Where("type = ?", UserOrganization).In("id", orgIDs).Find(&u.Orgs); err != nil {
  387. return err
  388. }
  389. return nil
  390. }
  391. // DisplayName returns full name if it's not empty,
  392. // returns username otherwise.
  393. func (u *User) DisplayName() string {
  394. if len(u.FullName) > 0 {
  395. return u.FullName
  396. }
  397. return u.Name
  398. }
  399. func (u *User) ShortName(length int) string {
  400. return tool.EllipsisString(u.Name, length)
  401. }
  402. // IsMailable checks if a user is eligible
  403. // to receive emails.
  404. func (u *User) IsMailable() bool {
  405. return u.IsActive
  406. }
  407. // IsUserExist checks if given user name exist,
  408. // the user name should be noncased unique.
  409. // If uid is presented, then check will rule out that one,
  410. // it is used when update a user name in settings page.
  411. func IsUserExist(uid int64, name string) (bool, error) {
  412. if name == "" {
  413. return false, nil
  414. }
  415. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  416. }
  417. // GetUserSalt returns a random user salt token.
  418. func GetUserSalt() (string, error) {
  419. return strutil.RandomChars(10)
  420. }
  421. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  422. func NewGhostUser() *User {
  423. return &User{
  424. ID: -1,
  425. Name: "Ghost",
  426. LowerName: "ghost",
  427. }
  428. }
  429. var (
  430. 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", ".", ".."}
  431. reservedUserPatterns = []string{"*.keys"}
  432. )
  433. type ErrNameNotAllowed struct {
  434. args errutil.Args
  435. }
  436. func IsErrNameNotAllowed(err error) bool {
  437. _, ok := err.(ErrNameNotAllowed)
  438. return ok
  439. }
  440. func (err ErrNameNotAllowed) Value() string {
  441. val, ok := err.args["name"].(string)
  442. if ok {
  443. return val
  444. }
  445. val, ok = err.args["pattern"].(string)
  446. if ok {
  447. return val
  448. }
  449. return "<value not found>"
  450. }
  451. func (err ErrNameNotAllowed) Error() string {
  452. return fmt.Sprintf("name is not allowed: %v", err.args)
  453. }
  454. // isNameAllowed checks if name is reserved or pattern of name is not allowed
  455. // based on given reserved names and patterns.
  456. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  457. func isNameAllowed(names, patterns []string, name string) error {
  458. name = strings.TrimSpace(strings.ToLower(name))
  459. if utf8.RuneCountInString(name) == 0 {
  460. return ErrNameNotAllowed{args: errutil.Args{"reason": "empty name"}}
  461. }
  462. for i := range names {
  463. if name == names[i] {
  464. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "name": name}}
  465. }
  466. }
  467. for _, pat := range patterns {
  468. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  469. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  470. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": pat}}
  471. }
  472. }
  473. return nil
  474. }
  475. // isUsernameAllowed return an error if given name is a reserved name or pattern for users.
  476. func isUsernameAllowed(name string) error {
  477. return isNameAllowed(reservedUsernames, reservedUserPatterns, name)
  478. }
  479. // CreateUser creates record of a new user.
  480. // Deprecated: Use Users.Create instead.
  481. func CreateUser(u *User) (err error) {
  482. if err = isUsernameAllowed(u.Name); err != nil {
  483. return err
  484. }
  485. isExist, err := IsUserExist(0, u.Name)
  486. if err != nil {
  487. return err
  488. } else if isExist {
  489. return ErrUserAlreadyExist{args: errutil.Args{"name": u.Name}}
  490. }
  491. u.Email = strings.ToLower(u.Email)
  492. isExist, err = IsEmailUsed(u.Email)
  493. if err != nil {
  494. return err
  495. } else if isExist {
  496. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  497. }
  498. u.LowerName = strings.ToLower(u.Name)
  499. u.AvatarEmail = u.Email
  500. u.Avatar = tool.HashEmail(u.AvatarEmail)
  501. if u.Rands, err = GetUserSalt(); err != nil {
  502. return err
  503. }
  504. if u.Salt, err = GetUserSalt(); err != nil {
  505. return err
  506. }
  507. u.EncodePassword()
  508. u.MaxRepoCreation = -1
  509. sess := x.NewSession()
  510. defer sess.Close()
  511. if err = sess.Begin(); err != nil {
  512. return err
  513. }
  514. if _, err = sess.Insert(u); err != nil {
  515. return err
  516. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  517. return err
  518. }
  519. return sess.Commit()
  520. }
  521. func countUsers(e Engine) int64 {
  522. count, _ := e.Where("type=0").Count(new(User))
  523. return count
  524. }
  525. // CountUsers returns number of users.
  526. func CountUsers() int64 {
  527. return countUsers(x)
  528. }
  529. // Users returns number of users in given page.
  530. func ListUsers(page, pageSize int) ([]*User, error) {
  531. users := make([]*User, 0, pageSize)
  532. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  533. }
  534. // parseUserFromCode returns user by username encoded in code.
  535. // It returns nil if code or username is invalid.
  536. func parseUserFromCode(code string) (user *User) {
  537. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  538. return nil
  539. }
  540. // Use tail hex username to query user
  541. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  542. if b, err := hex.DecodeString(hexStr); err == nil {
  543. if user, err = GetUserByName(string(b)); user != nil {
  544. return user
  545. } else if !IsErrUserNotExist(err) {
  546. log.Error("Failed to get user by name %q: %v", string(b), err)
  547. }
  548. }
  549. return nil
  550. }
  551. // verify active code when active account
  552. func VerifyUserActiveCode(code string) (user *User) {
  553. minutes := conf.Auth.ActivateCodeLives
  554. if user = parseUserFromCode(code); user != nil {
  555. // time limit code
  556. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  557. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  558. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  559. return user
  560. }
  561. }
  562. return nil
  563. }
  564. // verify active code when active account
  565. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  566. minutes := conf.Auth.ActivateCodeLives
  567. if user := parseUserFromCode(code); user != nil {
  568. // time limit code
  569. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  570. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  571. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  572. emailAddress := &EmailAddress{Email: email}
  573. if has, _ := x.Get(emailAddress); has {
  574. return emailAddress
  575. }
  576. }
  577. }
  578. return nil
  579. }
  580. // ChangeUserName changes all corresponding setting from old user name to new one.
  581. func ChangeUserName(u *User, newUserName string) (err error) {
  582. if err = isUsernameAllowed(newUserName); err != nil {
  583. return err
  584. }
  585. isExist, err := IsUserExist(0, newUserName)
  586. if err != nil {
  587. return err
  588. } else if isExist {
  589. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  590. }
  591. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  592. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  593. }
  594. // Delete all local copies of repositories and wikis the user owns.
  595. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  596. repo := bean.(*Repository)
  597. deleteRepoLocalCopy(repo)
  598. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  599. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  600. return nil
  601. }); err != nil {
  602. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  603. }
  604. // Rename or create user base directory
  605. baseDir := UserPath(u.Name)
  606. newBaseDir := UserPath(newUserName)
  607. if com.IsExist(baseDir) {
  608. return os.Rename(baseDir, newBaseDir)
  609. }
  610. return os.MkdirAll(newBaseDir, os.ModePerm)
  611. }
  612. func updateUser(e Engine, u *User) error {
  613. // Organization does not need email
  614. if !u.IsOrganization() {
  615. u.Email = strings.ToLower(u.Email)
  616. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  617. if err != nil {
  618. return err
  619. } else if has {
  620. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  621. }
  622. if u.AvatarEmail == "" {
  623. u.AvatarEmail = u.Email
  624. }
  625. u.Avatar = tool.HashEmail(u.AvatarEmail)
  626. }
  627. u.LowerName = strings.ToLower(u.Name)
  628. u.Location = tool.TruncateString(u.Location, 255)
  629. u.Website = tool.TruncateString(u.Website, 255)
  630. u.Description = tool.TruncateString(u.Description, 255)
  631. _, err := e.ID(u.ID).AllCols().Update(u)
  632. return err
  633. }
  634. // UpdateUser updates user's information.
  635. func UpdateUser(u *User) error {
  636. return updateUser(x, u)
  637. }
  638. // deleteBeans deletes all given beans, beans should contain delete conditions.
  639. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  640. for i := range beans {
  641. if _, err = e.Delete(beans[i]); err != nil {
  642. return err
  643. }
  644. }
  645. return nil
  646. }
  647. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  648. func deleteUser(e *xorm.Session, u *User) error {
  649. // Note: A user owns any repository or belongs to any organization
  650. // cannot perform delete operation.
  651. // Check ownership of repository.
  652. count, err := getRepositoryCount(e, u)
  653. if err != nil {
  654. return fmt.Errorf("GetRepositoryCount: %v", err)
  655. } else if count > 0 {
  656. return ErrUserOwnRepos{UID: u.ID}
  657. }
  658. // Check membership of organization.
  659. count, err = u.getOrganizationCount(e)
  660. if err != nil {
  661. return fmt.Errorf("GetOrganizationCount: %v", err)
  662. } else if count > 0 {
  663. return ErrUserHasOrgs{UID: u.ID}
  664. }
  665. // ***** START: Watch *****
  666. watches := make([]*Watch, 0, 10)
  667. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  668. return fmt.Errorf("get all watches: %v", err)
  669. }
  670. for i := range watches {
  671. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  672. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  673. }
  674. }
  675. // ***** END: Watch *****
  676. // ***** START: Star *****
  677. stars := make([]*Star, 0, 10)
  678. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  679. return fmt.Errorf("get all stars: %v", err)
  680. }
  681. for i := range stars {
  682. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  683. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  684. }
  685. }
  686. // ***** END: Star *****
  687. // ***** START: Follow *****
  688. followers := make([]*Follow, 0, 10)
  689. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  690. return fmt.Errorf("get all followers: %v", err)
  691. }
  692. for i := range followers {
  693. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  694. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  695. }
  696. }
  697. // ***** END: Follow *****
  698. if err = deleteBeans(e,
  699. &AccessToken{UserID: u.ID},
  700. &Collaboration{UserID: u.ID},
  701. &Access{UserID: u.ID},
  702. &Watch{UserID: u.ID},
  703. &Star{UID: u.ID},
  704. &Follow{FollowID: u.ID},
  705. &Action{UserID: u.ID},
  706. &IssueUser{UID: u.ID},
  707. &EmailAddress{UID: u.ID},
  708. ); err != nil {
  709. return fmt.Errorf("deleteBeans: %v", err)
  710. }
  711. // ***** START: PublicKey *****
  712. keys := make([]*PublicKey, 0, 10)
  713. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  714. return fmt.Errorf("get all public keys: %v", err)
  715. }
  716. keyIDs := make([]int64, len(keys))
  717. for i := range keys {
  718. keyIDs[i] = keys[i].ID
  719. }
  720. if err = deletePublicKeys(e, keyIDs...); err != nil {
  721. return fmt.Errorf("deletePublicKeys: %v", err)
  722. }
  723. // ***** END: PublicKey *****
  724. // Clear assignee.
  725. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  726. return fmt.Errorf("clear assignee: %v", err)
  727. }
  728. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  729. return fmt.Errorf("Delete: %v", err)
  730. }
  731. // FIXME: system notice
  732. // Note: There are something just cannot be roll back,
  733. // so just keep error logs of those operations.
  734. _ = os.RemoveAll(UserPath(u.Name))
  735. _ = os.Remove(u.CustomAvatarPath())
  736. return nil
  737. }
  738. // DeleteUser completely and permanently deletes everything of a user,
  739. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  740. func DeleteUser(u *User) (err error) {
  741. sess := x.NewSession()
  742. defer sess.Close()
  743. if err = sess.Begin(); err != nil {
  744. return err
  745. }
  746. if err = deleteUser(sess, u); err != nil {
  747. // Note: don't wrapper error here.
  748. return err
  749. }
  750. if err = sess.Commit(); err != nil {
  751. return err
  752. }
  753. return RewriteAuthorizedKeys()
  754. }
  755. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  756. func DeleteInactivateUsers() (err error) {
  757. users := make([]*User, 0, 10)
  758. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  759. return fmt.Errorf("get all inactive users: %v", err)
  760. }
  761. // FIXME: should only update authorized_keys file once after all deletions.
  762. for _, u := range users {
  763. if err = DeleteUser(u); err != nil {
  764. // Ignore users that were set inactive by admin.
  765. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  766. continue
  767. }
  768. return err
  769. }
  770. }
  771. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  772. return err
  773. }
  774. // UserPath returns the path absolute path of user repositories.
  775. func UserPath(username string) string {
  776. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  777. }
  778. func GetUserByKeyID(keyID int64) (*User, error) {
  779. user := new(User)
  780. 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)
  781. if err != nil {
  782. return nil, err
  783. } else if !has {
  784. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  785. }
  786. return user, nil
  787. }
  788. func getUserByID(e Engine, id int64) (*User, error) {
  789. u := new(User)
  790. has, err := e.ID(id).Get(u)
  791. if err != nil {
  792. return nil, err
  793. } else if !has {
  794. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  795. }
  796. return u, nil
  797. }
  798. // GetUserByID returns the user object by given ID if exists.
  799. // Deprecated: Use Users.GetByID instead.
  800. func GetUserByID(id int64) (*User, error) {
  801. return getUserByID(x, id)
  802. }
  803. // GetAssigneeByID returns the user with read access of repository by given ID.
  804. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  805. ctx := context.TODO()
  806. if !Perms.Authorize(ctx, userID, repo.ID, AccessModeRead,
  807. AccessModeOptions{
  808. OwnerID: repo.OwnerID,
  809. Private: repo.IsPrivate,
  810. },
  811. ) {
  812. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  813. }
  814. return Users.GetByID(ctx, userID)
  815. }
  816. // GetUserByName returns a user by given name.
  817. // Deprecated: Use Users.GetByUsername instead.
  818. func GetUserByName(name string) (*User, error) {
  819. if name == "" {
  820. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  821. }
  822. u := &User{LowerName: strings.ToLower(name)}
  823. has, err := x.Get(u)
  824. if err != nil {
  825. return nil, err
  826. } else if !has {
  827. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  828. }
  829. return u, nil
  830. }
  831. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  832. func GetUserEmailsByNames(names []string) []string {
  833. mails := make([]string, 0, len(names))
  834. for _, name := range names {
  835. u, err := GetUserByName(name)
  836. if err != nil {
  837. continue
  838. }
  839. if u.IsMailable() {
  840. mails = append(mails, u.Email)
  841. }
  842. }
  843. return mails
  844. }
  845. // GetUserIDsByNames returns a slice of ids corresponds to names.
  846. func GetUserIDsByNames(names []string) []int64 {
  847. ids := make([]int64, 0, len(names))
  848. for _, name := range names {
  849. u, err := GetUserByName(name)
  850. if err != nil {
  851. continue
  852. }
  853. ids = append(ids, u.ID)
  854. }
  855. return ids
  856. }
  857. // UserCommit represents a commit with validation of user.
  858. type UserCommit struct {
  859. User *User
  860. *git.Commit
  861. }
  862. // ValidateCommitWithEmail checks if author's e-mail of commit is corresponding to a user.
  863. func ValidateCommitWithEmail(c *git.Commit) *User {
  864. u, err := GetUserByEmail(c.Author.Email)
  865. if err != nil {
  866. return nil
  867. }
  868. return u
  869. }
  870. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  871. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  872. emails := make(map[string]*User)
  873. newCommits := make([]*UserCommit, len(oldCommits))
  874. for i := range oldCommits {
  875. var u *User
  876. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  877. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  878. emails[oldCommits[i].Author.Email] = u
  879. } else {
  880. u = v
  881. }
  882. newCommits[i] = &UserCommit{
  883. User: u,
  884. Commit: oldCommits[i],
  885. }
  886. }
  887. return newCommits
  888. }
  889. // GetUserByEmail returns the user object by given e-mail if exists.
  890. // Deprecated: Use Users.GetByEmail instead.
  891. func GetUserByEmail(email string) (*User, error) {
  892. if email == "" {
  893. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  894. }
  895. email = strings.ToLower(email)
  896. // First try to find the user by primary email
  897. user := &User{Email: email}
  898. has, err := x.Get(user)
  899. if err != nil {
  900. return nil, err
  901. }
  902. if has {
  903. return user, nil
  904. }
  905. // Otherwise, check in alternative list for activated email addresses
  906. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  907. has, err = x.Get(emailAddress)
  908. if err != nil {
  909. return nil, err
  910. }
  911. if has {
  912. return GetUserByID(emailAddress.UID)
  913. }
  914. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  915. }
  916. type SearchUserOptions struct {
  917. Keyword string
  918. Type UserType
  919. OrderBy string
  920. Page int
  921. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  922. }
  923. // SearchUserByName takes keyword and part of user name to search,
  924. // it returns results in given range and number of total results.
  925. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  926. if opts.Keyword == "" {
  927. return users, 0, nil
  928. }
  929. opts.Keyword = strings.ToLower(opts.Keyword)
  930. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  931. opts.PageSize = conf.UI.ExplorePagingNum
  932. }
  933. if opts.Page <= 0 {
  934. opts.Page = 1
  935. }
  936. searchQuery := "%" + opts.Keyword + "%"
  937. users = make([]*User, 0, opts.PageSize)
  938. // Append conditions
  939. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  940. Or("LOWER(full_name) LIKE ?", searchQuery).
  941. And("type = ?", opts.Type)
  942. countSess := *sess
  943. count, err := countSess.Count(new(User))
  944. if err != nil {
  945. return nil, 0, fmt.Errorf("Count: %v", err)
  946. }
  947. if len(opts.OrderBy) > 0 {
  948. sess.OrderBy(opts.OrderBy)
  949. }
  950. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  951. }
  952. // ___________ .__ .__
  953. // \_ _____/___ | | | | ______ _ __
  954. // | __)/ _ \| | | | / _ \ \/ \/ /
  955. // | \( <_> ) |_| |_( <_> ) /
  956. // \___ / \____/|____/____/\____/ \/\_/
  957. // \/
  958. // Follow represents relations of user and his/her followers.
  959. type Follow struct {
  960. ID int64
  961. UserID int64 `xorm:"UNIQUE(follow)"`
  962. FollowID int64 `xorm:"UNIQUE(follow)"`
  963. }
  964. func IsFollowing(userID, followID int64) bool {
  965. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  966. return has
  967. }
  968. // FollowUser marks someone be another's follower.
  969. func FollowUser(userID, followID int64) (err error) {
  970. if userID == followID || IsFollowing(userID, followID) {
  971. return nil
  972. }
  973. sess := x.NewSession()
  974. defer sess.Close()
  975. if err = sess.Begin(); err != nil {
  976. return err
  977. }
  978. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  979. return err
  980. }
  981. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  982. return err
  983. }
  984. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  985. return err
  986. }
  987. return sess.Commit()
  988. }
  989. // UnfollowUser unmarks someone be another's follower.
  990. func UnfollowUser(userID, followID int64) (err error) {
  991. if userID == followID || !IsFollowing(userID, followID) {
  992. return nil
  993. }
  994. sess := x.NewSession()
  995. defer sess.Close()
  996. if err = sess.Begin(); err != nil {
  997. return err
  998. }
  999. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1000. return err
  1001. }
  1002. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1003. return err
  1004. }
  1005. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1006. return err
  1007. }
  1008. return sess.Commit()
  1009. }
  1010. // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
  1011. func (u *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
  1012. accesses := make([]*Access, 0, 10)
  1013. if err := x.Find(&accesses, &Access{UserID: u.ID}); err != nil {
  1014. return nil, err
  1015. }
  1016. repos := make(map[*Repository]AccessMode, len(accesses))
  1017. for _, access := range accesses {
  1018. repo, err := GetRepositoryByID(access.RepoID)
  1019. if err != nil {
  1020. if IsErrRepoNotExist(err) {
  1021. log.Error("Failed to get repository by ID: %v", err)
  1022. continue
  1023. }
  1024. return nil, err
  1025. }
  1026. if repo.OwnerID == u.ID {
  1027. continue
  1028. }
  1029. repos[repo] = access.Mode
  1030. }
  1031. return repos, nil
  1032. }
  1033. // GetAccessibleRepositories finds repositories which the user has access but does not own.
  1034. // If limit is smaller than 1 means returns all found results.
  1035. func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
  1036. sess := x.Where("owner_id !=? ", user.ID).Desc("updated_unix")
  1037. if limit > 0 {
  1038. sess.Limit(limit)
  1039. repos = make([]*Repository, 0, limit)
  1040. } else {
  1041. repos = make([]*Repository, 0, 10)
  1042. }
  1043. return repos, sess.Join("INNER", "access", "access.user_id = ? AND access.repo_id = repository.id", user.ID).Find(&repos)
  1044. }