2020-10-21 18:34:59 +02:00
|
|
|
import React, { useState, useEffect, createContext, ReactNode } from 'react';
|
2020-08-12 04:13:14 +02:00
|
|
|
import { User } 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-10-21 18:34:59 +02:00
|
|
|
user?: User;
|
2020-08-12 04:13:14 +02:00
|
|
|
logout: () => void;
|
2020-11-21 04:02:38 +01:00
|
|
|
token?: string | null;
|
2020-08-12 04:13:14 +02:00
|
|
|
}
|
|
|
|
|
2020-10-21 18:34:59 +02:00
|
|
|
export const CASContext = createContext<CASContext | undefined>(undefined);
|
2020-08-12 04:13:14 +02:00
|
|
|
|
|
|
|
export interface CASProviderProps {
|
2020-10-21 18:34:59 +02:00
|
|
|
children: ReactNode;
|
2020-08-12 04:13:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export const CASProvider = ({ children }: CASProviderProps) => {
|
2020-10-21 18:34:59 +02:00
|
|
|
const [user, setUser] = useState<User | undefined>(undefined);
|
2020-11-21 04:02:38 +01:00
|
|
|
const [token, setToken] = useState<string | null>(null);
|
2020-08-12 04:13:14 +02:00
|
|
|
useEffect(() => {
|
|
|
|
login();
|
|
|
|
}, []);
|
|
|
|
|
2020-10-21 18:34:59 +02:00
|
|
|
const login = async () => {
|
2020-08-12 04:13:14 +02:00
|
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
|
|
const ticket = urlParams.get('ticket');
|
|
|
|
if (!ticket) {
|
|
|
|
redirectToCASLoginService();
|
|
|
|
}
|
2020-10-21 18:34:59 +02:00
|
|
|
try {
|
|
|
|
if (!sessionStorage.getItem('userToken')) {
|
2020-11-21 12:57:30 +01:00
|
|
|
const { data: token } = await axiosInstance.get(`${process.env.REACT_APP_API_URL}/token?ticket=${ticket}`);
|
2020-10-21 18:34:59 +02:00
|
|
|
sessionStorage.setItem('userToken', token);
|
|
|
|
}
|
|
|
|
const token = sessionStorage.getItem('userToken');
|
2020-11-21 04:02:38 +01:00
|
|
|
setToken(token);
|
2020-10-21 18:34:59 +02:00
|
|
|
} catch (e) {
|
|
|
|
console.log(e);
|
2020-08-12 04:13:14 +02:00
|
|
|
}
|
2020-10-21 18:34:59 +02:00
|
|
|
};
|
2020-08-12 04:13:14 +02:00
|
|
|
|
|
|
|
function logout() {
|
|
|
|
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
|
|
|
};
|