check_client_ip_job.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. package job
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "log"
  7. "os"
  8. "os/exec"
  9. "runtime"
  10. "sort"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  16. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  17. "gorm.io/gorm"
  18. )
  19. // IPWithTimestamp tracks an IP address with its last seen timestamp
  20. type IPWithTimestamp struct {
  21. IP string `json:"ip"`
  22. Timestamp int64 `json:"timestamp"`
  23. }
  24. // CheckClientIpJob monitors client IP addresses and manages IP blocking based
  25. // on configured limits. The per-client IPs come from the core's online-stats
  26. // API; no access log is involved. On a core too old to expose that API the job
  27. // simply skips the run (the bundled core always supports it).
  28. type CheckClientIpJob struct {
  29. disAllowedIps []string
  30. xrayService service.XrayService
  31. }
  32. var job *CheckClientIpJob
  33. const defaultXrayAPIPort = 62789
  34. const ipStaleAfterSeconds = int64(30 * 60)
  35. // NewCheckClientIpJob creates a new client IP monitoring job instance.
  36. func NewCheckClientIpJob() *CheckClientIpJob {
  37. job = new(CheckClientIpJob)
  38. return job
  39. }
  40. func (j *CheckClientIpJob) Run() {
  41. observed, apiMode := j.collectFromOnlineAPI()
  42. if !apiMode {
  43. // xray is down or predates the online-stats API. There is no access-log
  44. // fallback anymore, so there is nothing to do this run.
  45. logger.Debug("[LimitIP] online-stats API unavailable this run; skipping")
  46. return
  47. }
  48. if !isFail2BanEnabled() {
  49. return
  50. }
  51. hasLimit := j.hasLimitIp()
  52. f2bInstalled := false
  53. if hasLimit {
  54. f2bInstalled = j.checkFail2BanInstalled()
  55. }
  56. j.processObserved(observed, j.resolveEnforce(hasLimit, f2bInstalled), true)
  57. }
  58. // resolveEnforce decides whether limits can actually be enforced this run.
  59. // Without fail2ban on a platform that needs it the limit can't be applied, so
  60. // enforcement is skipped (the panel resets these limits to 0 on upgrade and
  61. // disables the field, so this is normally a no-op).
  62. func (j *CheckClientIpJob) resolveEnforce(hasLimit, f2bInstalled bool) bool {
  63. if hasLimit && runtime.GOOS != "windows" && !f2bInstalled {
  64. return false
  65. }
  66. return hasLimit
  67. }
  68. // collectFromOnlineAPI builds per-email IP observations (email -> ip ->
  69. // last-seen unix seconds) from the core's online-stats API. ok=false means the
  70. // API is unavailable — xray not running, an older core, or a transient gRPC
  71. // failure — and the caller skips the run (there is no access-log fallback).
  72. func (j *CheckClientIpJob) collectFromOnlineAPI() (map[string]map[string]int64, bool) {
  73. onlineUsers, ok, err := j.xrayService.GetOnlineUsers()
  74. if err != nil {
  75. logger.Debug("[LimitIP] online-stats API unavailable this run:", err)
  76. return nil, false
  77. }
  78. if !ok {
  79. return nil, false
  80. }
  81. now := time.Now().Unix()
  82. observed := make(map[string]map[string]int64, len(onlineUsers))
  83. for _, user := range onlineUsers {
  84. for _, entry := range user.IPs {
  85. // No localhost guard needed here: the core's OnlineMap.AddIP drops
  86. // 127.0.0.1/[::1] itself, so they never reach this list.
  87. ts := entry.LastSeen
  88. if ts <= 0 {
  89. ts = now
  90. }
  91. if _, exists := observed[user.Email]; !exists {
  92. observed[user.Email] = make(map[string]int64)
  93. }
  94. if existing, seen := observed[user.Email][entry.IP]; !seen || ts > existing {
  95. observed[user.Email][entry.IP] = ts
  96. }
  97. }
  98. }
  99. return observed, true
  100. }
  101. // hasLimitIp reports whether any client carries an IP limit. It probes the
  102. // normalized clients table (limit_ip is synced there by SyncInbound and the
  103. // legacy seeder), replacing the old `settings LIKE '%limitIp%'` scan that
  104. // loaded and JSON-parsed every inbound's settings blob on each 10s run.
  105. func (j *CheckClientIpJob) hasLimitIp() bool {
  106. db := database.GetDB()
  107. var probe int64
  108. err := db.Model(&model.ClientRecord{}).Where("limit_ip > 0").Limit(1).Count(&probe).Error
  109. return err == nil && probe > 0
  110. }
  111. // processObserved runs collection + enforcement for one scan's observations
  112. // (email -> ip -> last-seen unix seconds). observedAreLive marks the
  113. // observations as live connections, which bypass the stale cutoff: a connection
  114. // that opened hours ago is still live even though its timestamp is old. The
  115. // online-stats API always reports live connections, so the job passes true.
  116. func (j *CheckClientIpJob) processObserved(observed map[string]map[string]int64, enforce, observedAreLive bool) bool {
  117. shouldCleanLog := false
  118. now := time.Now().Unix()
  119. // attribution accumulates this scan's local observations per email so they can
  120. // be recorded under this panel's own guid for cross-node IP attribution.
  121. attribution := make(map[string][]model.ClientIpEntry, len(observed))
  122. for email, ipTimestamps := range observed {
  123. // The observations can still reference a client that was just renamed
  124. // or deleted; its email no longer matches any inbound. Skip it (and
  125. // drop any orphaned tracking row) instead of recreating a row and
  126. // logging an ERROR every run (#4963).
  127. inbound, err := j.getInboundByEmail(email)
  128. if err != nil {
  129. if errors.Is(err, gorm.ErrRecordNotFound) {
  130. logger.Debugf("[LimitIP] skipping stale observed email %q (renamed or deleted)", email)
  131. j.delInboundClientIps(email)
  132. } else {
  133. j.checkError(err)
  134. }
  135. continue
  136. }
  137. // Convert to IPWithTimestamp slice
  138. ipsWithTime := make([]IPWithTimestamp, 0, len(ipTimestamps))
  139. attrEntries := make([]model.ClientIpEntry, 0, len(ipTimestamps))
  140. for ip, timestamp := range ipTimestamps {
  141. ipsWithTime = append(ipsWithTime, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  142. // Live API observations may carry an old lastSeen (connection start),
  143. // so stamp attribution with now; otherwise the stale cutoff would evict
  144. // an IP that is connected right now.
  145. attrTs := timestamp
  146. if observedAreLive {
  147. attrTs = now
  148. }
  149. attrEntries = append(attrEntries, model.ClientIpEntry{IP: ip, Timestamp: attrTs})
  150. }
  151. if len(attrEntries) > 0 {
  152. attribution[email] = attrEntries
  153. }
  154. clientIpsRecord, err := j.getInboundClientIps(email)
  155. if err != nil {
  156. _ = j.addInboundClientIps(email, ipsWithTime)
  157. continue
  158. }
  159. shouldCleanLog = j.updateInboundClientIps(clientIpsRecord, inbound, email, ipsWithTime, enforce, observedAreLive) || shouldCleanLog
  160. }
  161. j.recordLocalAttribution(attribution)
  162. return shouldCleanLog
  163. }
  164. // recordLocalAttribution stores this scan's local observations under this panel's
  165. // own guid so a parent panel can attribute each IP to the node it is on.
  166. // Best-effort: attribution is advisory and must never block IP-limit enforcement.
  167. func (j *CheckClientIpJob) recordLocalAttribution(attribution map[string][]model.ClientIpEntry) {
  168. if len(attribution) == 0 {
  169. return
  170. }
  171. guid, err := (&service.SettingService{}).GetPanelGuid()
  172. if err != nil || guid == "" {
  173. return
  174. }
  175. if err := (&service.InboundService{}).RecordLocalClientIps(guid, attribution); err != nil {
  176. logger.Debug("[LimitIP] record local ip attribution failed:", err)
  177. }
  178. }
  179. // mergeClientIps folds this scan's observations into the persisted set,
  180. // dropping entries older than staleCutoff. newAlwaysLive exempts the new
  181. // entries from that cutoff: an API-observed IP is a live connection by
  182. // definition, even when its lastSeen (set at dispatch time) is hours old.
  183. func mergeClientIps(old, new []IPWithTimestamp, staleCutoff int64, newAlwaysLive bool) map[string]int64 {
  184. ipMap := make(map[string]int64, len(old)+len(new))
  185. for _, ipTime := range old {
  186. if ipTime.Timestamp < staleCutoff {
  187. continue
  188. }
  189. ipMap[ipTime.IP] = ipTime.Timestamp
  190. }
  191. for _, ipTime := range new {
  192. if !newAlwaysLive && ipTime.Timestamp < staleCutoff {
  193. continue
  194. }
  195. if existingTime, ok := ipMap[ipTime.IP]; !ok || ipTime.Timestamp > existingTime {
  196. ipMap[ipTime.IP] = ipTime.Timestamp
  197. }
  198. }
  199. return ipMap
  200. }
  201. // selectIpsToBan splits the live IPs (sorted oldest-first by partitionLiveIps)
  202. // into the newest `limit` entries to keep and the older remainder to ban.
  203. func selectIpsToBan(live []IPWithTimestamp, limit int) (kept, banned []IPWithTimestamp) {
  204. if limit <= 0 || len(live) <= limit {
  205. return live, nil
  206. }
  207. cutoff := len(live) - limit
  208. return live[cutoff:], live[:cutoff]
  209. }
  210. func partitionLiveIps(ipMap map[string]int64, observedThisScan map[string]bool) (live, historical []IPWithTimestamp) {
  211. live = make([]IPWithTimestamp, 0, len(observedThisScan))
  212. historical = make([]IPWithTimestamp, 0, len(ipMap))
  213. now := time.Now().Unix()
  214. for ip, ts := range ipMap {
  215. entry := IPWithTimestamp{IP: ip, Timestamp: ts}
  216. // Consider an IP "live" if it was seen locally in this scan, OR if its
  217. // timestamp from the synced database is very recent (e.g. within 2 minutes).
  218. // This ensures cluster-wide limits work even if the IP was seen on another node.
  219. if observedThisScan[ip] || now-ts < 120 {
  220. live = append(live, entry)
  221. } else {
  222. historical = append(historical, entry)
  223. }
  224. }
  225. sort.Slice(live, func(i, j int) bool { return live[i].Timestamp < live[j].Timestamp })
  226. sort.Slice(historical, func(i, j int) bool { return historical[i].Timestamp < historical[j].Timestamp })
  227. return live, historical
  228. }
  229. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  230. if !isFail2BanEnabled() {
  231. return false
  232. }
  233. cmd := "fail2ban-client"
  234. args := []string{"-h"}
  235. err := exec.CommandContext(context.Background(), cmd, args...).Run()
  236. return err == nil
  237. }
  238. func isFail2BanEnabled() bool {
  239. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  240. return !ok || value == "true"
  241. }
  242. func (j *CheckClientIpJob) checkError(e error) {
  243. if e != nil {
  244. logger.Warning("client ip job err:", e)
  245. }
  246. }
  247. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  248. db := database.GetDB()
  249. InboundClientIps := &model.InboundClientIps{}
  250. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  251. if err != nil {
  252. return nil, err
  253. }
  254. return InboundClientIps, nil
  255. }
  256. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  257. inboundClientIps := &model.InboundClientIps{}
  258. jsonIps, err := json.Marshal(ipsWithTime)
  259. j.checkError(err)
  260. inboundClientIps.ClientEmail = clientEmail
  261. inboundClientIps.Ips = string(jsonIps)
  262. db := database.GetDB()
  263. tx := db.Begin()
  264. defer func() {
  265. if err == nil {
  266. tx.Commit()
  267. } else {
  268. tx.Rollback()
  269. }
  270. }()
  271. err = tx.Save(inboundClientIps).Error
  272. if err != nil {
  273. return err
  274. }
  275. return nil
  276. }
  277. // delInboundClientIps drops the inbound_client_ips tracking row for an email
  278. // that no longer maps to any inbound (a renamed or deleted client), so stale
  279. // access-log entries don't keep a ghost row alive (#4963).
  280. func (j *CheckClientIpJob) delInboundClientIps(clientEmail string) {
  281. db := database.GetDB()
  282. if err := db.Where("client_email = ?", clientEmail).Delete(&model.InboundClientIps{}).Error; err != nil {
  283. j.checkError(err)
  284. }
  285. }
  286. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, inbound *model.Inbound, clientEmail string, newIpsWithTime []IPWithTimestamp, enforce, observedAreLive bool) bool {
  287. if inbound.Settings == "" {
  288. logger.Debug("wrong data:", inbound)
  289. return false
  290. }
  291. settings := map[string][]model.Client{}
  292. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  293. clients := settings["clients"]
  294. // Find the client's IP limit
  295. var limitIp int
  296. var clientFound bool
  297. for _, client := range clients {
  298. if client.Email == clientEmail {
  299. limitIp = client.LimitIP
  300. clientFound = true
  301. break
  302. }
  303. }
  304. if !enforce || !clientFound || limitIp <= 0 || !inbound.Enable {
  305. // Nothing to enforce (collection-only run, no limit, client missing, or
  306. // inbound disabled): record the observed IPs for the panel and return.
  307. jsonIps, _ := json.Marshal(newIpsWithTime)
  308. inboundClientIps.Ips = string(jsonIps)
  309. db := database.GetDB()
  310. db.Save(inboundClientIps)
  311. return false
  312. }
  313. // Parse old IPs from database
  314. var oldIpsWithTime []IPWithTimestamp
  315. if inboundClientIps.Ips != "" {
  316. _ = json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  317. }
  318. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds, observedAreLive)
  319. // only ips seen in this scan count toward the limit. see
  320. // partitionLiveIps.
  321. observedThisScan := make(map[string]bool, len(newIpsWithTime))
  322. for _, ipTime := range newIpsWithTime {
  323. observedThisScan[ipTime.IP] = true
  324. }
  325. liveIps, historicalIps := partitionLiveIps(ipMap, observedThisScan)
  326. shouldCleanLog := false
  327. j.disAllowedIps = []string{}
  328. // historical db-only ips are excluded from this count on purpose.
  329. keptLive, bannedLive := selectIpsToBan(liveIps, limitIp)
  330. if len(bannedLive) > 0 {
  331. shouldCleanLog = true
  332. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  333. if err != nil {
  334. logger.Errorf("failed to open IP limit log file: %s", err)
  335. return false
  336. }
  337. defer logIpFile.Close()
  338. ipLogger := log.New(logIpFile, "", log.LstdFlags)
  339. // log format is load-bearing: x-ui.sh create_iplimit_jails builds
  340. // filter.d/3x-ipl.conf with
  341. // failregex = \[LIMIT_IP\]\s*Email\s*=\s*<F-USER>.+</F-USER>\s*\|\|\s*Disconnecting OLD IP\s*=\s*<ADDR>\s*\|\|\s*Timestamp\s*=\s*\d+
  342. // don't change the wording.
  343. for _, ipTime := range bannedLive {
  344. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  345. ipLogger.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  346. }
  347. // force xray to drop existing connections from banned ips
  348. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  349. }
  350. // keep kept-live + historical in the blob so the panel keeps showing
  351. // recently seen ips. banned live ips are already in the fail2ban log
  352. // and will reappear in the next scan if they reconnect.
  353. dbIps := make([]IPWithTimestamp, 0, len(keptLive)+len(historicalIps))
  354. dbIps = append(dbIps, keptLive...)
  355. dbIps = append(dbIps, historicalIps...)
  356. jsonIps, _ := json.Marshal(dbIps)
  357. inboundClientIps.Ips = string(jsonIps)
  358. db := database.GetDB()
  359. err := db.Save(inboundClientIps).Error
  360. if err != nil {
  361. logger.Error("failed to save inboundClientIps:", err)
  362. return false
  363. }
  364. if len(j.disAllowedIps) > 0 {
  365. logger.Infof("[LIMIT_IP] Client %s: Kept %d live IPs, queued %d old IPs for fail2ban", clientEmail, len(keptLive), len(j.disAllowedIps))
  366. }
  367. return shouldCleanLog
  368. }
  369. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  370. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  371. var xrayAPI xray.XrayAPI
  372. apiPort := j.resolveXrayAPIPort()
  373. err := xrayAPI.Init(apiPort)
  374. if err != nil {
  375. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  376. return
  377. }
  378. defer xrayAPI.Close()
  379. // Find the client config
  380. var clientConfig map[string]any
  381. for _, client := range clients {
  382. if client.Email == clientEmail {
  383. // Convert client to map for API
  384. clientBytes, _ := json.Marshal(client)
  385. _ = json.Unmarshal(clientBytes, &clientConfig)
  386. break
  387. }
  388. }
  389. if clientConfig == nil {
  390. return
  391. }
  392. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  393. protocol := string(inbound.Protocol)
  394. switch protocol {
  395. case "vmess", "vless", "trojan", "shadowsocks":
  396. // supported protocols, continue
  397. default:
  398. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  399. return
  400. }
  401. // For Shadowsocks, ensure the required "cipher" field is present by
  402. // reading it from the inbound settings (e.g., settings["method"]).
  403. if string(inbound.Protocol) == "shadowsocks" {
  404. var inboundSettings map[string]any
  405. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  406. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  407. } else {
  408. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  409. clientConfig["cipher"] = method
  410. }
  411. }
  412. }
  413. // Remove user to disconnect all connections
  414. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  415. if err != nil {
  416. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  417. return
  418. }
  419. // Wait a moment for disconnection to take effect
  420. time.Sleep(100 * time.Millisecond)
  421. // Re-add user to allow new connections
  422. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  423. if err != nil {
  424. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  425. }
  426. }
  427. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  428. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  429. var configErr error
  430. var templateErr error
  431. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  432. return port
  433. } else {
  434. configErr = err
  435. }
  436. db := database.GetDB()
  437. var template model.Setting
  438. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  439. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  440. return port
  441. } else {
  442. templateErr = parseErr
  443. }
  444. } else {
  445. templateErr = err
  446. }
  447. logger.Warningf(
  448. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  449. defaultXrayAPIPort,
  450. configErr,
  451. templateErr,
  452. )
  453. return defaultXrayAPIPort
  454. }
  455. func getAPIPortFromConfigPath(configPath string) (int, error) {
  456. configData, err := os.ReadFile(configPath)
  457. if err != nil {
  458. return 0, err
  459. }
  460. return getAPIPortFromConfigData(configData)
  461. }
  462. func getAPIPortFromConfigData(configData []byte) (int, error) {
  463. xrayConfig := &xray.Config{}
  464. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  465. return 0, err
  466. }
  467. for _, inboundConfig := range xrayConfig.InboundConfigs {
  468. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  469. return inboundConfig.Port, nil
  470. }
  471. }
  472. return 0, errors.New("api inbound port not found")
  473. }
  474. // getInboundByEmail resolves the inbound that owns a client email. It prefers
  475. // the exact clients/client_inbounds relation; a substring "settings LIKE
  476. // %email%" can match the wrong inbound (an email that is a substring of another,
  477. // or text that merely appears elsewhere in the settings JSON). The LIKE + JSON
  478. // scan stays only as a fallback for clients not yet present in the relation, so
  479. // nothing regresses when the join finds no row.
  480. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  481. db := database.GetDB()
  482. inbound := &model.Inbound{}
  483. err := db.Model(&model.Inbound{}).
  484. Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id").
  485. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  486. Where("clients.email = ?", clientEmail).
  487. First(inbound).Error
  488. if err == nil {
  489. return inbound, nil
  490. }
  491. var candidates []model.Inbound
  492. if listErr := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&candidates).Error; listErr != nil {
  493. return nil, listErr
  494. }
  495. for i := range candidates {
  496. settings := map[string][]model.Client{}
  497. if jsonErr := json.Unmarshal([]byte(candidates[i].Settings), &settings); jsonErr != nil {
  498. continue
  499. }
  500. for _, client := range settings["clients"] {
  501. if client.Email == clientEmail {
  502. return &candidates[i], nil
  503. }
  504. }
  505. }
  506. return nil, err
  507. }