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