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

user.go 34 kB

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