user.go 32 KB

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