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