api.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import axios from 'axios'
  2. const defaultBaseUrl = `${window.location.protocol}//${window.location.hostname}:8000`
  3. const tokenKey = 'automation_remote_token'
  4. const unlockedKey = 'automation_auth_unlocked'
  5. export const api = axios.create({
  6. baseURL: import.meta.env.VITE_API_BASE || defaultBaseUrl,
  7. timeout: 120000,
  8. })
  9. api.interceptors.request.use((config) => {
  10. const token = automationToken()
  11. if (token) {
  12. config.headers = config.headers || {}
  13. config.headers['X-Automation-Token'] = token
  14. }
  15. return config
  16. })
  17. api.interceptors.response.use(
  18. (response) => response,
  19. (error) => {
  20. if ([401, 403].includes(error.response?.status)) {
  21. clearAutomationAuth()
  22. window.dispatchEvent(new CustomEvent('automation-auth-required'))
  23. }
  24. return Promise.reject(error)
  25. },
  26. )
  27. export function automationToken() {
  28. return window.localStorage.getItem(tokenKey) || ''
  29. }
  30. export function setAutomationToken(token) {
  31. const value = String(token || '').trim()
  32. if (value) {
  33. window.localStorage.setItem(tokenKey, value)
  34. } else {
  35. window.localStorage.removeItem(tokenKey)
  36. }
  37. window.localStorage.setItem(unlockedKey, '1')
  38. }
  39. export function clearAutomationAuth() {
  40. window.localStorage.removeItem(tokenKey)
  41. window.localStorage.removeItem(unlockedKey)
  42. }
  43. export function hasAutomationAuth() {
  44. return window.localStorage.getItem(unlockedKey) === '1' || Boolean(automationToken())
  45. }
  46. export const statusOptions = [
  47. { label: '待确认', value: 'PENDING', type: 'warning' },
  48. { label: '可信', value: 'TRUSTED', type: 'success' },
  49. { label: '可疑', value: 'SUSPICIOUS', type: 'danger' },
  50. { label: '忽略', value: 'IGNORED', type: 'info' },
  51. { label: '信息不足', value: 'NEED_MORE_INFO', type: 'primary' },
  52. ]
  53. export function statusMeta(value) {
  54. return statusOptions.find((item) => item.value === value) || statusOptions[0]
  55. }