Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

user.go 35KB

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