user.go 32 KB

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