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 36 kB

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