user.go 32 KB

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