bento-auth-js
Version:
Authentication library for web applications of Bento-Platform
63 lines • 2.89 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
// Async actions using createAsyncThunk
export const fetchOpenIdConfiguration = createAsyncThunk("openIdConfig/fetchOpenIdConfiguration", (openIdConfigUrl_1, _a) => __awaiter(void 0, [openIdConfigUrl_1, _a], void 0, function* (openIdConfigUrl, { rejectWithValue }) {
const response = yield fetch(openIdConfigUrl);
if (response.ok) {
return yield response.json();
}
else {
return rejectWithValue("Could not fetch identity provider configuration");
}
}), {
condition: (_, { getState }) => {
const state = getState();
const { isFetching, data, expiry } = state.openIdConfiguration;
return !isFetching && (!data || !expiry || Date.now() > expiry * 1000);
},
});
export const fetchOpenIdConfigurationIfNecessary = (openIdConfigUrl) => (dispatch, getState) => __awaiter(void 0, void 0, void 0, function* () {
const { isFetching, expiry } = getState().openIdConfiguration;
if (isFetching || (expiry && Date.now() < expiry * 1000))
return;
return dispatch(fetchOpenIdConfiguration(openIdConfigUrl));
});
const initialState = {
isFetching: false,
hasAttempted: false,
data: undefined,
expiry: undefined,
};
export const openIdConfigSlice = createSlice({
name: "openIdConfiguration",
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchOpenIdConfiguration.pending, (state) => {
state.isFetching = true;
});
builder.addCase(fetchOpenIdConfiguration.fulfilled, (state, { payload }) => {
state.isFetching = false;
state.hasAttempted = true;
state.data = payload;
state.expiry = Date.now() / 1000 + 3 * 60 * 60; // Cache for 3 hours
});
builder.addCase(fetchOpenIdConfiguration.rejected, (state, { error }) => {
console.error(error);
state.isFetching = false;
state.hasAttempted = true;
state.data = undefined;
state.expiry = undefined;
});
},
});
export default openIdConfigSlice.reducer;
//# sourceMappingURL=openIdConfigSlice.js.map