user.go 31 KB

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