user.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. // USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
  36. const USER_AVATAR_URL_PREFIX = "avatars"
  37. type UserType int
  38. const (
  39. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  40. USER_TYPE_ORGANIZATION
  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. Devto 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, USER_AVATAR_URL_PREFIX, 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, USER_AVATAR_URL_PREFIX, 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 == USER_TYPE_ORGANIZATION
  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 = ?", USER_TYPE_ORGANIZATION).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", ".", ".."}
  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. func IsUsableUsername(name string) error {
  498. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  499. }
  500. // CreateUser creates record of a new user.
  501. func CreateUser(u *User) (err error) {
  502. if err = IsUsableUsername(u.Name); err != nil {
  503. return err
  504. }
  505. isExist, err := IsUserExist(0, u.Name)
  506. if err != nil {
  507. return err
  508. } else if isExist {
  509. return ErrUserAlreadyExist{u.Name}
  510. }
  511. u.Email = strings.ToLower(u.Email)
  512. isExist, err = IsEmailUsed(u.Email)
  513. if err != nil {
  514. return err
  515. } else if isExist {
  516. return ErrEmailAlreadyUsed{u.Email}
  517. }
  518. u.LowerName = strings.ToLower(u.Name)
  519. u.AvatarEmail = u.Email
  520. u.Avatar = tool.HashEmail(u.AvatarEmail)
  521. if u.Rands, err = GetUserSalt(); err != nil {
  522. return err
  523. }
  524. if u.Salt, err = GetUserSalt(); err != nil {
  525. return err
  526. }
  527. u.EncodePasswd()
  528. u.MaxRepoCreation = -1
  529. sess := x.NewSession()
  530. defer sess.Close()
  531. if err = sess.Begin(); err != nil {
  532. return err
  533. }
  534. if _, err = sess.Insert(u); err != nil {
  535. return err
  536. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  537. return err
  538. }
  539. return sess.Commit()
  540. }
  541. func countUsers(e Engine) int64 {
  542. count, _ := e.Where("type=0").Count(new(User))
  543. return count
  544. }
  545. // CountUsers returns number of users.
  546. func CountUsers() int64 {
  547. return countUsers(x)
  548. }
  549. // Users returns number of users in given page.
  550. func Users(page, pageSize int) ([]*User, error) {
  551. users := make([]*User, 0, pageSize)
  552. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  553. }
  554. // parseUserFromCode returns user by username encoded in code.
  555. // It returns nil if code or username is invalid.
  556. func parseUserFromCode(code string) (user *User) {
  557. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  558. return nil
  559. }
  560. // Use tail hex username to query user
  561. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  562. if b, err := hex.DecodeString(hexStr); err == nil {
  563. if user, err = GetUserByName(string(b)); user != nil {
  564. return user
  565. } else if !errors.IsUserNotExist(err) {
  566. raven.CaptureErrorAndWait(err, nil)
  567. log.Error(2, "GetUserByName: %v", err)
  568. }
  569. }
  570. return nil
  571. }
  572. // verify active code when active account
  573. func VerifyUserActiveCode(code string) (user *User) {
  574. minutes := setting.Service.ActiveCodeLives
  575. if user = parseUserFromCode(code); user != nil {
  576. // time limit code
  577. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  578. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  579. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  580. return user
  581. }
  582. }
  583. return nil
  584. }
  585. // verify active code when active account
  586. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  587. minutes := setting.Service.ActiveCodeLives
  588. if user := parseUserFromCode(code); user != nil {
  589. // time limit code
  590. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  591. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  592. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  593. emailAddress := &EmailAddress{Email: email}
  594. if has, _ := x.Get(emailAddress); has {
  595. return emailAddress
  596. }
  597. }
  598. }
  599. return nil
  600. }
  601. // ChangeUserName changes all corresponding setting from old user name to new one.
  602. func ChangeUserName(u *User, newUserName string) (err error) {
  603. if err = IsUsableUsername(newUserName); err != nil {
  604. return err
  605. }
  606. isExist, err := IsUserExist(0, newUserName)
  607. if err != nil {
  608. return err
  609. } else if isExist {
  610. return ErrUserAlreadyExist{newUserName}
  611. }
  612. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  613. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  614. }
  615. // Delete all local copies of repository wiki that user owns.
  616. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  617. repo := bean.(*Repository)
  618. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  619. return nil
  620. }); err != nil {
  621. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  622. }
  623. // Rename or create user base directory
  624. baseDir := UserPath(u.Name)
  625. newBaseDir := UserPath(newUserName)
  626. if com.IsExist(baseDir) {
  627. return os.Rename(baseDir, newBaseDir)
  628. }
  629. return os.MkdirAll(newBaseDir, os.ModePerm)
  630. }
  631. func updateUser(e Engine, u *User) error {
  632. // Organization does not need email
  633. if !u.IsOrganization() {
  634. u.Email = strings.ToLower(u.Email)
  635. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  636. if err != nil {
  637. return err
  638. } else if has {
  639. return ErrEmailAlreadyUsed{u.Email}
  640. }
  641. if len(u.AvatarEmail) == 0 {
  642. u.AvatarEmail = u.Email
  643. }
  644. u.Avatar = tool.HashEmail(u.AvatarEmail)
  645. }
  646. if len(u.Description) > 255 {
  647. u.Description = u.Description[:255]
  648. }
  649. u.LowerName = strings.ToLower(u.Name)
  650. u.Company = tool.TruncateString(u.Company, 255)
  651. u.Location = tool.TruncateString(u.Location, 255)
  652. u.Website = tool.TruncateString(u.Website, 255)
  653. _, err := e.ID(u.ID).AllCols().Update(u)
  654. return err
  655. }
  656. // UpdateUser updates user's information.
  657. func UpdateUser(u *User) error {
  658. return updateUser(x, u)
  659. }
  660. // deleteBeans deletes all given beans, beans should contain delete conditions.
  661. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  662. for i := range beans {
  663. if _, err = e.Delete(beans[i]); err != nil {
  664. return err
  665. }
  666. }
  667. return nil
  668. }
  669. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  670. func deleteUser(e *xorm.Session, u *User) error {
  671. // Note: A user owns any repository or belongs to any organization
  672. // cannot perform delete operation.
  673. // Check ownership of repository.
  674. count, err := getRepositoryCount(e, u)
  675. if err != nil {
  676. return fmt.Errorf("GetRepositoryCount: %v", err)
  677. } else if count > 0 {
  678. return ErrUserOwnRepos{UID: u.ID}
  679. }
  680. // Check membership of organization.
  681. count, err = u.getOrganizationCount(e)
  682. if err != nil {
  683. return fmt.Errorf("GetOrganizationCount: %v", err)
  684. } else if count > 0 {
  685. return ErrUserHasOrgs{UID: u.ID}
  686. }
  687. // ***** START: Watch *****
  688. watches := make([]*Watch, 0, 10)
  689. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  690. return fmt.Errorf("get all watches: %v", err)
  691. }
  692. for i := range watches {
  693. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  694. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  695. }
  696. }
  697. // ***** END: Watch *****
  698. // ***** START: Star *****
  699. stars := make([]*Star, 0, 10)
  700. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  701. return fmt.Errorf("get all stars: %v", err)
  702. }
  703. for i := range stars {
  704. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  705. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  706. }
  707. }
  708. // ***** END: Star *****
  709. // ***** START: Follow *****
  710. followers := make([]*Follow, 0, 10)
  711. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  712. return fmt.Errorf("get all followers: %v", err)
  713. }
  714. for i := range followers {
  715. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  716. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  717. }
  718. }
  719. // ***** END: Follow *****
  720. if err = deleteBeans(e,
  721. &AccessToken{UID: u.ID},
  722. &Collaboration{UserID: u.ID},
  723. &Access{UserID: u.ID},
  724. &Watch{UserID: u.ID},
  725. &Star{UID: u.ID},
  726. &Follow{FollowID: u.ID},
  727. &Action{UserID: u.ID},
  728. &IssueUser{UID: u.ID},
  729. &EmailAddress{UID: u.ID},
  730. ); err != nil {
  731. return fmt.Errorf("deleteBeans: %v", err)
  732. }
  733. // ***** START: PublicKey *****
  734. keys := make([]*PublicKey, 0, 10)
  735. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  736. return fmt.Errorf("get all public keys: %v", err)
  737. }
  738. keyIDs := make([]int64, len(keys))
  739. for i := range keys {
  740. keyIDs[i] = keys[i].ID
  741. }
  742. if err = deletePublicKeys(e, keyIDs...); err != nil {
  743. return fmt.Errorf("deletePublicKeys: %v", err)
  744. }
  745. // ***** END: PublicKey *****
  746. // Clear assignee.
  747. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  748. return fmt.Errorf("clear assignee: %v", err)
  749. }
  750. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  751. return fmt.Errorf("Delete: %v", err)
  752. }
  753. // FIXME: system notice
  754. // Note: There are something just cannot be roll back,
  755. // so just keep error logs of those operations.
  756. os.RemoveAll(UserPath(u.Name))
  757. os.Remove(u.CustomAvatarPath())
  758. return nil
  759. }
  760. // DeleteUser completely and permanently deletes everything of a user,
  761. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  762. func DeleteUser(u *User) (err error) {
  763. sess := x.NewSession()
  764. defer sess.Close()
  765. if err = sess.Begin(); err != nil {
  766. return err
  767. }
  768. if err = deleteUser(sess, u); err != nil {
  769. // Note: don't wrapper error here.
  770. return err
  771. }
  772. if err = sess.Commit(); err != nil {
  773. return err
  774. }
  775. return RewriteAuthorizedKeys()
  776. }
  777. // UserPath returns the path absolute path of user repositories.
  778. func UserPath(userName string) string {
  779. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  780. }
  781. func GetUserByKeyID(keyID int64) (*User, error) {
  782. user := new(User)
  783. 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)
  784. if err != nil {
  785. return nil, err
  786. } else if !has {
  787. return nil, errors.UserNotKeyOwner{keyID}
  788. }
  789. return user, nil
  790. }
  791. func getUserByID(e Engine, id int64) (*User, error) {
  792. u := new(User)
  793. has, err := e.ID(id).Get(u)
  794. if err != nil {
  795. return nil, err
  796. } else if !has {
  797. return nil, errors.UserNotExist{id, ""}
  798. }
  799. return u, nil
  800. }
  801. // GetUserByID returns the user object by given ID if exists.
  802. func GetUserByID(id int64) (*User, error) {
  803. return getUserByID(x, id)
  804. }
  805. // GetAssigneeByID returns the user with write access of repository by given ID.
  806. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  807. has, err := HasAccess(userID, repo, AccessModeRead)
  808. if err != nil {
  809. return nil, err
  810. } else if !has {
  811. return nil, errors.UserNotExist{userID, ""}
  812. }
  813. return GetUserByID(userID)
  814. }
  815. // GetUserByName returns a user by given name.
  816. func GetUserByName(name string) (*User, error) {
  817. if len(name) == 0 {
  818. return nil, errors.UserNotExist{0, name}
  819. }
  820. u := &User{LowerName: strings.ToLower(name)}
  821. has, err := x.Get(u)
  822. if err != nil {
  823. return nil, err
  824. } else if !has {
  825. return nil, errors.UserNotExist{0, name}
  826. }
  827. return u, nil
  828. }
  829. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  830. func GetUserEmailsByNames(names []string) []string {
  831. mails := make([]string, 0, len(names))
  832. for _, name := range names {
  833. u, err := GetUserByName(name)
  834. if err != nil {
  835. continue
  836. }
  837. if u.IsMailable() {
  838. mails = append(mails, u.Email)
  839. }
  840. }
  841. return mails
  842. }
  843. // GetUserIDsByNames returns a slice of ids corresponds to names.
  844. func GetUserIDsByNames(names []string) []int64 {
  845. ids := make([]int64, 0, len(names))
  846. for _, name := range names {
  847. u, err := GetUserByName(name)
  848. if err != nil {
  849. continue
  850. }
  851. ids = append(ids, u.ID)
  852. }
  853. return ids
  854. }
  855. // UserCommit represents a commit with validation of user.
  856. type UserCommit struct {
  857. User *User
  858. *git.Commit
  859. }
  860. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  861. func ValidateCommitWithEmail(c *git.Commit) *User {
  862. u, err := GetUserByEmail(c.Author.Email)
  863. if err != nil {
  864. return nil
  865. }
  866. return u
  867. }
  868. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  869. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  870. var (
  871. u *User
  872. emails = map[string]*User{}
  873. newCommits = list.New()
  874. e = oldCommits.Front()
  875. )
  876. for e != nil {
  877. c := e.Value.(*git.Commit)
  878. if v, ok := emails[c.Author.Email]; !ok {
  879. u, _ = GetUserByEmail(c.Author.Email)
  880. emails[c.Author.Email] = u
  881. } else {
  882. u = v
  883. }
  884. newCommits.PushBack(UserCommit{
  885. User: u,
  886. Commit: c,
  887. })
  888. e = e.Next()
  889. }
  890. return newCommits
  891. }
  892. // GetUserByEmail returns the user object by given e-mail if exists.
  893. func GetUserByEmail(email string) (*User, error) {
  894. if len(email) == 0 {
  895. return nil, errors.UserNotExist{0, "email"}
  896. }
  897. email = strings.ToLower(email)
  898. // First try to find the user by primary email
  899. user := &User{Email: email}
  900. has, err := x.Get(user)
  901. if err != nil {
  902. return nil, err
  903. }
  904. if has {
  905. return user, nil
  906. }
  907. // Otherwise, check in alternative list for activated email addresses
  908. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  909. has, err = x.Get(emailAddress)
  910. if err != nil {
  911. return nil, err
  912. }
  913. if has {
  914. return GetUserByID(emailAddress.UID)
  915. }
  916. return nil, errors.UserNotExist{0, email}
  917. }
  918. type SearchUserOptions struct {
  919. Keyword string
  920. Type UserType
  921. OrderBy string
  922. Page int
  923. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  924. }
  925. // SearchUserByName takes keyword and part of user name to search,
  926. // it returns results in given range and number of total results.
  927. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  928. if len(opts.Keyword) == 0 {
  929. return users, 0, nil
  930. }
  931. opts.Keyword = strings.ToLower(opts.Keyword)
  932. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  933. opts.PageSize = setting.UI.ExplorePagingNum
  934. }
  935. if opts.Page <= 0 {
  936. opts.Page = 1
  937. }
  938. searchQuery := "%" + opts.Keyword + "%"
  939. users = make([]*User, 0, opts.PageSize)
  940. // Append conditions
  941. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  942. Or("LOWER(full_name) LIKE ?", searchQuery).
  943. And("type = ?", opts.Type)
  944. var countSess xorm.Session
  945. countSess = *sess
  946. count, err := countSess.Count(new(User))
  947. if err != nil {
  948. return nil, 0, fmt.Errorf("Count: %v", err)
  949. }
  950. if len(opts.OrderBy) > 0 {
  951. sess.OrderBy(opts.OrderBy)
  952. }
  953. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  954. }
  955. // Follow represents relations of user and his/her followers.
  956. type Follow struct {
  957. ID int64
  958. UserID int64 `xorm:"UNIQUE(follow)"`
  959. FollowID int64 `xorm:"UNIQUE(follow)"`
  960. }
  961. func IsFollowing(userID, followID int64) bool {
  962. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  963. return has
  964. }
  965. // FollowUser marks someone be another's follower.
  966. func FollowUser(userID, followID int64) (err error) {
  967. if userID == followID || IsFollowing(userID, followID) {
  968. return nil
  969. }
  970. sess := x.NewSession()
  971. defer sess.Close()
  972. if err = sess.Begin(); err != nil {
  973. return err
  974. }
  975. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  976. return err
  977. }
  978. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  979. return err
  980. }
  981. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  982. return err
  983. }
  984. return sess.Commit()
  985. }
  986. // UnfollowUser unmarks someone be another's follower.
  987. func UnfollowUser(userID, followID int64) (err error) {
  988. if userID == followID || !IsFollowing(userID, followID) {
  989. return nil
  990. }
  991. sess := x.NewSession()
  992. defer sess.Close()
  993. if err = sess.Begin(); err != nil {
  994. return err
  995. }
  996. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  997. return err
  998. }
  999. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1000. return err
  1001. }
  1002. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1003. return err
  1004. }
  1005. return sess.Commit()
  1006. }