feat: sync with latest api

This commit is contained in:
Paul Pan 2024-04-29 00:16:03 +08:00
parent 7785d7a875
commit 6eb3ccfdd0
6 changed files with 50 additions and 181 deletions

View File

@ -1,5 +1,5 @@
name: Build Container Image
on: [ push ]
on: [push]
jobs:
image:
runs-on: ubuntu-latest

View File

@ -7,18 +7,6 @@ export enum UserRole {
RoleGuest = 10,
}
export interface UserRequest {
email?: string;
password?: string;
nickname?: string;
uid?: number;
}
export interface UserLoginResponse {
nickname: string;
token: string;
}
export interface UserProfile {
meta: Meta;
email: string;
@ -29,22 +17,6 @@ export interface UserProfile {
export const userApi = api.injectEndpoints({
endpoints: (builder) => ({
register: builder.mutation<Wrap<string>, UserRequest>({
query: (data: UserRequest) => ({
url: "/user/create",
method: "POST",
body: data,
}),
invalidatesTags: ["User", "Status", "Submission"],
}),
login: builder.mutation<Wrap<UserLoginResponse>, UserRequest>({
query: (data: UserRequest) => ({
url: "/user/login",
method: "POST",
body: data,
}),
invalidatesTags: ["User", "Status", "Submission"],
}),
logout: builder.mutation<Wrap<void>, void>({
query: () => ({
url: "/user/logout",
@ -63,4 +35,4 @@ export const userApi = api.injectEndpoints({
}),
});
export const { useRegisterMutation, useLoginMutation, useLogoutMutation, useProfileQuery } = userApi;
export const { useLogoutMutation, useProfileQuery } = userApi;

View File

@ -26,23 +26,11 @@ export const authSlice = createAppSlice({
},
extraReducers: (builder) => {
builder
.addMatcher(userApi.endpoints.login.matchFulfilled, (_state, action) => {
// Login Success
const { token } = action.payload.body;
localStorage.setItem("token", token);
return { ...initialState, token: token };
})
.addMatcher(userApi.endpoints.logout.matchFulfilled, (_state, _action) => {
// Logout Success
localStorage.removeItem("token");
return { ...initialState, token: null };
})
.addMatcher(userApi.endpoints.login.matchRejected, (_state, action) => {
// Login Failed
console.error("Login Failed", action.payload);
localStorage.removeItem("token");
return { ...initialState, token: null };
})
.addMatcher(userApi.endpoints.profile.matchRejected, (_state, action) => {
// Profile Failed
if (action.meta.arg.originalArgs != 0) return;

View File

@ -1,9 +1,11 @@
import { isRouteErrorResponse, useNavigate, useRouteError } from "react-router-dom";
import { isRouteErrorResponse, useNavigate, useRouteError, useSearchParams } from "react-router-dom";
import { Box, Button, ButtonGroup, Flex, Heading, Text } from "@chakra-ui/react";
import { CloseIcon } from "@chakra-ui/icons";
export const ErrorPage = () => {
const navigate = useNavigate();
const [searchParams, _] = useSearchParams();
const serverError = searchParams.get("message");
const error = useRouteError();
const convertError = (error: unknown): string => {
@ -13,6 +15,8 @@ export const ErrorPage = () => {
return error.message;
} else if (typeof error === "string") {
return error;
} else if (serverError) {
return serverError;
} else {
console.error(error);
return "Unknown error";

View File

@ -1,32 +1,11 @@
import type React from "react";
import { useEffect, useState } from "react";
import {
Box,
Button,
Center,
Container,
Divider,
FormControl,
FormLabel,
Heading,
HStack,
Input,
Link,
Stack,
Text,
useColorModeValue,
useToast,
} from "@chakra-ui/react";
import { Link as ReactRouterLink, useNavigate, useSearchParams } from "react-router-dom";
import { useEffect } from "react";
import { Box, Button, Center, Container, Heading, Stack, Text, useColorModeValue, useToast } from "@chakra-ui/react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Cookies from "universal-cookie";
import { useAppDispatch } from "../hooks/store";
import { PasswordField } from "../components/PasswordField";
import { api } from "../app/services/api";
import type { UserRequest } from "../app/services/user";
import { useLoginMutation } from "../app/services/user";
import { useOAuthUrlQuery } from "../app/services/oauth";
import type { Wrap } from "../app/services/base";
import { RiLoginCircleLine } from "react-icons/ri";
import KeyCloakSVG from "../resources/keycloak.svg";
@ -34,8 +13,7 @@ import { setToken } from "../features/auth/authSlice";
export default function LoginPage() {
const bg = useColorModeValue("gray.50", "gray.900");
const fg = "teal";
const fg2 = "gray";
const fg = "gray";
const dispatch = useAppDispatch();
const toast = useToast();
@ -45,15 +23,9 @@ export default function LoginPage() {
const [searchParams, _] = useSearchParams();
const redirectToken = searchParams.get("redirect_token");
const [login, { isLoading: loginIsLoading }] = useLoginMutation();
const { data: oauthInfo, isSuccess: oauthIsSuccess } = useOAuthUrlQuery(undefined, {
// refresh every minute
pollingInterval: 60000,
});
const [formState, setFormState] = useState<UserRequest>({
email: "",
password: "",
// refresh every 10 minute
pollingInterval: 600000,
});
useEffect(() => {
@ -64,40 +36,6 @@ export default function LoginPage() {
navigate("/");
}, [dispatch, navigate, redirectToken]);
const handleChange = ({ target: { name, value } }: React.ChangeEvent<HTMLInputElement>) =>
setFormState((prev) => ({ ...prev, [name]: value }));
const validate = () => {
const { email, password } = formState;
return email && password && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};
const doLogin = async () => {
if (!validate()) {
toast({
status: "error",
title: "Invalid Input",
description: "Please fill in all fields and make sure your email is valid.",
isClosable: true,
});
return;
}
try {
// authSlice will automatically handle the response
await login(formState).unwrap();
navigate("/");
} catch (err) {
const errTyped = err as { status: number | string; data: Wrap<void> };
toast({
status: "error",
title: "Error",
description: errTyped.status === 200 ? errTyped.data.msg : "Oh no, there was an error!",
isClosable: true,
});
}
};
const doSSOLogin = () => {
if (!oauthIsSuccess || !oauthInfo) {
toast({
@ -117,37 +55,9 @@ export default function LoginPage() {
window.open(oauthInfo.body.url, "_self");
};
const formArea = (
<form
onSubmit={(e) => {
e.preventDefault();
void doLogin();
}}
>
<Stack spacing="5">
<FormControl>
<FormLabel htmlFor="email">Email</FormLabel>
<Input id="email" name="email" type="email" isDisabled={loginIsLoading} onChange={handleChange} />
</FormControl>
<PasswordField isDisabled={loginIsLoading} onChange={handleChange} />
{/* eslint-disable-next-line @typescript-eslint/no-misused-promises */}
<Button type="submit" colorScheme={fg} isLoading={loginIsLoading} onClick={doLogin}>
Sign in
</Button>
</Stack>
</form>
);
const ssoArea = (
<Stack spacing="6">
<HStack>
<Divider />
<Text textStyle="sm" whiteSpace="nowrap" color={fg}>
or continue with
</Text>
<Divider />
</HStack>
<Button colorScheme={fg2} onClick={doSSOLogin}>
<Button colorScheme={fg} onClick={doSSOLogin}>
<img src={KeyCloakSVG} alt="KeyCloak" width="24" height="24" />
<Text mx={2}>Sign in with SSO</Text>
</Button>
@ -159,15 +69,9 @@ export default function LoginPage() {
<Center>
<RiLoginCircleLine size={72} />
</Center>
<Stack spacing={{ base: "2", md: "3" }} textAlign="center">
<Center>
<Heading>Log in to your account</Heading>
<Text>
Don&apos;t have an account?{" "}
<Link as={ReactRouterLink} to="/register" color={fg}>
Sign up
</Link>
</Text>
</Stack>
</Center>
</Stack>
);
@ -182,10 +86,7 @@ export default function LoginPage() {
boxShadow={{ base: "none", sm: "xl" }}
borderRadius={{ base: "none", sm: "xl" }}
>
<Stack spacing="6">
{formArea}
{ssoArea}
</Stack>
<Stack spacing="6">{ssoArea}</Stack>
</Box>
</Stack>
</Container>

View File

@ -25,6 +25,10 @@ export const router: RouteObject[] = [
index: true,
element: <HomePage />,
},
{
path: "error",
element: <ErrorPage />,
},
{
path: "home",
element: <HomePage />,