init keycloak
This commit is contained in:
@@ -3,8 +3,15 @@ import { RouterProvider } from 'react-router-dom';
|
||||
import { router } from './router';
|
||||
import { store } from '../../store';
|
||||
import { Provider } from 'react-redux';
|
||||
import { useKeycloak } from './keycloak';
|
||||
|
||||
const Main = (): React.ReactElement | string => {
|
||||
const { isLoading } = useKeycloak();
|
||||
|
||||
if (isLoading) {
|
||||
return 'Loading...';
|
||||
}
|
||||
|
||||
const Main = (): React.ReactElement => {
|
||||
return (
|
||||
<Provider store={store}>
|
||||
<RouterProvider router={router} />
|
||||
|
||||
53
src/container/main/keycloak.ts
Normal file
53
src/container/main/keycloak.ts
Normal 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
|
||||
};
|
||||
};
|
||||
@@ -4,3 +4,7 @@ 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}`;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user