feat: 添加登录支持。

This commit is contained in:
Ivan Li 2021-07-17 17:31:44 +08:00
parent 7d04d53d02
commit 9490d874a9
15 changed files with 4605 additions and 156 deletions

View File

@ -3,6 +3,7 @@
"Formik", "Formik",
"clsx", "clsx",
"fontsource", "fontsource",
"notistack",
"vditor" "vditor"
] ]
} }

View File

@ -7,6 +7,6 @@ generates:
- "typescript" - "typescript"
- "typescript-operations" - "typescript-operations"
- "typescript-react-apollo" - "typescript-react-apollo"
./graphql.schema.json: src/generated/graphql.schema.json:
plugins: plugins:
- "introspection" - "introspection"

4286
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -12,6 +12,7 @@
"@material-ui/icons": "^4.11.2", "@material-ui/icons": "^4.11.2",
"@material-ui/lab": "*", "@material-ui/lab": "*",
"@material-ui/pickers": "^3.3.10", "@material-ui/pickers": "^3.3.10",
"@nestjs-lib/auth": "^0.1.1",
"@testing-library/jest-dom": "^5.11.10", "@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6", "@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3", "@testing-library/user-event": "^12.8.3",
@ -19,16 +20,22 @@
"@types/node": "^12.20.10", "@types/node": "^12.20.10",
"@types/react": "^17.0.3", "@types/react": "^17.0.3",
"@types/react-dom": "^17.0.3", "@types/react-dom": "^17.0.3",
"date-fns": "^2.21.1", "apollo-link-scalars": "^2.1.3",
"date-fns": "^2.22.1",
"eventemitter3": "^4.0.7",
"events": "^3.3.0",
"fontsource-roboto": "^4.0.0", "fontsource-roboto": "^4.0.0",
"formik": "^2.2.6", "formik": "^2.2.6",
"formik-material-ui": "^3.0.1", "formik-material-ui": "^3.0.1",
"formik-material-ui-pickers": "^0.0.12", "formik-material-ui-pickers": "^0.0.12",
"graphql": "^15.5.0", "graphql": "^15.5.0",
"graphql-scalars": "^1.10.0",
"notistack": "^1.0.9",
"ramda": "^0.27.1", "ramda": "^0.27.1",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-scripts": "4.0.3", "react-scripts": "4.0.3",
"subscriptions-transport-ws": "^0.9.19",
"typescript": "^4.2.4", "typescript": "^4.2.4",
"vditor": "^3.8.4", "vditor": "^3.8.4",
"web-vitals": "^1.1.1", "web-vitals": "^1.1.1",

View File

