You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. // GetRepositoryIDs returns repositories IDs where user owned
  427. func (u *User) GetRepositoryIDs() ([]int64, error) {
  428. var ids []int64
  429. return ids, x.Table("repository").Cols("id").Where("owner_id = ?", u.ID).Find(&ids)
  430. }
  431. // GetOrgRepositoryIDs returns repositories IDs where user's team owned
  432. func (u *User) GetOrgRepositoryIDs() ([]int64, error) {
  433. var ids []int64
  434. return ids, x.Table("repository").
  435. Cols("repository.id").
  436. Join("INNER", "team_user", "repository.owner_id = team_user.org_id AND team_user.uid = ?", u.ID).
  437. GroupBy("repository.id").Find(&ids)
  438. }
  439. // GetAccessRepoIDs returns all repsitories IDs where user's or user is a team member orgnizations
  440. func (u *User) GetAccessRepoIDs() ([]int64, error) {
  441. ids, err := u.GetRepositoryIDs()
  442. if err != nil {
  443. return nil, err
  444. }
  445. ids2, err := u.GetOrgRepositoryIDs()
  446. if err != nil {
  447. return nil, err
  448. }
  449. return append(ids, ids2...), nil
  450. }
  451. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  452. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  453. return GetUserMirrorRepositories(u.ID)
  454. }
  455. // GetOwnedOrganizations returns all organizations that user owns.
  456. func (u *User) GetOwnedOrganizations() (err error) {
  457. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  458. return err
  459. }
  460. // GetOrganizations returns all organizations that user belongs to.
  461. func (u *User) GetOrganizations(all bool) error {
  462. ous, err := GetOrgUsersByUserID(u.ID, all)
  463. if err != nil {
  464. return err
  465. }
  466. u.Orgs = make([]*User, len(ous))
  467. for i, ou := range ous {
  468. u.Orgs[i], err = GetUserByID(ou.OrgID)
  469. if err != nil {
  470. return err
  471. }
  472. }
  473. return nil
  474. }
  475. // DisplayName returns full name if it's not empty,
  476. // returns username otherwise.
  477. func (u *User) DisplayName() string {
  478. if len(u.FullName) > 0 {
  479. return u.FullName
  480. }
  481. return u.Name
  482. }
  483. // ShortName ellipses username to length
  484. func (u *User) ShortName(length int) string {
  485. return base.EllipsisString(u.Name, length)
  486. }
  487. // IsMailable checks if a user is elegible
  488. // to receive emails.
  489. func (u *User) IsMailable() bool {
  490. return u.IsActive
  491. }
  492. // IsUserExist checks if given user name exist,
  493. // the user name should be noncased unique.
  494. // If uid is presented, then check will rule out that one,
  495. // it is used when update a user name in settings page.
  496. func IsUserExist(uid int64, name string) (bool, error) {
  497. if len(name) == 0 {
  498. return false, nil
  499. }
  500. return x.
  501. Where("id!=?", uid).
  502. Get(&User{LowerName: strings.ToLower(name)})
  503. }
  504. // GetUserSalt returns a ramdom user salt token.
  505. func GetUserSalt() (string, error) {
  506. return base.GetRandomString(10)
  507. }
  508. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  509. func NewGhostUser() *User {
  510. return &User{
  511. ID: -1,
  512. Name: "Ghost",
  513. LowerName: "ghost",
  514. }
  515. }
  516. var (
  517. reservedUsernames = []string{"assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  518. reservedUserPatterns = []string{"*.keys"}
  519. )
  520. // isUsableName checks if name is reserved or pattern of name is not allowed
  521. // based on given reserved names and patterns.
  522. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  523. func isUsableName(names, patterns []string, name string) error {
  524. name = strings.TrimSpace(strings.ToLower(name))
  525. if utf8.RuneCountInString(name) == 0 {
  526. return ErrNameEmpty
  527. }
  528. for i := range names {
  529. if name == names[i] {
  530. return ErrNameReserved{name}
  531. }
  532. }
  533. for _, pat := range patterns {
  534. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  535. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  536. return ErrNamePatternNotAllowed{pat}
  537. }
  538. }
  539. return nil
  540. }
  541. // IsUsableUsername returns an error when a username is reserved
  542. func IsUsableUsername(name string) error {
  543. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  544. }
  545. // CreateUser creates record of a new user.
  546. func CreateUser(u *User) (err error) {
  547. if err = IsUsableUsername(u.Name); err != nil {
  548. return err
  549. }
  550. isExist, err := IsUserExist(0, u.Name)
  551. if err != nil {
  552. return err
  553. } else if isExist {
  554. return ErrUserAlreadyExist{u.Name}
  555. }
  556. u.Email = strings.ToLower(u.Email)
  557. has, err := x.
  558. Where("email=?", u.Email).
  559. Get(new(User))
  560. if err != nil {
  561. return err
  562. } else if has {
  563. return ErrEmailAlreadyUsed{u.Email}
  564. }
  565. isExist, err = IsEmailUsed(u.Email)
  566. if err != nil {
  567. return err
  568. } else if isExist {
  569. return ErrEmailAlreadyUsed{u.Email}
  570. }
  571. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  572. u.LowerName = strings.ToLower(u.Name)
  573. u.AvatarEmail = u.Email
  574. u.Avatar = base.HashEmail(u.AvatarEmail)
  575. if u.Rands, err = GetUserSalt(); err != nil {
  576. return err
  577. }
  578. if u.Salt, err = GetUserSalt(); err != nil {
  579. return err
  580. }
  581. u.EncodePasswd()
  582. u.AllowCreateOrganization = true
  583. u.MaxRepoCreation = -1
  584. sess := x.NewSession()
  585. defer sessionRelease(sess)
  586. if err = sess.Begin(); err != nil {
  587. return err
  588. }
  589. if _, err = sess.Insert(u); err != nil {
  590. return err
  591. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  592. return err
  593. }
  594. return sess.Commit()
  595. }
  596. func countUsers(e Engine) int64 {
  597. count, _ := e.
  598. Where("type=0").
  599. Count(new(User))
  600. return count
  601. }
  602. // CountUsers returns number of users.
  603. func CountUsers() int64 {
  604. return countUsers(x)
  605. }
  606. // Users returns number of users in given page.
  607. func Users(opts *SearchUserOptions) ([]*User, error) {
  608. if len(opts.OrderBy) == 0 {
  609. opts.OrderBy = "name ASC"
  610. }
  611. users := make([]*User, 0, opts.PageSize)
  612. sess := x.
  613. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  614. Where("type=0")
  615. return users, sess.
  616. OrderBy(opts.OrderBy).
  617. Find(&users)
  618. }
  619. // get user by verify code
  620. func getVerifyUser(code string) (user *User) {
  621. if len(code) <= base.TimeLimitCodeLength {
  622. return nil
  623. }
  624. // use tail hex username query user
  625. hexStr := code[base.TimeLimitCodeLength:]
  626. if b, err := hex.DecodeString(hexStr); err == nil {
  627. if user, err = GetUserByName(string(b)); user != nil {
  628. return user
  629. }
  630. log.Error(4, "user.getVerifyUser: %v", err)
  631. }
  632. return nil
  633. }
  634. // VerifyUserActiveCode verifies active code when active account
  635. func VerifyUserActiveCode(code string) (user *User) {
  636. minutes := setting.Service.ActiveCodeLives
  637. if user = getVerifyUser(code); user != nil {
  638. // time limit code
  639. prefix := code[:base.TimeLimitCodeLength]
  640. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  641. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  642. return user
  643. }
  644. }
  645. return nil
  646. }
  647. // VerifyActiveEmailCode verifies active email code when active account
  648. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  649. minutes := setting.Service.ActiveCodeLives
  650. if user := getVerifyUser(code); user != nil {
  651. // time limit code
  652. prefix := code[:base.TimeLimitCodeLength]
  653. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  654. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  655. emailAddress := &EmailAddress{Email: email}
  656. if has, _ := x.Get(emailAddress); has {
  657. return emailAddress
  658. }
  659. }
  660. }
  661. return nil
  662. }
  663. // ChangeUserName changes all corresponding setting from old user name to new one.
  664. func ChangeUserName(u *User, newUserName string) (err error) {
  665. if err = IsUsableUsername(newUserName); err != nil {
  666. return err
  667. }
  668. isExist, err := IsUserExist(0, newUserName)
  669. if err != nil {
  670. return err
  671. } else if isExist {
  672. return ErrUserAlreadyExist{newUserName}
  673. }
  674. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  675. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  676. }
  677. // Delete all local copies of repository wiki that user owns.
  678. if err = x.
  679. Where("owner_id=?", u.ID).
  680. Iterate(new(Repository), func(idx int, bean interface{}) error {
  681. repo := bean.(*Repository)
  682. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  683. return nil
  684. }); err != nil {
  685. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  686. }
  687. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  688. }
  689. func updateUser(e Engine, u *User) error {
  690. // Organization does not need email
  691. if !u.IsOrganization() {
  692. u.Email = strings.ToLower(u.Email)
  693. has, err := e.
  694. Where("id!=?", u.ID).
  695. And("type=?", u.Type).
  696. And("email=?", u.Email).
  697. Get(new(User))
  698. if err != nil {
  699. return err
  700. } else if has {
  701. return ErrEmailAlreadyUsed{u.Email}
  702. }
  703. if len(u.AvatarEmail) == 0 {
  704. u.AvatarEmail = u.Email
  705. }
  706. u.Avatar = base.HashEmail(u.AvatarEmail)
  707. }
  708. u.LowerName = strings.ToLower(u.Name)
  709. u.Location = base.TruncateString(u.Location, 255)
  710. u.Website = base.TruncateString(u.Website, 255)
  711. u.Description = base.TruncateString(u.Description, 255)
  712. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  713. _, err := e.Id(u.ID).AllCols().Update(u)
  714. return err
  715. }
  716. // UpdateUser updates user's information.
  717. func UpdateUser(u *User) error {
  718. return updateUser(x, u)
  719. }
  720. // deleteBeans deletes all given beans, beans should contain delete conditions.
  721. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  722. for i := range beans {
  723. if _, err = e.Delete(beans[i]); err != nil {
  724. return err
  725. }
  726. }
  727. return nil
  728. }
  729. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  730. func deleteUser(e *xorm.Session, u *User) error {
  731. // Note: A user owns any repository or belongs to any organization
  732. // cannot perform delete operation.
  733. // Check ownership of repository.
  734. count, err := getRepositoryCount(e, u)
  735. if err != nil {
  736. return fmt.Errorf("GetRepositoryCount: %v", err)
  737. } else if count > 0 {
  738. return ErrUserOwnRepos{UID: u.ID}
  739. }
  740. // Check membership of organization.
  741. count, err = u.getOrganizationCount(e)
  742. if err != nil {
  743. return fmt.Errorf("GetOrganizationCount: %v", err)
  744. } else if count > 0 {
  745. return ErrUserHasOrgs{UID: u.ID}
  746. }
  747. // ***** START: Watch *****
  748. watches := make([]*Watch, 0, 10)
  749. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  750. return fmt.Errorf("get all watches: %v", err)
  751. }
  752. for i := range watches {
  753. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  754. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  755. }
  756. }
  757. // ***** END: Watch *****
  758. // ***** START: Star *****
  759. stars := make([]*Star, 0, 10)
  760. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  761. return fmt.Errorf("get all stars: %v", err)
  762. }
  763. for i := range stars {
  764. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  765. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  766. }
  767. }
  768. // ***** END: Star *****
  769. // ***** START: Follow *****
  770. followers := make([]*Follow, 0, 10)
  771. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  772. return fmt.Errorf("get all followers: %v", err)
  773. }
  774. for i := range followers {
  775. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  776. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  777. }
  778. }
  779. // ***** END: Follow *****
  780. if err = deleteBeans(e,
  781. &AccessToken{UID: u.ID},
  782. &Collaboration{UserID: u.ID},
  783. &Access{UserID: u.ID},
  784. &Watch{UserID: u.ID},
  785. &Star{UID: u.ID},
  786. &Follow{FollowID: u.ID},
  787. &Action{UserID: u.ID},
  788. &IssueUser{UID: u.ID},
  789. &EmailAddress{UID: u.ID},
  790. ); err != nil {
  791. return fmt.Errorf("deleteBeans: %v", err)
  792. }
  793. // ***** START: PublicKey *****
  794. keys := make([]*PublicKey, 0, 10)
  795. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  796. return fmt.Errorf("get all public keys: %v", err)
  797. }
  798. keyIDs := make([]int64, len(keys))
  799. for i := range keys {
  800. keyIDs[i] = keys[i].ID
  801. }
  802. if err = deletePublicKeys(e, keyIDs...); err != nil {
  803. return fmt.Errorf("deletePublicKeys: %v", err)
  804. }
  805. // ***** END: PublicKey *****
  806. // Clear assignee.
  807. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  808. return fmt.Errorf("clear assignee: %v", err)
  809. }
  810. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  811. return fmt.Errorf("Delete: %v", err)
  812. }
  813. // FIXME: system notice
  814. // Note: There are something just cannot be roll back,
  815. // so just keep error logs of those operations.
  816. path := UserPath(u.Name)
  817. if err := os.RemoveAll(path); err != nil {
  818. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  819. }
  820. avatarPath := u.CustomAvatarPath()
  821. if com.IsExist(avatarPath) {
  822. if err := os.Remove(avatarPath); err != nil {
  823. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  824. }
  825. }
  826. return nil
  827. }
  828. // DeleteUser completely and permanently deletes everything of a user,
  829. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  830. func DeleteUser(u *User) (err error) {
  831. sess := x.NewSession()
  832. defer sessionRelease(sess)
  833. if err = sess.Begin(); err != nil {
  834. return err
  835. }
  836. if err = deleteUser(sess, u); err != nil {
  837. // Note: don't wrapper error here.
  838. return err
  839. }
  840. if err = sess.Commit(); err != nil {
  841. return err
  842. }
  843. return RewriteAllPublicKeys()
  844. }
  845. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  846. func DeleteInactivateUsers() (err error) {
  847. users := make([]*User, 0, 10)
  848. if err = x.
  849. Where("is_active = ?", false).
  850. Find(&users); err != nil {
  851. return fmt.Errorf("get all inactive users: %v", err)
  852. }
  853. // FIXME: should only update authorized_keys file once after all deletions.
  854. for _, u := range users {
  855. if err = DeleteUser(u); err != nil {
  856. // Ignore users that were set inactive by admin.
  857. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  858. continue
  859. }
  860. return err
  861. }
  862. }
  863. _, err = x.
  864. Where("is_activated = ?", false).
  865. Delete(new(EmailAddress))
  866. return err
  867. }
  868. // UserPath returns the path absolute path of user repositories.
  869. func UserPath(userName string) string {
  870. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  871. }
  872. // GetUserByKeyID get user information by user's public key id
  873. func GetUserByKeyID(keyID int64) (*User, error) {
  874. var user User
  875. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  876. Where("`public_key`.id=?", keyID).
  877. Get(&user)
  878. if err != nil {
  879. return nil, err
  880. }
  881. if !has {
  882. return nil, ErrUserNotExist{0, "", keyID}
  883. }
  884. return &user, nil
  885. }
  886. func getUserByID(e Engine, id int64) (*User, error) {
  887. u := new(User)
  888. has, err := e.Id(id).Get(u)
  889. if err != nil {
  890. return nil, err
  891. } else if !has {
  892. return nil, ErrUserNotExist{id, "", 0}
  893. }
  894. return u, nil
  895. }
  896. // GetUserByID returns the user object by given ID if exists.
  897. func GetUserByID(id int64) (*User, error) {
  898. return getUserByID(x, id)
  899. }
  900. // GetAssigneeByID returns the user with write access of repository by given ID.
  901. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  902. has, err := HasAccess(&User{ID: userID}, repo, AccessModeWrite)
  903. if err != nil {
  904. return nil, err
  905. } else if !has {
  906. return nil, ErrUserNotExist{userID, "", 0}
  907. }
  908. return GetUserByID(userID)
  909. }
  910. // GetUserByName returns user by given name.
  911. func GetUserByName(name string) (*User, error) {
  912. if len(name) == 0 {
  913. return nil, ErrUserNotExist{0, name, 0}
  914. }
  915. u := &User{LowerName: strings.ToLower(name)}
  916. has, err := x.Get(u)
  917. if err != nil {
  918. return nil, err
  919. } else if !has {
  920. return nil, ErrUserNotExist{0, name, 0}
  921. }
  922. return u, nil
  923. }
  924. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  925. func GetUserEmailsByNames(names []string) []string {
  926. mails := make([]string, 0, len(names))
  927. for _, name := range names {
  928. u, err := GetUserByName(name)
  929. if err != nil {
  930. continue
  931. }
  932. if u.IsMailable() {
  933. mails = append(mails, u.Email)
  934. }
  935. }
  936. return mails
  937. }
  938. // GetUsersByIDs returns all resolved users from a list of Ids.
  939. func GetUsersByIDs(ids []int64) ([]*User, error) {
  940. ous := make([]*User, 0, len(ids))
  941. if len(ids) == 0 {
  942. return ous, nil
  943. }
  944. err := x.In("id", ids).
  945. Asc("name").
  946. Find(&ous)
  947. return ous, err
  948. }
  949. // GetUserIDsByNames returns a slice of ids corresponds to names.
  950. func GetUserIDsByNames(names []string) []int64 {
  951. ids := make([]int64, 0, len(names))
  952. for _, name := range names {
  953. u, err := GetUserByName(name)
  954. if err != nil {
  955. continue
  956. }
  957. ids = append(ids, u.ID)
  958. }
  959. return ids
  960. }
  961. // UserCommit represents a commit with validation of user.
  962. type UserCommit struct {
  963. User *User
  964. *git.Commit
  965. }
  966. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  967. func ValidateCommitWithEmail(c *git.Commit) *User {
  968. u, err := GetUserByEmail(c.Author.Email)
  969. if err != nil {
  970. return nil
  971. }
  972. return u
  973. }
  974. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  975. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  976. var (
  977. u *User
  978. emails = map[string]*User{}
  979. newCommits = list.New()
  980. e = oldCommits.Front()
  981. )
  982. for e != nil {
  983. c := e.Value.(*git.Commit)
  984. if v, ok := emails[c.Author.Email]; !ok {
  985. u, _ = GetUserByEmail(c.Author.Email)
  986. emails[c.Author.Email] = u
  987. } else {
  988. u = v
  989. }
  990. newCommits.PushBack(UserCommit{
  991. User: u,
  992. Commit: c,
  993. })
  994. e = e.Next()
  995. }
  996. return newCommits
  997. }
  998. // GetUserByEmail returns the user object by given e-mail if exists.
  999. func GetUserByEmail(email string) (*User, error) {
  1000. if len(email) == 0 {
  1001. return nil, ErrUserNotExist{0, email, 0}
  1002. }
  1003. email = strings.ToLower(email)
  1004. // First try to find the user by primary email
  1005. user := &User{Email: email}
  1006. has, err := x.Get(user)
  1007. if err != nil {
  1008. return nil, err
  1009. }
  1010. if has {
  1011. return user, nil
  1012. }
  1013. // Otherwise, check in alternative list for activated email addresses
  1014. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1015. has, err = x.Get(emailAddress)
  1016. if err != nil {
  1017. return nil, err
  1018. }
  1019. if has {
  1020. return GetUserByID(emailAddress.UID)
  1021. }
  1022. return nil, ErrUserNotExist{0, email, 0}
  1023. }
  1024. // SearchUserOptions contains the options for searching
  1025. type SearchUserOptions struct {
  1026. Keyword string
  1027. Type UserType
  1028. OrderBy string
  1029. Page int
  1030. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1031. }
  1032. // SearchUserByName takes keyword and part of user name to search,
  1033. // it returns results in given range and number of total results.
  1034. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1035. if len(opts.Keyword) == 0 {
  1036. return users, 0, nil
  1037. }
  1038. opts.Keyword = strings.ToLower(opts.Keyword)
  1039. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1040. opts.PageSize = setting.UI.ExplorePagingNum
  1041. }
  1042. if opts.Page <= 0 {
  1043. opts.Page = 1
  1044. }
  1045. searchQuery := "%" + opts.Keyword + "%"
  1046. users = make([]*User, 0, opts.PageSize)
  1047. // Append conditions
  1048. sess := x.
  1049. Where("LOWER(lower_name) LIKE ?", searchQuery).
  1050. Or("LOWER(full_name) LIKE ?", searchQuery).
  1051. And("type = ?", opts.Type)
  1052. var countSess xorm.Session
  1053. countSess = *sess
  1054. count, err := countSess.Count(new(User))
  1055. if err != nil {
  1056. return nil, 0, fmt.Errorf("Count: %v", err)
  1057. }
  1058. if len(opts.OrderBy) > 0 {
  1059. sess.OrderBy(opts.OrderBy)
  1060. }
  1061. return users, count, sess.
  1062. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  1063. Find(&users)
  1064. }
  1065. // ___________ .__ .__
  1066. // \_ _____/___ | | | | ______ _ __
  1067. // | __)/ _ \| | | | / _ \ \/ \/ /
  1068. // | \( <_> ) |_| |_( <_> ) /
  1069. // \___ / \____/|____/____/\____/ \/\_/
  1070. // \/
  1071. // Follow represents relations of user and his/her followers.
  1072. type Follow struct {
  1073. ID int64 `xorm:"pk autoincr"`
  1074. UserID int64 `xorm:"UNIQUE(follow)"`
  1075. FollowID int64 `xorm:"UNIQUE(follow)"`
  1076. }
  1077. // IsFollowing returns true if user is following followID.
  1078. func IsFollowing(userID, followID int64) bool {
  1079. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  1080. return has
  1081. }
  1082. // FollowUser marks someone be another's follower.
  1083. func FollowUser(userID, followID int64) (err error) {
  1084. if userID == followID || IsFollowing(userID, followID) {
  1085. return nil
  1086. }
  1087. sess := x.NewSession()
  1088. defer sessionRelease(sess)
  1089. if err = sess.Begin(); err != nil {
  1090. return err
  1091. }
  1092. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1093. return err
  1094. }
  1095. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1096. return err
  1097. }
  1098. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1099. return err
  1100. }
  1101. return sess.Commit()
  1102. }
  1103. // UnfollowUser unmarks someone as another's follower.
  1104. func UnfollowUser(userID, followID int64) (err error) {
  1105. if userID == followID || !IsFollowing(userID, followID) {
  1106. return nil
  1107. }
  1108. sess := x.NewSession()
  1109. defer sessionRelease(sess)
  1110. if err = sess.Begin(); err != nil {
  1111. return err
  1112. }
  1113. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1114. return err
  1115. }
  1116. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1117. return err
  1118. }
  1119. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1120. return err
  1121. }
  1122. return sess.Commit()
  1123. }
  1124. // GetStarredRepos returns the repos starred by a particular user
  1125. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1126. sess := x.Where("star.uid=?", userID).
  1127. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1128. if !private {
  1129. sess = sess.And("is_private=?", false)
  1130. }
  1131. repos := make([]*Repository, 0, 10)
  1132. err := sess.Find(&repos)
  1133. if err != nil {
  1134. return nil, err
  1135. }
  1136. return repos, nil
  1137. }
  1138. // GetWatchedRepos returns the repos watched by a particular user
  1139. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1140. sess := x.Where("watch.user_id=?", userID).
  1141. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1142. if !private {
  1143. sess = sess.And("is_private=?", false)
  1144. }
  1145. repos := make([]*Repository, 0, 10)
  1146. err := sess.Find(&repos)
  1147. if err != nil {
  1148. return nil, err
  1149. }
  1150. return repos, nil
  1151. }