frontend/src/contexts/CASProvider.tsx

56 lines
1.6 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect, createContext, ReactNode } from 'react';
2020-08-12 04:13:14 +02:00
import { User } from '../types';
import axios from 'axios';
2020-08-12 04:13:14 +02:00
export interface CASContext {
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
}
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) => {
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();
}, []);
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();
}
try {
if (!sessionStorage.getItem('userToken')) {
const { data: token } = await axios.get(`${process.env.REACT_APP_API_URL}/token?ticket=${ticket}`);
sessionStorage.setItem('userToken', token);
}
const token = sessionStorage.getItem('userToken');
2020-11-21 04:02:38 +01:00
setToken(token);
} catch (e) {
console.log(e);
2020-08-12 04:13:14 +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
};