feat: connect onboarding to APIs

This commit is contained in:
Liyang Zhu
2022-06-05 23:58:13 +08:00
parent 78a585f137
commit defacf6b63
7 changed files with 404 additions and 340 deletions
+8 -12
View File
@@ -17,6 +17,9 @@ const whiteList = [
"getOpenid", "getOpenid",
"getMetamaskNonce", "getMetamaskNonce",
"renew", "renew",
"getInitialized",
"createAdmin",
"updateLoginConfig"
]; ];
const baseQuery = fetchBaseQuery({ const baseQuery = fetchBaseQuery({
baseUrl: BASE_URL, baseUrl: BASE_URL,
@@ -27,7 +30,7 @@ const baseQuery = fetchBaseQuery({
headers.set(tokenHeader, token); headers.set(tokenHeader, token);
} }
return headers; return headers;
}, }
}); });
let waitingForRenew = null; let waitingForRenew = null;
const baseQueryWithTokenCheck = async (args, api, extraOptions) => { const baseQueryWithTokenCheck = async (args, api, extraOptions) => {
@@ -35,16 +38,9 @@ const baseQueryWithTokenCheck = async (args, api, extraOptions) => {
await waitingForRenew; await waitingForRenew;
} }
// 先检查token是否过期,过期则renew // 先检查token是否过期,过期则renew
const { const { token, refreshToken, expireTime = new Date().getTime() } = api.getState().authData;
token,
refreshToken,
expireTime = new Date().getTime(),
} = api.getState().authData;
let result = null; let result = null;
if ( if (!whiteList.includes(api.endpoint) && dayjs().isAfter(new Date(expireTime - 20 * 1000))) {
!whiteList.includes(api.endpoint) &&
dayjs().isAfter(new Date(expireTime - 20 * 1000))
) {
// 快过期了,renew // 快过期了,renew
waitingForRenew = baseQuery( waitingForRenew = baseQuery(
{ {
@@ -52,8 +48,8 @@ const baseQueryWithTokenCheck = async (args, api, extraOptions) => {
method: "POST", method: "POST",
body: { body: {
token, token,
refresh_token: refreshToken, refresh_token: refreshToken
}, }
}, },
api, api,
extraOptions extraOptions
+53 -39
View File
@@ -20,7 +20,7 @@ export const serverApi = createApi({
} catch { } catch {
console.log("get server info error"); console.log("get server info error");
} }
}, }
}), }),
getThirdPartySecret: builder.query({ getThirdPartySecret: builder.query({
query: () => ({ query: () => ({
@@ -29,142 +29,142 @@ export const serverApi = createApi({
// accept: "text/plain", // accept: "text/plain",
// }, // },
url: `/admin/system/third_party_secret`, url: `/admin/system/third_party_secret`,
responseHandler: (response) => response.text(), responseHandler: (response) => response.text()
}), }),
keepUnusedDataFor: 0, keepUnusedDataFor: 0
}), }),
updateThirdPartySecret: builder.mutation({ updateThirdPartySecret: builder.mutation({
query: () => ({ query: () => ({
url: `/admin/system/third_party_secret`, url: `/admin/system/third_party_secret`,
method: "POST", method: "POST",
responseHandler: (response) => response.text(), responseHandler: (response) => response.text()
}), })
}), }),
getMetrics: builder.query({ getMetrics: builder.query({
query: () => ({ url: `/admin/system/metrics` }), query: () => ({ url: `/admin/system/metrics` })
}), }),
getServerVersion: builder.query({ getServerVersion: builder.query({
query: () => ({ query: () => ({
headers: { headers: {
// "content-type": "text/plain", // "content-type": "text/plain",
accept: "text/plain", accept: "text/plain"
}, },
url: `/admin/system/version`, url: `/admin/system/version`,
responseHandler: (response) => response.text(), responseHandler: (response) => response.text()
}), })
}), }),
getFirebaseConfig: builder.query({ getFirebaseConfig: builder.query({
query: () => ({ url: `admin/fcm/config` }), query: () => ({ url: `admin/fcm/config` })
}), }),
getGoogleAuthConfig: builder.query({ getGoogleAuthConfig: builder.query({
query: () => ({ url: `admin/google_auth/config` }), query: () => ({ url: `admin/google_auth/config` })
}), }),
updateGoogleAuthConfig: builder.mutation({ updateGoogleAuthConfig: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/google_auth/config`, url: `admin/google_auth/config`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
getGithubAuthConfig: builder.query({ getGithubAuthConfig: builder.query({
query: () => ({ url: `admin/github_auth/config` }), query: () => ({ url: `admin/github_auth/config` })
}), }),
updateGithubAuthConfig: builder.mutation({ updateGithubAuthConfig: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/github_auth/config`, url: `admin/github_auth/config`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
sendTestEmail: builder.mutation({ sendTestEmail: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `/admin/system/send_mail`, url: `/admin/system/send_mail`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
updateFirebaseConfig: builder.mutation({ updateFirebaseConfig: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/fcm/config`, url: `admin/fcm/config`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
getAgoraConfig: builder.query({ getAgoraConfig: builder.query({
query: () => ({ url: `admin/agora/config` }), query: () => ({ url: `admin/agora/config` })
}), }),
updateAgoraConfig: builder.mutation({ updateAgoraConfig: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/agora/config`, url: `admin/agora/config`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
getSMTPConfig: builder.query({ getSMTPConfig: builder.query({
query: () => ({ url: `admin/smtp/config` }), query: () => ({ url: `admin/smtp/config` })
}), }),
getSMTPStatus: builder.query({ getSMTPStatus: builder.query({
query: () => ({ url: `/admin/smtp/enabled` }), query: () => ({ url: `/admin/smtp/enabled` })
}), }),
updateSMTPConfig: builder.mutation({ updateSMTPConfig: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/smtp/config`, url: `admin/smtp/config`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
getLoginConfig: builder.query({ getLoginConfig: builder.query({
query: () => ({ url: `admin/login/config` }), query: () => ({ url: `admin/login/config` })
}), }),
updateLoginConfig: builder.mutation({ updateLoginConfig: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/login/config`, url: `admin/login/config`,
method: "POST", method: "POST",
body: data, body: data
}), })
}), }),
updateLogo: builder.mutation({ updateLogo: builder.mutation({
query: (data) => ({ query: (data) => ({
headers: { headers: {
"content-type": "image/png", "content-type": "image/png"
}, },
url: `admin/system/organization/logo`, url: `admin/system/organization/logo`,
method: "POST", method: "POST",
body: data, body: data
}), }),
async onQueryStarted(data, { dispatch, queryFulfilled }) { async onQueryStarted(data, { dispatch, queryFulfilled }) {
try { try {
await queryFulfilled; await queryFulfilled;
dispatch( dispatch(
updateInfo({ updateInfo({
logo: `${BASE_URL}/resource/organization/logo?t=${new Date().getTime()}`, logo: `${BASE_URL}/resource/organization/logo?t=${new Date().getTime()}`
}) })
); );
} catch { } catch {
console.log("update server logo error"); console.log("update server logo error");
} }
}, }
}), }),
createInviteLink: builder.query({ createInviteLink: builder.query({
query: (expired_in = defaultExpireDuration) => ({ query: (expired_in = defaultExpireDuration) => ({
headers: { headers: {
"content-type": "text/plain", "content-type": "text/plain",
accept: "text/plain", accept: "text/plain"
}, },
url: `/admin/system/create_invite_link?expired_in=${expired_in}`, url: `/admin/system/create_invite_link?expired_in=${expired_in}`,
responseHandler: (response) => response.text(), responseHandler: (response) => response.text()
}), }),
transformResponse: (link) => { transformResponse: (link) => {
// 替换掉域名 // 替换掉域名
const invite = new URL(link); const invite = new URL(link);
return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`; return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`;
}, }
}), }),
updateServer: builder.mutation({ updateServer: builder.mutation({
query: (data) => ({ query: (data) => ({
url: `admin/system/organization`, url: `admin/system/organization`,
method: "POST", method: "POST",
body: data, body: data
}), }),
async onQueryStarted(data, { dispatch, queryFulfilled, getState }) { async onQueryStarted(data, { dispatch, queryFulfilled, getState }) {
const { name: prevName, description: prevDesc } = getState().server; const { name: prevName, description: prevDesc } = getState().server;
@@ -174,9 +174,21 @@ export const serverApi = createApi({
} catch { } catch {
dispatch(updateInfo({ name: prevName, description: prevDesc })); dispatch(updateInfo({ name: prevName, description: prevDesc }));
} }
}, }
}), }),
createAdmin: builder.mutation({
query: (data) => ({
url: `/admin/system/createAdmin`,
method: "POST",
body: data
})
}), }),
getInitialized: builder.query({
query: () => ({
url: `/admin/system/initialized`
})
})
})
}); });
export const { export const {
@@ -204,4 +216,6 @@ export const {
useLazyCreateInviteLinkQuery, useLazyCreateInviteLinkQuery,
useGetThirdPartySecretQuery, useGetThirdPartySecretQuery,
useUpdateThirdPartySecretMutation, useUpdateThirdPartySecretMutation,
useCreateAdminMutation,
useGetInitializedQuery
} = serverApi; } = serverApi;
@@ -0,0 +1,8 @@
import { Navigate } from "react-router-dom";
import { useGetInitializedQuery } from "../../app/services/server";
export default function RequireInitialized({ children, redirectTo = "/" }) {
const { data } = useGetInitializedQuery();
console.log("initialized?", data);
return data === false ? <Navigate to={redirectTo} replace /> : children;
}
+5
View File
@@ -24,6 +24,7 @@ import SettingChannelPage from "./settingChannel";
import OnboardingPage from "./onboarding"; import OnboardingPage from "./onboarding";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import ResourceManagement from "./resources"; import ResourceManagement from "./resources";
import RequireInitialized from "../common/component/RequireInitialized";
const PageRoutes = () => { const PageRoutes = () => {
const { const {
@@ -49,9 +50,11 @@ const PageRoutes = () => {
<Route <Route
path="/login" path="/login"
element={ element={
<RequireInitialized>
<RequireNoAuth> <RequireNoAuth>
<LoginPage /> <LoginPage />
</RequireNoAuth> </RequireNoAuth>
</RequireInitialized>
} }
/> />
<Route <Route
@@ -89,9 +92,11 @@ const PageRoutes = () => {
<Route <Route
path="/" path="/"
element={ element={
<RequireInitialized>
<RequireAuth> <RequireAuth>
<HomePage /> <HomePage />
</RequireAuth> </RequireAuth>
</RequireInitialized>
} }
> >
<Route path="setting"> <Route path="setting">
+1 -5
View File
@@ -11,11 +11,7 @@ import StyledOnboardingPage from "./styled";
export default function OnboardingPage() { export default function OnboardingPage() {
const [step, setStep] = useState(0); const [step, setStep] = useState(0);
const [data, setData] = useState({ const [data, setData] = useState({
spaceName: "", spaceName: ""
adminEmail: "",
adminPassword: "",
adminPassword2: "",
inviteRule: null
}); });
const props = { step, setStep, data, setData }; const props = { step, setStep, data, setData };
@@ -1,7 +1,10 @@
import { useEffect, useState } from "react";
import styled from "styled-components"; import styled from "styled-components";
import toast from "react-hot-toast";
import StyledInput from "../../../common/component/styled/Input"; import StyledInput from "../../../common/component/styled/Input";
import StyledButton from "../../../common/component/styled/Button"; import StyledButton from "../../../common/component/styled/Button";
import toast from "react-hot-toast"; import { useCreateAdminMutation } from "../../../app/services/server";
import { useLoginMutation } from "../../../app/services/auth";
const StyledAdminCredentialsStep = styled.div` const StyledAdminCredentialsStep = styled.div`
height: 100%; height: 100%;
@@ -19,7 +22,34 @@ const StyledAdminCredentialsStep = styled.div`
} }
`; `;
export default function AdminCredentialsStep({ step, setStep, data, setData }) { export default function AdminCredentialsStep({ step, setStep }) {
const [
createAdmin,
{ isLoading: isSignUpLoading, isSuccess: isSignUpSuccess, error: signUpError }
] = useCreateAdminMutation();
const [login, { isLoading: isLoginLoading, isSuccess: isLoginSuccess, error: loginError }] =
useLoginMutation();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState("");
// Display error
useEffect(() => {
if (signUpError === undefined) return;
toast.error(`Failed to sign up: ${signUpError.data}`);
}, [signUpError]);
useEffect(() => {
if (loginError === undefined) return;
toast.error(`Login failed: ${loginError.data}`);
}, [loginError]);
// Increment `step` when both signing up and logging in have completed
useEffect(() => {
if (isSignUpSuccess && isLoginSuccess) setStep(step + 1);
}, [isSignUpSuccess, isLoginSuccess]);
return ( return (
<StyledAdminCredentialsStep> <StyledAdminCredentialsStep>
<span className="primaryText">Now lets set up your admin account</span> <span className="primaryText">Now lets set up your admin account</span>
@@ -27,56 +57,51 @@ export default function AdminCredentialsStep({ step, setStep, data, setData }) {
<StyledInput <StyledInput
className="input" className="input"
placeholder="Enter your email" placeholder="Enter your email"
value={data.adminEmail} value={email}
onChange={(e) => onChange={(e) => setEmail(e.target.value)}
setData({
...data,
adminEmail: e.target.value
})
}
/> />
<StyledInput <StyledInput
className="input" className="input"
type="password" type="password"
placeholder="Enter your password" placeholder="Enter your password"
value={data.adminPassword} value={password}
onChange={(e) => onChange={(e) => setPassword(e.target.value)}
setData({
...data,
adminPassword: e.target.value
})
}
/> />
<StyledInput <StyledInput
className="input" className="input"
type="password" type="password"
placeholder="Confirm your password" placeholder="Confirm your password"
value={data.adminPassword2} value={confirm}
onChange={(e) => onChange={(e) => setConfirm(e.target.value)}
setData({
...data,
adminPassword2: e.target.value
})
}
/> />
<StyledButton <StyledButton
className="button" className="button"
onClick={() => { onClick={async () => {
// Verification for admin credentials // Verification for admin credentials
if (data.adminEmail === "") { if (email === "") {
toast.error("Please enter admin email!"); toast.error("Please enter admin email!");
return; return;
} else if (data.adminPassword === "") { } else if (password === "") {
toast.error("Please enter admin password!"); toast.error("Please enter admin password!");
return; return;
} else if (data.adminPassword !== data.adminPassword2) { } else if (password !== confirm) {
toast.error("Two passwords do not match!"); toast.error("Two passwords do not match!");
return; return;
} }
setStep(step + 1); await createAdmin({
email,
name: "Admin",
password,
gender: 0
});
await login({
email,
password,
type: "password"
});
}} }}
> >
Sign Up {!(isSignUpLoading || isLoginLoading) ? "Sign Up" : "..."}
</StyledButton> </StyledButton>
</StyledAdminCredentialsStep> </StyledAdminCredentialsStep>
); );
+28 -8
View File
@@ -1,6 +1,9 @@
import { useState, useEffect } from "react";
import toast from "react-hot-toast";
import styled from "styled-components"; import styled from "styled-components";
import StyledRadio from "../../../common/component/styled/Radio"; import StyledRadio from "../../../common/component/styled/Radio";
import StyledButton from "../../../common/component/styled/Button"; import StyledButton from "../../../common/component/styled/Button";
import { useGetLoginConfigQuery, useUpdateLoginConfigMutation } from "../../../app/services/server";
const StyledInviteRuleStep = styled.div` const StyledInviteRuleStep = styled.div`
height: 100%; height: 100%;
@@ -14,22 +17,39 @@ const StyledInviteRuleStep = styled.div`
} }
`; `;
export default function InviteRuleStep({ step, setStep, data, setData }) { export default function InviteRuleStep({ step, setStep }) {
const { data: loginConfig } = useGetLoginConfigQuery();
const [updateLoginConfig, { isSuccess, error }] = useUpdateLoginConfigMutation();
const [value, setValue] = useState(null);
// Display error
useEffect(() => {
if (error === undefined) return;
toast.error(`Failed to update invitation rule: ${error.data}`);
}, [error]);
// Increment `step` when updating has completed
useEffect(() => {
if (isSuccess) setStep(step + 1);
}, [isSuccess]);
return ( return (
<StyledInviteRuleStep> <StyledInviteRuleStep>
<span className="primaryText">Last step: invite others!</span> <span className="primaryText">Last step: invite others!</span>
<span className="secondaryText">Firstly, who can sign up to this server?</span> <span className="secondaryText">Firstly, who can sign up to this server?</span>
<StyledRadio <StyledRadio
options={["Everyone", "Invitation link only"]} options={["Everyone", "Invitation link only"]}
value={data.inviteRule} value={value}
onChange={(v) => { onChange={(v) => {
setData({ setValue(v);
...data, if (loginConfig !== undefined) {
inviteRule: v const whoCanSignUp = ["EveryOne", "InvitationOnly"][v];
updateLoginConfig({
...loginConfig,
who_can_sign_up: whoCanSignUp
}); });
setTimeout(() => { }
setStep(step + 1);
}, 750);
}} }}
/> />
<StyledButton className="button border_less ghost" onClick={() => setStep(step + 1)}> <StyledButton className="button border_less ghost" onClick={() => setStep(step + 1)}>