@ -15,6 +15,7 @@ import EditIcon from "@material-ui/icons/Edit";
import { useRouter } from "@curi/react-dom"; import { useRouter } from "@curi/react-dom";
import { ARTICLES, REMOVE_ARTICLE } from './articles.constants'; import { ARTICLES, REMOVE_ARTICLE } from './articles.constants';
import { Delete } from '@material-ui/icons'; import { Delete } from '@material-ui/icons';
import { format } from "date-fns";
export const ArticleIndex: FC = () => { export const ArticleIndex: FC = () => {
const { data } = useQuery<{ const { data } = useQuery<{
@ -44,7 +45,9 @@ export const ArticleIndex: FC = () => {
<TableCell component="th" scope="row"> <TableCell component="th" scope="row">
{article.title} {article.title}
</TableCell> </TableCell>
<TableCell>{article.publishedAt}</TableCell> <TableCell>
{format(article.publishedAt, "yyyy-MM-dd HH:mm:ss")}
</TableCell>
<TableCell align="right"> -- </TableCell> <TableCell align="right"> -- </TableCell>
<TableCell align="right"> -- </TableCell> <TableCell align="right"> -- </TableCell>
<TableCell> <TableCell>

View File

@ -0,0 +1,55 @@
import { createContext, useContext, useState } from "react";
import { FC } from "react";
import { Login } from "./login";
export interface AuthContext {
accessToken: string | null;
setAccessToken: (token: string) => void;
setRefreshToken: (token: string) => void;
refreshToken: string | undefined;
login: (dto: any) => void;
account?: any;
setAccount: (dto: any) => void;
logout: () => void;
}
const Context = createContext({} as AuthContext);
export const useAuth = () => useContext(Context);
export const AuthProvider: FC = ({ children }) => {
const [accessToken, setAccessToken] = useState<string | null>(
localStorage.getItem("accessToken")
);
const [refreshToken, setRefreshToken] = useState<string>();
const [account, setAccount] = useState<any>();
const login = (dto: any) => {
setAccessToken(dto.accessToken);
setRefreshToken(dto.refreshToken);
setAccount(dto.account);
localStorage.setItem("accessToken", dto.accessToken);
};
const logout = () => {
setAccessToken(null);
setRefreshToken(undefined);
setAccount(undefined);
};
return (
<Context.Provider
value={{
accessToken,
setAccessToken,
refreshToken,
setRefreshToken,
login,
account,
setAccount,
logout,
}}
>
{children}
{accessToken ? null : <Login />}
</Context.Provider>
);
};

View File

@ -0,0 +1,66 @@
import { makeStyles } from "@material-ui/core";
import { FC, Fragment, useEffect, useRef } from "react";
import { useAuth } from "./auth.provider";
const useStyles = makeStyles((theme) => ({
iframe: {
height: "300px",
width: "500px",
position: "absolute",
top: "100px",
left: "50%",
transform: "translateX(-50%)",
zIndex: theme.zIndex.modal,
border: "none",
boxShadow: theme.shadows[4],
},
mask: {
top: "0",
left: "0",
bottom: "0",
right: "0",
position: "absolute",
backgroundColor: "rgba(0, 0, 0, 0.3)",
zIndex: theme.zIndex.modal,
},
}));
export const Login: FC = () => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const { login } = useAuth();
useEffect(() => {
const iframe = iframeRef.current;
if (!iframe) {
return;
}
let messagePort: MessagePort;
const onLoad = (ev: MessageEvent) => {
if (ev.data !== "init-channel") {
return;
}
messagePort = ev.ports?.[0] as MessagePort;
messagePort.onmessage = (ev: MessageEvent) => {
if (ev.data?.type === "logged") {
login(ev.data.payload);
}
};
};
window.addEventListener("message", onLoad);
return () => {
window.removeEventListener("message", onLoad);
};
}, [login]);
const classes = useStyles();
return (
<Fragment>
<div className={classes.mask} />
<iframe
ref={iframeRef}
className={classes.iframe}
title="Auth"
src="https://user.rpi.ivanli.cc/auth/login"
></iframe>
</Fragment>
);
};

View File

@ -1,6 +0,0 @@
import { ApolloClient, InMemoryCache } from "@apollo/client";
export const client = new ApolloClient({
uri: "/api/graphql",
cache: new InMemoryCache(),
});

View File

@ -0,0 +1,178 @@
import {
ApolloClient,
ApolloLink,
HttpLink,
InMemoryCache,
split,
ApolloProvider,
fromPromise,
FetchResult,
} from "@apollo/client";
import { withScalars } from "apollo-link-scalars";
import { buildClientSchema, IntrospectionQuery } from "graphql";
import { DateTimeResolver } from "graphql-scalars";
import { FC } from "react";
import introspectionResult from "../../generated/graphql.schema.json";
import { onError } from "@apollo/client/link/error";
import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition, Observable } from "@apollo/client/utilities";
import { useSnackbar } from "notistack";
import { deepOmit } from "../../utils/deep-omit";
import { useMemo } from "react";
import { EventEmitter } from "events";
import { useState } from "react";
import { useAuth } from "../auth/auth.provider";
import { useEffect } from "react";
import { useRef } from "react";
import { setContext } from "@apollo/client/link/context";
const schema = buildClientSchema(
introspectionResult as unknown as IntrospectionQuery
);
const typesMap = {
DateTime: DateTimeResolver,
};
const cleanTypeName = new ApolloLink((operation, forward) => {
if (operation.variables) {
operation.variables = deepOmit(["__typename"], operation.variables);
}
const rt = forward(operation);
return (
rt.map?.((data) => {
return data;
}) ?? rt
);
});
export const AppApolloClientProvider: FC = ({ children }) => {
const { enqueueSnackbar } = useSnackbar();
const { accessToken, logout } = useAuth();
const [loggedEventTarget] = useState(() => new EventEmitter());
const accessTokenRef = useRef(accessToken);
const logoutRef = useRef(logout);
useEffect(() => {
accessTokenRef.current = accessToken;
if (accessToken) {
loggedEventTarget.emit("logged", accessToken);
}
}, [loggedEventTarget, accessToken]);
useEffect(() => {
logoutRef.current = logout;
}, [logout]);
const client = useMemo(() => {
const authLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (const error of graphQLErrors) {
if (error.extensions?.code === "401") {
return fromPromise(
new Promise<Observable<FetchResult>>((resolve) => {
loggedEventTarget.once("logged", (accessToken: string) => {
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${accessToken}`,
},
});
resolve(forward(operation));
});
logoutRef.current();
})
).flatMap((v) => v);
}
}
}
const httpResult = (networkError as any)?.result;
if (httpResult?.statusCode === 401) {
return fromPromise(
new Promise<Observable<FetchResult>>((resolve) => {
loggedEventTarget.once("logged", (accessToken: string) => {
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${accessToken}`,
},
});
resolve(forward(operation));
});
logoutRef.current();
})
).flatMap((v) => v);
}
}
).concat(
setContext(() => ({
headers: {
authorization: `Bearer ${accessTokenRef.current}`,
},
}))
);
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach((error) => {
enqueueSnackbar(error.message, {
variant: "error",
});
});
graphQLErrors.forEach(({ message, locations, path }) => {
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
});
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
enqueueSnackbar(networkError.message, {
variant: "error",
});
}
});
const wsLink = new WebSocketLink({
uri: `${window.location.protocol.replace("http", "ws")}//${
window.location.hostname
}:${window.location.port}/api/graphql`,
options: {
reconnect: true,
},
});
const httpLink = new HttpLink({
uri: "/api/graphql",
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
);
const link = ApolloLink.from([
errorLink,
authLink,
withScalars({ schema, typesMap }) as unknown as ApolloLink,
cleanTypeName,
splitLink,
]);
const client = new ApolloClient({
connectToDevTools: true,
ssrMode: typeof window === "undefined",
link,
cache: new InMemoryCache({
typePolicies: {},
}),
});
return client;
}, [enqueueSnackbar, loggedEventTarget]);
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};

