Auth.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { createContext, useEffect, useState } from 'react';
  2. import { AuthContextType } from './Types';
  3. import { MilvusService } from '@/http';
  4. import { AuthReq } from '@server/types';
  5. import {
  6. MILVUS_CLIENT_ID,
  7. MILVUS_URL,
  8. MILVUS_DATABASE,
  9. ATTU_AUTH_REQ,
  10. } from '@/consts';
  11. export const authContext = createContext<AuthContextType>({
  12. clientId: '',
  13. authReq: {
  14. username: '',
  15. password: '',
  16. address: '',
  17. token: '',
  18. database: '',
  19. },
  20. setAuthReq: () => {},
  21. isManaged: false,
  22. isAuth: false,
  23. login: async () => {
  24. return { clientId: '', database: '' };
  25. },
  26. logout: () => {},
  27. });
  28. const { Provider } = authContext;
  29. export const AuthProvider = (props: { children: React.ReactNode }) => {
  30. // get data from local storage
  31. const localAuthReq = JSON.parse(
  32. window.localStorage.getItem(ATTU_AUTH_REQ) ||
  33. JSON.stringify({
  34. username: '',
  35. password: '',
  36. address: MILVUS_URL,
  37. token: '',
  38. database: MILVUS_DATABASE,
  39. })
  40. );
  41. // state
  42. const [authReq, setAuthReq] = useState<AuthReq>(localAuthReq);
  43. const [clientId, setClientId] = useState<string>(
  44. window.localStorage.getItem(MILVUS_CLIENT_ID) || ''
  45. );
  46. // update title when address changes
  47. useEffect(() => {
  48. document.title = authReq.address ? `${authReq.address} - Attu` : 'Attu';
  49. return () => {
  50. document.title = 'Attu';
  51. };
  52. }, [authReq.address]);
  53. // update local storage when authReq changes
  54. useEffect(() => {
  55. // store auth request in local storage
  56. window.localStorage.setItem(
  57. ATTU_AUTH_REQ,
  58. JSON.stringify({ ...authReq, password: '', token: '' })
  59. );
  60. }, [authReq]);
  61. // login API
  62. const login = async (params: AuthReq) => {
  63. // connect to Milvus
  64. const res = await MilvusService.connect(params);
  65. // update auth request
  66. setAuthReq({ ...params, database: res.database, password: '', token: '' });
  67. setClientId(res.clientId);
  68. return res;
  69. };
  70. // logout API
  71. const logout = () => {
  72. // clear client id
  73. setClientId('');
  74. // remove client id from local storage
  75. window.localStorage.removeItem(MILVUS_CLIENT_ID);
  76. };
  77. return (
  78. <Provider
  79. value={{
  80. authReq,
  81. setAuthReq,
  82. login,
  83. logout,
  84. clientId,
  85. isAuth: !!clientId,
  86. isManaged: authReq.address.includes('zilliz'),
  87. }}
  88. >
  89. {props.children}
  90. </Provider>
  91. );
  92. };