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

user.go 39KB

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