frontend/src/contexts/CASProvider.tsx

61 lines
2.0 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect, createContext, ReactNode } from 'react';
2020-12-12 19:57:16 +01:00
import { LoggedUser } from '../types';
2020-11-21 12:57:30 +01:00
import { axiosInstance } from '../utils/axiosInstance';
2020-08-12 04:13:14 +02:00
export interface CASContext {
2020-12-12 19:57:16 +01:00
user: LoggedUser | undefined;
2020-08-12 04:13:14 +02:00
logout: () => void;
2020-12-12 19:57:16 +01:00
token: string | undefined;
2020-08-12 04:13:14 +02:00
}
export const CASContext = createContext<CASContext | undefined>(undefined);
2020-08-12 04:13:14 +02:00
export interface CASProviderProps {
children: ReactNode;
2020-08-12 04:13:14 +02:00
}
export const CASProvider = ({ children }: CASProviderProps) => {
2020-12-12 19:57:16 +01:00
const [user, setUser] = useState<LoggedUser>();
const [token, setToken] = useState<string | undefined>();
2020-08-12 04:13:14 +02:00
useEffect(() => {
2020-11-22 18:22:07 +01:00
const login = async () => {
const urlParams = new URLSearchParams(window.location.search);
const ticket = urlParams.get('ticket');
if (!ticket) {
redirectToCASLoginService();
}
try {
2020-12-12 17:54:13 +01:00
if (!localStorage.getItem('userToken')) {
2020-12-12 19:57:16 +01:00
const { data: user } = await axiosInstance.get<LoggedUser & { token: string }>(
`${process.env.REACT_APP_API_URL}/token?ticket=${ticket}`,
);
setUser({ authorityRole: user.authorityRole, email: user.email, id: user.id });
localStorage.setItem('userToken', user.token);
localStorage.setItem('userPrivilige', user.authorityRole);
2020-11-22 18:22:07 +01:00
}
2020-12-12 19:57:16 +01:00
const token = localStorage.getItem('userToken');
token && setToken(token);
2020-11-22 18:22:07 +01:00
} catch (e) {
console.log(e);
}
};
2020-08-12 04:13:14 +02:00
login();
}, []);
function logout() {
2020-12-12 19:57:16 +01:00
localStorage.removeItem('userToken');
2020-12-16 00:50:09 +01:00
localStorage.removeItem('userPrivilige');
2020-08-12 04:13:14 +02:00
redirectToCASLogoutService();
}
function redirectToCASLogoutService() {
window.location.replace(`https://cas.amu.edu.pl/cas/logout?service=${window.origin}`);
}
function redirectToCASLoginService() {
window.location.replace(`https://cas.amu.edu.pl/cas/login?service=${window.origin}&locale=pl`);
}
2020-11-21 04:02:38 +01:00
return <CASContext.Provider value={{ user, token, logout }}>{children}</CASContext.Provider>;
2020-08-12 04:13:14 +02:00
};