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.

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