diff --git a/src/app/services/base.query.js b/src/app/services/base.query.js index 3b09165e..f28b0a95 100644 --- a/src/app/services/base.query.js +++ b/src/app/services/base.query.js @@ -1,106 +1,100 @@ -import { fetchBaseQuery } from "@reduxjs/toolkit/query"; -import toast from "react-hot-toast"; -import dayjs from "dayjs"; -import { updateToken, resetAuthData } from "../slices/auth.data"; -import BASE_URL, { tokenHeader } from "../config"; +import { fetchBaseQuery } from '@reduxjs/toolkit/query'; +import toast from 'react-hot-toast'; +import dayjs from 'dayjs'; +import { updateToken, resetAuthData } from '../slices/auth.data'; +import BASE_URL, { tokenHeader } from '../config'; const whiteList = [ - "login", - "register", - "checkInviteTokenValid", - "getServer", - "getOpenid", - "getMetamaskNonce", - "renew", + 'login', + 'register', + 'checkInviteTokenValid', + 'getLoginConfig', + 'getServer', + 'getOpenid', + 'getMetamaskNonce', + 'renew' ]; const baseQuery = fetchBaseQuery({ - baseUrl: BASE_URL, - prepareHeaders: (headers, { getState, endpoint }) => { - console.log("req", endpoint); - const { token } = getState().authData; - if (token && !whiteList.includes(endpoint)) { - headers.set(tokenHeader, token); - } - return headers; - }, + baseUrl: BASE_URL, + prepareHeaders: (headers, { getState, endpoint }) => { + console.log('req', endpoint); + const { token } = getState().authData; + if (token && !whiteList.includes(endpoint)) { + headers.set(tokenHeader, token); + } + return headers; + } }); let waitingForRenew = null; const baseQueryWithTokenCheck = async (args, api, extraOptions) => { - if (waitingForRenew) { - await waitingForRenew; - } - // 先检查token是否过期,过期则renew - const { - token, - refreshToken, - expireTime = new Date().getTime(), - } = api.getState().authData; - let result = null; - if ( - !whiteList.includes(api.endpoint) && - dayjs().isAfter(new Date(expireTime - 20 * 1000)) - ) { - // 快过期了,renew - waitingForRenew = baseQuery( - { - url: "/token/renew", - method: "POST", - body: { - token, - refresh_token: refreshToken, - }, - }, - api, - extraOptions - ); - result = await waitingForRenew; - waitingForRenew = null; - if (result.data) { - // store the new token - api.dispatch(updateToken(result.data)); - // retry the initial query - result = await baseQuery(args, api, extraOptions); + if (waitingForRenew) { + await waitingForRenew; + } + // 先检查token是否过期,过期则renew + const { token, refreshToken, expireTime = new Date().getTime() } = api.getState().authData; + let result = null; + if (!whiteList.includes(api.endpoint) && dayjs().isAfter(new Date(expireTime - 20 * 1000))) { + // 快过期了,renew + waitingForRenew = baseQuery( + { + url: '/token/renew', + method: 'POST', + body: { + token, + refresh_token: refreshToken } - } else { - result = await baseQuery(args, api, extraOptions); + }, + api, + extraOptions + ); + result = await waitingForRenew; + waitingForRenew = null; + if (result.data) { + // store the new token + api.dispatch(updateToken(result.data)); + // retry the initial query + result = await baseQuery(args, api, extraOptions); } - if (result?.error) { - console.log("api error", result.error, api.endpoint); - switch (result.error.originalStatus || result.error.status) { - case "FETCH_ERROR": - { - toast.error(`${api.endpoint}: Failed to fetch`); - } - break; - case 404: - { - toast.error("Request Not Found"); - } - break; - case 500: - { - toast.error(result.error.data || "server error"); - } - break; - case 401: - { - // if (api.endpoint === "renew") { - // toast.error("token expired, please login again"); - api.dispatch(resetAuthData()); - location.href = "/#/login"; - // } else { - toast.error("API Not Authenticated"); - // return; - // } - } - break; - case 403: - toast.error("Request Not Allowed"); - break; - default: - break; + } else { + result = await baseQuery(args, api, extraOptions); + } + if (result?.error) { + console.log('api error', result.error, api.endpoint); + switch (result.error.originalStatus || result.error.status) { + case 'FETCH_ERROR': + { + toast.error(`${api.endpoint}: Failed to fetch`); } + break; + case 404: + { + toast.error('Request Not Found'); + } + break; + case 500: + { + toast.error(result.error.data || 'server error'); + } + break; + case 401: + { + // if (api.endpoint === "renew") { + // toast.error("token expired, please login again"); + api.dispatch(resetAuthData()); + location.href = '/#/login'; + // } else { + toast.error('API Not Authenticated'); + // return; + // } + } + break; + case 403: + toast.error('Request Not Allowed'); + break; + default: + break; } - return result; + } + return result; }; export default baseQueryWithTokenCheck; diff --git a/src/app/services/server.js b/src/app/services/server.js index 070476d8..ced50103 100644 --- a/src/app/services/server.js +++ b/src/app/services/server.js @@ -1,147 +1,156 @@ -import { createApi } from "@reduxjs/toolkit/query/react"; -import BASE_URL from "../config"; -import { updateInviteLink, updateInfo } from "../slices/server"; -import baseQuery from "./base.query"; +import { createApi } from '@reduxjs/toolkit/query/react'; +import BASE_URL from '../config'; +import { updateInviteLink, updateInfo } from '../slices/server'; +import baseQuery from './base.query'; const defaultExpireDuration = 7 * 24 * 60 * 60; export const serverApi = createApi({ - reducerPath: "serverApi", - baseQuery, - endpoints: (builder) => ({ - getServer: builder.query({ - query: () => ({ url: `admin/system/organization` }), - transformResponse: (data) => { - data.logo = `${BASE_URL}/resource/organization/logo?t=${new Date().getTime()}`; - return data; - }, - async onQueryStarted(data, { dispatch, queryFulfilled }) { - try { - const { data: server } = await queryFulfilled; - dispatch(updateInfo(server)); - } catch { - console.log("get server info error"); - } - }, - }), - getMetrics: builder.query({ - query: () => ({ url: `/admin/system/metrics` }), - }), - getFirebaseConfig: builder.query({ - query: () => ({ url: `admin/fcm/config` }), - }), - sendTestEmail: builder.mutation({ - query: (data) => ({ - url: `/admin/system/send_mail`, - method: "POST", - body: data, - }), - }), - updateFirebaseConfig: builder.mutation({ - query: (data) => ({ - url: `admin/fcm/config`, - method: "POST", - body: data, - }), - }), - getAgoraConfig: builder.query({ - query: () => ({ url: `admin/agora/config` }), - }), - updateAgoraConfig: builder.mutation({ - query: (data) => ({ - url: `admin/agora/config`, - method: "POST", - body: data, - }), - }), - getSMTPConfig: builder.query({ - query: () => ({ url: `admin/smtp/config` }), - }), - updateSMTPConfig: builder.mutation({ - query: (data) => ({ - url: `admin/smtp/config`, - method: "POST", - body: data, - }), - }), - updateLogo: builder.mutation({ - query: (data) => ({ - headers: { - "content-type": "image/png", - }, - url: `admin/system/organization/logo`, - method: "POST", - body: data, - }), - async onQueryStarted(data, { dispatch, queryFulfilled }) { - try { - await queryFulfilled; - dispatch( - updateInfo({ - logo: `${BASE_URL}/resource/organization/logo?t=${new Date().getTime()}`, - }) - ); - } catch { - console.log("update server logo error"); - } - }, - }), - createInviteLink: builder.query({ - query: (expired_in = defaultExpireDuration) => ({ - headers: { - "content-type": "text/plain", - accept: "text/plain", - }, - url: `/admin/user/create_invite_link?expired_in=${expired_in}`, - responseHandler: (response) => response.text(), - }), - transformResponse: (link) => { - // 替换掉域名 - const invite = new URL(link); - return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`; - }, - async onQueryStarted( - expire = defaultExpireDuration, - { dispatch, queryFulfilled } - ) { - try { - const { data: link } = await queryFulfilled; - console.log("link", link); - dispatch(updateInviteLink({ expire, link })); - } catch { - console.log("invite link error"); - } - }, - }), - updateServer: builder.mutation({ - query: (data) => ({ - url: `admin/system/organization`, - method: "POST", - body: data, - }), - async onQueryStarted(data, { dispatch, queryFulfilled, getState }) { - const { name: prevName, description: prevDesc } = getState().server; - dispatch(updateInfo(data)); - try { - await queryFulfilled; - } catch { - dispatch(updateInfo({ name: prevName, description: prevDesc })); - } - }, - }), + reducerPath: 'serverApi', + baseQuery, + endpoints: (builder) => ({ + getServer: builder.query({ + query: () => ({ url: `admin/system/organization` }), + transformResponse: (data) => { + data.logo = `${BASE_URL}/resource/organization/logo?t=${new Date().getTime()}`; + return data; + }, + async onQueryStarted(data, { dispatch, queryFulfilled }) { + try { + const { data: server } = await queryFulfilled; + dispatch(updateInfo(server)); + } catch { + console.log('get server info error'); + } + } }), + getMetrics: builder.query({ + query: () => ({ url: `/admin/system/metrics` }) + }), + getFirebaseConfig: builder.query({ + query: () => ({ url: `admin/fcm/config` }) + }), + sendTestEmail: builder.mutation({ + query: (data) => ({ + url: `/admin/system/send_mail`, + method: 'POST', + body: data + }) + }), + updateFirebaseConfig: builder.mutation({ + query: (data) => ({ + url: `admin/fcm/config`, + method: 'POST', + body: data + }) + }), + getAgoraConfig: builder.query({ + query: () => ({ url: `admin/agora/config` }) + }), + updateAgoraConfig: builder.mutation({ + query: (data) => ({ + url: `admin/agora/config`, + method: 'POST', + body: data + }) + }), + getSMTPConfig: builder.query({ + query: () => ({ url: `admin/smtp/config` }) + }), + updateSMTPConfig: builder.mutation({ + query: (data) => ({ + url: `admin/smtp/config`, + method: 'POST', + body: data + }) + }), + getLoginConfig: builder.query({ + query: () => ({ url: `admin/login/config` }) + }), + updateLoginConfig: builder.mutation({ + query: (data) => ({ + url: `admin/login/config`, + method: 'POST', + body: data + }) + }), + updateLogo: builder.mutation({ + query: (data) => ({ + headers: { + 'content-type': 'image/png' + }, + url: `admin/system/organization/logo`, + method: 'POST', + body: data + }), + async onQueryStarted(data, { dispatch, queryFulfilled }) { + try { + await queryFulfilled; + dispatch( + updateInfo({ + logo: `${BASE_URL}/resource/organization/logo?t=${new Date().getTime()}` + }) + ); + } catch { + console.log('update server logo error'); + } + } + }), + createInviteLink: builder.query({ + query: (expired_in = defaultExpireDuration) => ({ + headers: { + 'content-type': 'text/plain', + accept: 'text/plain' + }, + url: `/admin/user/create_invite_link?expired_in=${expired_in}`, + responseHandler: (response) => response.text() + }), + transformResponse: (link) => { + // 替换掉域名 + const invite = new URL(link); + return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`; + }, + async onQueryStarted(expire = defaultExpireDuration, { dispatch, queryFulfilled }) { + try { + const { data: link } = await queryFulfilled; + console.log('link', link); + dispatch(updateInviteLink({ expire, link })); + } catch { + console.log('invite link error'); + } + } + }), + updateServer: builder.mutation({ + query: (data) => ({ + url: `admin/system/organization`, + method: 'POST', + body: data + }), + async onQueryStarted(data, { dispatch, queryFulfilled, getState }) { + const { name: prevName, description: prevDesc } = getState().server; + dispatch(updateInfo(data)); + try { + await queryFulfilled; + } catch { + dispatch(updateInfo({ name: prevName, description: prevDesc })); + } + } + }) + }) }); export const { - useSendTestEmailMutation, - useUpdateFirebaseConfigMutation, - useGetFirebaseConfigQuery, - useGetSMTPConfigQuery, - useUpdateSMTPConfigMutation, - useGetAgoraConfigQuery, - useUpdateAgoraConfigMutation, - useGetServerQuery, - useLazyGetMetricsQuery, - useLazyGetServerQuery, - useUpdateServerMutation, - useUpdateLogoMutation, - useLazyCreateInviteLinkQuery, + useSendTestEmailMutation, + useUpdateFirebaseConfigMutation, + useGetFirebaseConfigQuery, + useGetLoginConfigQuery, + useUpdateLoginConfigMutation, + useGetSMTPConfigQuery, + useUpdateSMTPConfigMutation, + useGetAgoraConfigQuery, + useUpdateAgoraConfigMutation, + useGetServerQuery, + useLazyGetMetricsQuery, + useLazyGetServerQuery, + useUpdateServerMutation, + useUpdateLogoMutation, + useLazyCreateInviteLinkQuery } = serverApi; diff --git a/src/common/component/Setting/config/Logins.js b/src/common/component/Setting/config/Logins.js new file mode 100644 index 00000000..2e96cfcb --- /dev/null +++ b/src/common/component/Setting/config/Logins.js @@ -0,0 +1,115 @@ +// import { useState, useEffect } from "react"; +import StyledContainer from './StyledContainer'; +// import Input from "../../styled/Input"; +import Textarea from '../../styled/Textarea'; +import Toggle from '../../styled/Toggle'; +import Label from '../../styled/Label'; +import SaveTip from '../../SaveTip'; +import useConfig from './useConfig'; + +export default function Logins() { + const { values, updateConfig, setValues, reset, changed } = useConfig('login'); + const handleUpdate = () => { + // const { token_url, description } = values; + updateConfig(values); + }; + const handleChange = (evt) => { + const newValue = evt.target.value; + const { type } = evt.target.dataset; + const items = newValue ? newValue.split('\n') : []; + setValues((prev) => { + return { ...prev, [type]: items }; + }); + }; + const handleToggle = (val) => { + setValues((prev) => { + return { ...prev, ...val }; + }); + }; + if (!values) return null; + const { google, metamask, password, oidc = [] } = values ?? {}; + return ( + + + + Password + + + + Google + + + + Metamask + + + + OIDC + + + + {/* + Token Url + + + + Project ID + + + + Private Key + + + + Client Email + + */} + + {changed && } + {/* update */} + + ); +} diff --git a/src/common/component/Setting/config/useConfig.js b/src/common/component/Setting/config/useConfig.js index 1dae412e..a7e3da26 100644 --- a/src/common/component/Setting/config/useConfig.js +++ b/src/common/component/Setting/config/useConfig.js @@ -1,96 +1,92 @@ -import { useEffect, useState } from "react"; -import { isObjectEqual } from "../../../utils"; -import toast from "react-hot-toast"; +import { useEffect, useState } from 'react'; +import { isObjectEqual } from '../../../utils'; +import toast from 'react-hot-toast'; import { - useGetAgoraConfigQuery, - useGetFirebaseConfigQuery, - useGetSMTPConfigQuery, - useUpdateSMTPConfigMutation, - useUpdateAgoraConfigMutation, - useUpdateFirebaseConfigMutation, -} from "../../../../app/services/server"; -export default function useConfig(config = "smtp") { - const [changed, setChanged] = useState(false); - const [values, setValues] = useState({}); - const { data: SMTP, refetch: refetchSMTP } = useGetSMTPConfigQuery(); - const [ - updateSMTPConfig, - { isSuccess: SMTPUpdated }, - ] = useUpdateSMTPConfigMutation(); - const { data: Agora, refetch: refetchAgora } = useGetAgoraConfigQuery(); - const [ - updateAgoraConfig, - { isSuccess: AgoraUpdated }, - ] = useUpdateAgoraConfigMutation(); - const { - data: Firebase, - refetch: refetchFirebase, - } = useGetFirebaseConfigQuery(); - const [ - updateFirebaseConfig, - { isSuccess: FirebaseUpdated }, - ] = useUpdateFirebaseConfigMutation(); + useGetAgoraConfigQuery, + useGetFirebaseConfigQuery, + useGetSMTPConfigQuery, + useGetLoginConfigQuery, + useUpdateLoginConfigMutation, + useUpdateSMTPConfigMutation, + useUpdateAgoraConfigMutation, + useUpdateFirebaseConfigMutation +} from '../../../../app/services/server'; +export default function useConfig(config = 'smtp') { + const [changed, setChanged] = useState(false); + const [values, setValues] = useState({}); + const { data: Login, refetch: refetchLogin } = useGetLoginConfigQuery(); + const [updateLoginConfig, { isSuccess: LoginUpdated }] = useUpdateLoginConfigMutation(); + const { data: SMTP, refetch: refetchSMTP } = useGetSMTPConfigQuery(); + const [updateSMTPConfig, { isSuccess: SMTPUpdated }] = useUpdateSMTPConfigMutation(); + const { data: Agora, refetch: refetchAgora } = useGetAgoraConfigQuery(); + const [updateAgoraConfig, { isSuccess: AgoraUpdated }] = useUpdateAgoraConfigMutation(); + const { data: Firebase, refetch: refetchFirebase } = useGetFirebaseConfigQuery(); + const [updateFirebaseConfig, { isSuccess: FirebaseUpdated }] = useUpdateFirebaseConfigMutation(); - const datas = { - smtp: SMTP, - agora: Agora, - firebase: Firebase, - }; - const updateFns = { - smtp: updateSMTPConfig, - agora: updateAgoraConfig, - firebase: updateFirebaseConfig, - }; - const refetchs = { - smtp: refetchSMTP, - agora: refetchAgora, - firebase: refetchFirebase, - }; - const updateds = { - smtp: SMTPUpdated, - agora: AgoraUpdated, - firebase: FirebaseUpdated, - }; - const data = datas[config]; - const updateConfig = updateFns[config]; - const refetch = refetchs[config]; - const updated = updateds[config]; - const reset = () => { - setValues(data ?? {}); - }; + const datas = { + login: Login, + smtp: SMTP, + agora: Agora, + firebase: Firebase + }; + const updateFns = { + login: updateLoginConfig, + smtp: updateSMTPConfig, + agora: updateAgoraConfig, + firebase: updateFirebaseConfig + }; + const refetchs = { + smtp: refetchSMTP, + agora: refetchAgora, + firebase: refetchFirebase, + login: refetchLogin + }; + const updateds = { + login: LoginUpdated, + smtp: SMTPUpdated, + agora: AgoraUpdated, + firebase: FirebaseUpdated + }; + const data = datas[config]; + const updateConfig = updateFns[config]; + const refetch = refetchs[config]; + const updated = updateds[config]; + const reset = () => { + setValues(data ?? {}); + }; - const toggleEnable = () => { - setValues((prev) => { - return { ...prev, enabled: !prev.enabled }; - }); - }; - useEffect(() => { - if (updated) { - toast.success("Configuration Updated!"); - refetch(); - } - }, [updated]); - useEffect(() => { - console.log("wtf", data); - // if (data) { - setValues(data ?? {}); - // } - }, [data]); - useEffect(() => { - // if (data && values) { - if (!isObjectEqual(data, values)) { - setChanged(true); - } else { - setChanged(false); - } - // } - }, [data, values]); - return { - reset, - changed, - updateConfig, - values, - setValues, - toggleEnable, - }; + const toggleEnable = () => { + setValues((prev) => { + return { ...prev, enabled: !prev.enabled }; + }); + }; + useEffect(() => { + if (updated) { + toast.success('Configuration Updated!'); + refetch(); + } + }, [updated]); + useEffect(() => { + console.log('wtf', data); + // if (data) { + setValues(data ?? {}); + // } + }, [data]); + useEffect(() => { + // if (data && values) { + if (!isObjectEqual(data, values)) { + setChanged(true); + } else { + setChanged(false); + } + // } + }, [data, values]); + return { + reset, + changed, + updateConfig, + values, + setValues, + toggleEnable + }; } diff --git a/src/common/component/Setting/navs.js b/src/common/component/Setting/navs.js index e41dc7c7..6126f89e 100644 --- a/src/common/component/Setting/navs.js +++ b/src/common/component/Setting/navs.js @@ -1,98 +1,104 @@ -import { useSelector } from "react-redux"; -import MyAccount from "./MyAccount"; -import Overview from "./Overview"; -import ConfigFirebase from "./config/Firebase"; -import ConfigSMTP from "./config/SMTP"; -import Notifications from "./Notifications"; -import ManageMembers from "../ManageMembers"; -import FAQ from "../FAQ"; -import ConfigAgora from "./config/Agora"; +import { useSelector } from 'react-redux'; +import MyAccount from './MyAccount'; +import Overview from './Overview'; +import Logins from './config/Logins'; +import ConfigFirebase from './config/Firebase'; +import ConfigSMTP from './config/SMTP'; +import Notifications from './Notifications'; +import ManageMembers from '../ManageMembers'; +import FAQ from '../FAQ'; +import ConfigAgora from './config/Agora'; const navs = [ - { - title: "General", - items: [ - { - name: "overview", - title: "Overview", - component: , - }, - { - name: "members", - title: "Members", - component: , - admin: true, - }, - { - name: "notification", - title: "Notification", - component: , - }, - ], - }, - { - title: "User", - items: [ - { - name: "my_account", - title: "My Account", - component: , - }, - ], - }, - { - title: "Configuration", - items: [ - { - name: "firebase", - title: "Firebase", - component: , - }, - { - name: "agora", - title: "Agora", - component: , - }, - { - name: "smtp", - title: "SMTP", - component: , - }, - ], - admin: true, - }, - { - title: "About", - items: [ - { - name: "faq", - title: "FAQ", - component: , - }, - { - name: "terms", - title: "Terms & Privacy", - component: "Terms & Privacy", - }, - { - name: "feedback", - title: "Feedback", - component: "feedback", - }, - ], - }, + { + title: 'General', + items: [ + { + name: 'overview', + title: 'Overview', + component: + }, + { + name: 'members', + title: 'Members', + component: , + admin: true + }, + { + name: 'notification', + title: 'Notification', + component: + } + ] + }, + { + title: 'User', + items: [ + { + name: 'my_account', + title: 'My Account', + component: + } + ] + }, + { + title: 'Configuration', + items: [ + { + name: 'firebase', + title: 'Firebase', + component: + }, + { + name: 'agora', + title: 'Agora', + component: + }, + { + name: 'smtp', + title: 'SMTP', + component: + }, + { + name: 'social_login', + title: 'Social Login', + component: + } + ], + admin: true + }, + { + title: 'About', + items: [ + { + name: 'faq', + title: 'FAQ', + component: + }, + { + name: 'terms', + title: 'Terms & Privacy', + component: 'Terms & Privacy' + }, + { + name: 'feedback', + title: 'Feedback', + component: 'feedback' + } + ] + } ]; const useNavs = () => { - const loginUser = useSelector((store) => { - return store.contacts.byId[store.authData.uid]; - }); - const Navs = navs.filter((nav) => { - if (loginUser.is_admin) { - return true; - } else { - return !nav.admin; - } - }); - return Navs; + const loginUser = useSelector((store) => { + return store.contacts.byId[store.authData.uid]; + }); + const Navs = navs.filter((nav) => { + if (loginUser.is_admin) { + return true; + } else { + return !nav.admin; + } + }); + return Navs; }; export default useNavs; diff --git a/src/routes/login/SolidLoginButton.js b/src/routes/login/SolidLoginButton.js index 93aec9c1..0fa43eed 100644 --- a/src/routes/login/SolidLoginButton.js +++ b/src/routes/login/SolidLoginButton.js @@ -1,35 +1,31 @@ /* eslint-disable no-undef */ -import { useEffect } from "react"; -import { useGetOpenidMutation } from "../../app/services/auth"; -import solidSvg from "../../assets/icons/solid.svg?url"; -import { StyledSocialButton } from "./styled"; +import { useEffect } from 'react'; +import { useGetOpenidMutation } from '../../app/services/auth'; +import solidSvg from '../../assets/icons/solid.svg?url'; +import { StyledSocialButton } from './styled'; -export default function SolidLoginButton() { - const [getOpenId, { data, isLoading, isSuccess }] = useGetOpenidMutation(); +export default function SolidLoginButton({ issuers }) { + const [getOpenId, { data, isLoading, isSuccess }] = useGetOpenidMutation(); - const handleSolidLogin = () => { - getOpenId({ - // issuer: "solidweb.org", - issuer: "broker.pod.inrupt.com", - redirect_uri: `${location.origin}/#/login`, - }); - }; - useEffect(() => { - if (isSuccess) { - console.log("wtf", data); - const { url } = data; - location.href = url; - } - }, [data, isSuccess]); + const handleSolidLogin = () => { + getOpenId({ + // issuer: "solidweb.org", + issuer: issuers[0], + redirect_uri: `${location.origin}/#/login` + }); + }; + useEffect(() => { + if (isSuccess) { + console.log('wtf', data); + const { url } = data; + location.href = url; + } + }, [data, isSuccess]); - return ( - - - {isLoading ? `Redirecting...` : `Sign in with Solid`} - - ); + return ( + + + {isLoading ? `Redirecting...` : `Sign in with Solid`} + + ); } diff --git a/src/routes/login/index.js b/src/routes/login/index.js index 1bdb9596..6ef3c2d9 100644 --- a/src/routes/login/index.js +++ b/src/routes/login/index.js @@ -1,130 +1,130 @@ /* eslint-disable no-undef */ -import { useState, useEffect } from "react"; -import { useDispatch } from "react-redux"; -import { useNavigate } from "react-router-dom"; -import toast from "react-hot-toast"; -import BASE_URL from "../../app/config"; +import { useState, useEffect } from 'react'; +import { useDispatch } from 'react-redux'; +import { useNavigate } from 'react-router-dom'; +import toast from 'react-hot-toast'; +import BASE_URL from '../../app/config'; // import web3 from "web3"; -import StyledWrapper from "./styled"; -import MetamaskLoginButton from "./MetamaskLoginButton"; -import SolidLoginButton from "./SolidLoginButton"; -import Input from "../../common/component/styled/Input"; -import Button from "../../common/component/styled/Button"; -import GoogleLoginButton from "./GoogleLoginButton"; -import { useLoginMutation } from "../../app/services/auth"; -import { setAuthData } from "../../app/slices/auth.data"; +import StyledWrapper from './styled'; +import MetamaskLoginButton from './MetamaskLoginButton'; +import SolidLoginButton from './SolidLoginButton'; +import Input from '../../common/component/styled/Input'; +import Button from '../../common/component/styled/Button'; +import GoogleLoginButton from './GoogleLoginButton'; +import { useLoginMutation } from '../../app/services/auth'; +import { useGetLoginConfigQuery } from '../../app/services/server'; +import { setAuthData } from '../../app/slices/auth.data'; export default function LoginPage() { - const [login, { data, isSuccess, isLoading, error }] = useLoginMutation(); - const navigateTo = useNavigate(); - const dispatch = useDispatch(); - const [input, setInput] = useState({ - email: "", - password: "", + const [login, { data, isSuccess, isLoading, error }] = useLoginMutation(); + const { data: loginConfig, isSuccess: loginConfigSuccess } = useGetLoginConfigQuery(); + const navigateTo = useNavigate(); + const dispatch = useDispatch(); + const [input, setInput] = useState({ + email: '', + password: '' + }); + useEffect(() => { + const query = new URLSearchParams(location.search); + const code = query.get('code'); + const state = query.get('state'); + if (code && state) { + login({ + code, + state, + type: 'oidc' + }); + } + }, []); + + useEffect(() => { + if (error) { + console.log(error); + switch (error.status) { + case 'PARSING_ERROR': + toast.error(error.data); + break; + case 401: + toast.error('username or password incorrect'); + break; + case 404: + toast.error('account not exsit'); + break; + default: + toast.error('something error'); + break; + } + return; + } + }, [error]); + useEffect(() => { + if (isSuccess && data) { + // 更新本地认证信息 + console.log('login data', data); + toast.success('login success'); + dispatch(setAuthData(data)); + navigateTo('/'); + } + }, [isSuccess, data]); + + const handleLogin = (evt) => { + evt.preventDefault(); + console.log('wtf', input); + login({ + ...input, + type: 'password' }); - useEffect(() => { - const query = new URLSearchParams(location.search); - const code = query.get("code"); - const state = query.get("state"); - if (code && state) { - login({ - code, - state, - type: "oidc", - }); - } - }, []); + }; - useEffect(() => { - if (error) { - console.log(error); - switch (error.status) { - case "PARSING_ERROR": - toast.error(error.data); - break; - case 401: - toast.error("username or password incorrect"); - break; - case 404: - toast.error("account not exsit"); - break; - default: - toast.error("something error"); - break; - } - return; - } - }, [error]); - useEffect(() => { - if (isSuccess && data) { - // 更新本地认证信息 - console.log("login data", data); - toast.success("login success"); - dispatch(setAuthData(data)); - navigateTo("/"); - } - }, [isSuccess, data]); - - const handleLogin = (evt) => { - evt.preventDefault(); - console.log("wtf", input); - login({ - ...input, - type: "password", - }); - }; - - const handleInput = (evt) => { - const { type } = evt.target.dataset; - const { value } = evt.target; - console.log(type, value); - setInput((prev) => { - prev[type] = value; - return { ...prev }; - }); - }; - const { email, password } = input; - return ( - - - - - Login to Rustchat - Please enter your details. - - - - - - {isLoading ? "Signing" : `Sign in`} - - - - - - - - - ); + const handleInput = (evt) => { + const { type } = evt.target.dataset; + const { value } = evt.target; + console.log(type, value); + setInput((prev) => { + prev[type] = value; + return { ...prev }; + }); + }; + const { email, password } = input; + if (!loginConfigSuccess) return null; + const { google: enableGoogleLogin, metamask: enableMetamaskLogin, oidc } = loginConfig; + return ( + + + + + Login to Rustchat + Please enter your details. + + + + + + {isLoading ? 'Signing' : `Sign in`} + + + {(enableGoogleLogin || enableMetamaskLogin || oidc.length > 0) && } + {enableGoogleLogin && } + {enableMetamaskLogin && } + {oidc.length > 0 && } + + + ); }