Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

user.go 39KB

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