Compare commits

..

2 Commits

Author SHA1 Message Date
grinikita
90992b087f init keycloak 2024-12-14 13:08:54 +03:00
grinikita
0ad224f04d redux 2024-12-14 12:32:32 +03:00
16 changed files with 889 additions and 35 deletions

View File

@ -11,7 +11,7 @@ module.exports = {
/* use https://admin.bro-js.ru/ to create config, navigations and features */ /* use https://admin.bro-js.ru/ to create config, navigations and features */
navigations: { navigations: {
'kfu-24-teacher.main': '/kfu-24-teacher', 'kfu-24-teacher.main': '/kfu-24-teacher',
'kfu-24-teacher.detail': '/kfu-24-teacher/detail' 'kfu-24-teacher.detail': '/kfu-24-teacher/:id'
}, },
features: { features: {
'kfu-24-teacher': { 'kfu-24-teacher': {

720
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -17,9 +17,14 @@
"@brojs/cli": "^1.6.3", "@brojs/cli": "^1.6.3",
"@emotion/react": "^11.13.5", "@emotion/react": "^11.13.5",
"@emotion/styled": "^11.13.5", "@emotion/styled": "^11.13.5",
"@reduxjs/toolkit": "^2.5.0",
"axios": "^1.7.9",
"express": "^4.19.2", "express": "^4.19.2",
"keycloak-connect": "^26.0.7",
"keycloak-js": "^26.0.7",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-redux": "^9.2.0",
"react-router-dom": "^6.28.0" "react-router-dom": "^6.28.0"
}, },
"devDependencies": { "devDependencies": {

View File

@ -1,9 +1,11 @@
import React from 'react'; import React from 'react';
import Heading from '../../components/heading'; import Heading from '../../components/heading';
import { HeadingVariant } from '../../components/heading/types'; import { HeadingVariant } from '../../components/heading/types';
import { useParams } from 'react-router-dom';
const DetailPage = (): React.ReactElement => { const DetailPage = (): React.ReactElement => {
return <Heading variant={HeadingVariant.h2}>Detail Page</Heading>; const { id } = useParams();
return <Heading variant={HeadingVariant.h2}>Detail Page {id} </Heading>;
}; };
export default DetailPage; export default DetailPage;

View File

@ -1,30 +1,9 @@
import React, { useEffect, useState } from 'react'; import React from 'react';
import Heading from '../../components/heading'; import Heading from '../../components/heading';
import { useGetListQuery } from '../../store/api';
const ListPage = (): React.ReactElement => { const ListPage = (): React.ReactElement => {
const [error, setError] = useState<string>(null); const { data, isLoading, error } = useGetListQuery(undefined);
const [data, setData] = useState<Array<{ id: number; title: string; description: string }>>();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const handle = async () => {
setIsLoading(true);
try {
const res = await fetch('/api/list');
const data = await res.json();
if (res.ok) {
setData(data);
} else {
setError(data.message);
}
} catch (e) {
setError(e.message);
} finally {
setIsLoading(false);
}
};
handle();
}, []);
return ( return (
<> <>

View File

@ -1,9 +1,22 @@
import React from 'react'; import React from 'react';
import { RouterProvider } from 'react-router-dom'; import { RouterProvider } from 'react-router-dom';
import { router } from './router'; import { router } from './router';
import { store } from '../../store';
import { Provider } from 'react-redux';
import { useKeycloak } from './keycloak';
const Main = (): React.ReactElement => { const Main = (): React.ReactElement | string => {
return <RouterProvider router={router} />; const { isLoading } = useKeycloak();
if (isLoading) {
return 'Loading...';
}
return (
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
);
}; };
export default Main; export default Main;

View File

@ -0,0 +1,53 @@
import Keycloak from 'keycloak-js';
import { useEffect, useState } from 'react';
import { setToken } from '../../service/network';
const keycloak = new Keycloak({
url: 'https://kc.bro-js.ru/',
realm: 'open',
clientId: 'kfu-m-24-1'
});
export interface User {
email: string;
email_verified: boolean;
family_name: string;
given_name: string;
name: string;
preferred_username: string;
id: string;
}
export const useKeycloak = () => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState();
useEffect(() => {
const handle = async () => {
setIsLoading(true);
try {
const authenticated = await keycloak.init({ onLoad: 'login-required' });
if (authenticated) {
setToken(keycloak.token);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { sub, ...user } = (await keycloak.loadUserInfo()) as any;
console.log(user);
setUser({ ...user, id: sub });
console.log('User is authenticated');
} else {
console.log('User is not authenticated');
}
} catch (error) {
console.error('Failed to initialize adapter:', error);
} finally {
setIsLoading(false);
}
};
handle();
}, []);
return {
isLoading,
user
};
};

11
src/service/list/index.ts Normal file
View File

@ -0,0 +1,11 @@
import { network } from '../network';
import { GetListResponse } from './types';
class ListService {
async getList() {
const res = await network.get<GetListResponse>('/list');
return res.data;
}
}
export const listService = new ListService();

View File

@ -0,0 +1,7 @@
export interface ListItem {
id: number;
title: string;
description: string;
}
export type GetListResponse = Array<ListItem>;

10
src/service/network.ts Normal file
View File

@ -0,0 +1,10 @@
import axios from 'axios';
import { getConfigValue } from '@brojs/cli';
const baseUrl = getConfigValue('kfu-24-teacher.api');
export const network = axios.create({ baseURL: baseUrl });
export const setToken = (token: string) => {
network.defaults.headers.authorization = `Bearer ${token}`;
};

29
src/store/api.ts Normal file
View File

@ -0,0 +1,29 @@
// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery, QueryReturnValue } from '@reduxjs/toolkit/query/react';
import { GetListResponse } from '../service/list/types';
import { listService } from '../service/list';
const createQueryFromPromise =
<ARGS, RES>(fn: (...args: Array<ARGS>) => Promise<RES>) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (...args): Promise<QueryReturnValue<RES, any, any>> => {
try {
const data = await fn(...args);
return { data };
} catch (e: unknown) {
return { error: e };
}
};
// Define a service using a base URL and expected endpoints
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '' }),
endpoints: (builder) => ({
getList: builder.query<GetListResponse, undefined>({
queryFn: createQueryFromPromise(() => listService.getList())
})
})
});
export const { useGetListQuery } = api;

20
src/store/index.ts Normal file
View File

@ -0,0 +1,20 @@
import { configureStore } from '@reduxjs/toolkit';
import { api } from './api';
import { setupListeners } from '@reduxjs/toolkit/query';
export const store = configureStore({
reducer: {
// Add the generated reducer as a specific top-level slice
[api.reducerPath]: api.reducer
},
// Adding the api middleware enables caching, invalidation, polling,
// and other useful features of `rtk-query`.
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware)
});
setupListeners(store.dispatch);
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

View File

@ -1,5 +1,6 @@
const router = require('express').Router(); const router = require('express').Router();
const listRouter = require('./list'); const listRouter = require('./list');
const keycloak = require('./keycloak');
module.exports = router; module.exports = router;
const delay = const delay =
@ -8,5 +9,6 @@ const delay =
setTimeout(next, ms); setTimeout(next, ms);
}; };
router.use(keycloak.middleware());
router.use(delay()); router.use(delay());
router.use('/list', listRouter); router.use('/list', listRouter);

12
stubs/api/keycloak.js Normal file
View File

@ -0,0 +1,12 @@
const Keycloak = require('keycloak-connect');
const kcConfig = {
clientId: 'kfu-m-24-1',
bearerOnly: true,
serverUrl: 'https://kc.bro-js.ru/',
realm: 'open'
};
const keycloak = new Keycloak({}, kcConfig);
module.exports = keycloak;

View File

@ -3,8 +3,9 @@ const router = require('express').Router();
module.exports = router; module.exports = router;
const data = require('./data/list.json'); const data = require('./data/list.json');
const keycloak = require('../keycloak');
router.get('/', (req, res) => { router.get('/', keycloak.protect(), (req, res) => {
res.send(data); res.send(data);
// res.status(500).send({ // res.status(500).send({
// message: 'Internal server error' // message: 'Internal server error'

View File

@ -9,7 +9,7 @@
"esModuleInterop": true, "esModuleInterop": true,
"noImplicitAny": false, "noImplicitAny": false,
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "Bundler",
"target": "es6", "target": "es6",
"jsx": "react", "jsx": "react",
"typeRoots": ["node_modules/@types", "src/typings"], "typeRoots": ["node_modules/@types", "src/typings"],