View File

@ -0,0 +1,20 @@
import { ActiveHookProps, Link, LinkProps, useActive } from '@curi/react-dom';
import React, { FC, ReactNode } from 'react';
export type ActiveLinkProps = ActiveHookProps &
LinkProps & {
className?: string;
children: ReactNode;
};
export const ActiveLink:FC<ActiveLinkProps> = ({ name, params, partial, className = "", ...rest }) => {
const active = useActive({ name, params, partial });
return (
<Link
name={name}
params={params}
{...rest}
className={active ? `${className} active` : className}
/>
);
};

View File

@ -0,0 +1,31 @@
import { useApolloClient } from "@apollo/client";
import { createRouterComponent } from "@curi/react-dom";
import { createRouter, announce } from "@curi/router";
import { browser } from "@hickory/browser";
import { FC, useEffect, useState } from "react";
import routes from "../../routes";
import { LinearProgress } from "@material-ui/core";
const Component: FC = ({ children }) => {
const client = useApolloClient();
const [body, setBody] = useState<any>(null);
useEffect(() => {
const router = createRouter(browser, routes, {
sideEffects: [
announce(({ response }) => {
return `Navigated to ${response.location.pathname}`;
}),
],
external: { client },
});
const Router = createRouterComponent(router);
router.once(() => {
setBody(<Router>{children}</Router>);
});
}, [setBody, client, children]);
return body ?? <LinearProgress />;
};
export default Component;

View File

@ -96,6 +96,34 @@
}, },
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "deprecationReason": null
},
{
"name": "html",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
} }
], ],
"inputFields": null, "inputFields": null,

View File

@ -21,6 +21,8 @@ export type Article = {
content: Scalars['String']; content: Scalars['String'];
publishedAt?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>;
tags: Array<Scalars['String']>; tags: Array<Scalars['String']>;
html: Scalars['String'];
description?: Maybe<Scalars['String']>;
}; };
export type CreateArticleInput = { export type CreateArticleInput = {

View File

@ -4,40 +4,30 @@ import "./index.css";
import "fontsource-roboto"; import "fontsource-roboto";
import App from "./App"; import App from "./App";
import reportWebVitals from "./reportWebVitals"; import reportWebVitals from "./reportWebVitals";
import { client } from "./commons/graphql/client"; import { AppApolloClientProvider } from "./commons/graphql/client";
import { ApolloProvider } from "@apollo/client";
import { MuiPickersUtilsProvider } from "@material-ui/pickers"; import { MuiPickersUtilsProvider } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns"; import DateFnsUtils from "@date-io/date-fns";
import zhLocale from "date-fns/locale/zh-CN"; import zhLocale from "date-fns/locale/zh-CN";
import { createRouterComponent } from "@curi/react-dom"; import { SnackbarProvider } from "notistack";
import { createRouter, announce } from "@curi/router"; import Router from "./commons/route/router";
import { browser } from "@hickory/browser"; import { AuthProvider } from "./commons/auth/auth.provider";
import routes from "./routes";
const router = createRouter(browser, routes, { ReactDOM.render(
sideEffects: [
announce(({ response }) => {
return `Navigated to ${response.location.pathname}`;
}),
],
external: { client }
});
const Router = createRouterComponent(router);
router.once(() => {
ReactDOM.render(
<React.StrictMode> <React.StrictMode>
<ApolloProvider client={client}> <SnackbarProvider maxSnack={5}>
<AuthProvider>
<AppApolloClientProvider>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}> <MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}>
<Router> <Router>
<App /> <App />
</Router> </Router>
</MuiPickersUtilsProvider> </MuiPickersUtilsProvider>
</ApolloProvider> </AppApolloClientProvider>
</AuthProvider>
</SnackbarProvider>
</React.StrictMode>, </React.StrictMode>,
document.getElementById("root") document.getElementById("root")
); );
});
// If you want to start measuring performance in your app, pass a function // If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log)) // to log results (for example: reportWebVitals(console.log))

22
src/utils/deep-omit.ts Normal file
View File

@ -0,0 +1,22 @@
import { fromPairs, map, omit, pipe, toPairs, type } from "ramda";
export const deepOmit = <T = any, K = any>(
names: readonly string[],
value: K
): T => {
switch (type(value)) {
case "Array":
return (value as unknown as Array<any>).map((item: any) =>
deepOmit(names, item)
) as unknown as T;
case "Object":
return pipe(
omit(names),
toPairs,
map(([key, val]) => [key, deepOmit(names, val)] as any),
fromPairs
)(value) as unknown as T;
default:
return value as unknown as T;
}
};