Initial commit
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
import useAuthorizedApi from "./authorized-api";
|
||||
import {Album} from "../models/album";
|
||||
|
||||
const apiUrl = window._env_.REACT_APP_API_URL;
|
||||
|
||||
export default function useAlbumsApi() {
|
||||
const {get, post, patch, doDelete} = useAuthorizedApi();
|
||||
|
||||
return {
|
||||
fetchAlbums,
|
||||
postAlbum,
|
||||
patchAlbum,
|
||||
deleteAlbum,
|
||||
moveAlbumDown,
|
||||
moveAlbumUp,
|
||||
patchPhoto,
|
||||
uploadPhotos,
|
||||
deletePhoto,
|
||||
movePhotoDown,
|
||||
movePhotoUp,
|
||||
};
|
||||
|
||||
/**
|
||||
* @return {Promise<Album[]>}
|
||||
*/
|
||||
async function fetchAlbums(instance) {
|
||||
const response = await get(`${apiUrl}/api/instances/${instance.instanceId}/albums`);
|
||||
return response.data.map(album => new Album(album));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Instance} instance
|
||||
* @param {Album} album
|
||||
* @return {Promise<Album>}
|
||||
*/
|
||||
async function patchAlbum(instance, album) {
|
||||
const patches = [];
|
||||
if (album.name) {
|
||||
patches.push({op: "replace", path: "/name", value: album.name})
|
||||
}
|
||||
if (album.description) {
|
||||
patches.push({op: "replace", path: "/description", value: album.description})
|
||||
}
|
||||
if (album.sort) {
|
||||
patches.push({op: "replace", path: "/sort", value: album.sort})
|
||||
}
|
||||
if (patches.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const response = await patch(
|
||||
`${apiUrl}/api/instances/${instance.instanceId}/albums/${album.albumId}`,
|
||||
patches
|
||||
);
|
||||
return new Album(response.data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Instance} instance
|
||||
* @param {Album} album
|
||||
* @return {Promise<Album>}
|
||||
*/
|
||||
async function postAlbum(instance, album) {
|
||||
const response = await post(
|
||||
`${apiUrl}/api/instances/${instance.instanceId}/albums`, {
|
||||
name: album.name,
|
||||
description: album.description,
|
||||
sort: album.sort
|
||||
}
|
||||
);
|
||||
return new Album(response.data);
|
||||
}
|
||||
|
||||
async function deleteAlbum(instance, albumId) {
|
||||
const response = await doDelete(`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}`);
|
||||
return response.data.map(a => new Album(a));
|
||||
}
|
||||
|
||||
async function moveAlbumDown(instance, albumId) {
|
||||
const response = await post(`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/move-down`);
|
||||
return response.data.map(a => new Album(a));
|
||||
}
|
||||
|
||||
async function moveAlbumUp(instance, albumId) {
|
||||
const response = await post(`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/move-up`);
|
||||
return response.data.map(a => new Album(a));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Instance} instance
|
||||
* @param {string} albumId
|
||||
* @param {Photo} photo
|
||||
* @return {Promise<Album>}
|
||||
*/
|
||||
async function patchPhoto(instance, albumId, photo) {
|
||||
const patches = [];
|
||||
if (photo.name) {
|
||||
patches.push({op: "replace", path: "/name", value: photo.name})
|
||||
}
|
||||
if (photo.description) {
|
||||
patches.push({op: "replace", path: "/description", value: photo.description})
|
||||
}
|
||||
if (patches.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const response = await patch(
|
||||
`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/photos/${photo.photoId}`,
|
||||
patches
|
||||
);
|
||||
return new Album(response.data);
|
||||
}
|
||||
|
||||
async function uploadPhotos(instance, albumId, formData) {
|
||||
const response = await post(
|
||||
`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/upload-photos`,
|
||||
formData
|
||||
);
|
||||
return new Album(response.data);
|
||||
}
|
||||
|
||||
async function deletePhoto(instance, albumId, photoId) {
|
||||
const response = await doDelete(`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/photos/${photoId}`);
|
||||
return new Album(response.data);
|
||||
}
|
||||
|
||||
async function movePhotoDown(instance, albumId, photoId) {
|
||||
const response = await post(`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/photos/${photoId}/move-down`);
|
||||
return new Album(response.data);
|
||||
}
|
||||
|
||||
async function movePhotoUp(instance, albumId, photoId) {
|
||||
const response = await post(`${apiUrl}/api/instances/${instance.instanceId}/albums/${albumId}/photos/${photoId}/move-up`);
|
||||
return new Album(response.data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import React, {
|
||||
useState,
|
||||
useEffect,
|
||||
useRef,
|
||||
useMemo,
|
||||
useCallback,
|
||||
} from 'react';
|
||||
import {
|
||||
UserManager,
|
||||
} from 'oidc-client-ts';
|
||||
|
||||
export const AuthContext = React.createContext(
|
||||
undefined
|
||||
);
|
||||
|
||||
/**
|
||||
* @private
|
||||
* @hidden
|
||||
* @param {Location} location
|
||||
*/
|
||||
export const hasCodeInUrl = (location) => {
|
||||
const searchParams = new URLSearchParams(location.search);
|
||||
const hashParams = new URLSearchParams(location.hash.replace('#', '?'));
|
||||
|
||||
return (
|
||||
searchParams.has('code') ??
|
||||
searchParams.has('id_token') ??
|
||||
searchParams.has('session_state') ??
|
||||
hashParams.has('code') ??
|
||||
hashParams.has('id_token') ??
|
||||
hashParams.has('session_state')
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @private
|
||||
* @hidden
|
||||
* @param props
|
||||
*/
|
||||
export const initUserManager = (props) => {
|
||||
if (props.userManager) {
|
||||
return props.userManager;
|
||||
}
|
||||
|
||||
const {
|
||||
authority,
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri,
|
||||
silentRedirectUri,
|
||||
postLogoutRedirectUri,
|
||||
responseType,
|
||||
scope,
|
||||
automaticSilentRenew,
|
||||
loadUserInfo,
|
||||
popupWindowFeatures,
|
||||
popupRedirectUri,
|
||||
popupWindowTarget,
|
||||
extraQueryParams,
|
||||
metadata,
|
||||
} = props;
|
||||
return new UserManager({
|
||||
authority: authority ?? '',
|
||||
client_id: clientId ?? '',
|
||||
client_secret: clientSecret,
|
||||
redirect_uri: redirectUri ?? '',
|
||||
silent_redirect_uri: silentRedirectUri ?? redirectUri,
|
||||
post_logout_redirect_uri: postLogoutRedirectUri ?? redirectUri,
|
||||
response_type: responseType ?? 'code',
|
||||
scope: scope ?? 'authentication',
|
||||
loadUserInfo: loadUserInfo ?? true,
|
||||
popupWindowFeatures: popupWindowFeatures,
|
||||
popup_redirect_uri: popupRedirectUri,
|
||||
popupWindowTarget: popupWindowTarget,
|
||||
automaticSilentRenew,
|
||||
extraQueryParams,
|
||||
metadata: metadata,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param children
|
||||
* @param autoSignIn
|
||||
* @param autoSignInArgs
|
||||
* @param autoSignOut
|
||||
* @param autoSignOutArgs
|
||||
* @param onBeforeSignIn
|
||||
* @param onSignIn
|
||||
* @param onSignOut
|
||||
* @param location
|
||||
* @param onSignInError
|
||||
* @param props AuthProviderProps
|
||||
*/
|
||||
export const AuthProvider = ({
|
||||
children,
|
||||
autoSignIn = true,
|
||||
autoSignInArgs,
|
||||
autoSignOut = true,
|
||||
autoSignOutArgs,
|
||||
onBeforeSignIn,
|
||||
onSignIn,
|
||||
onSignOut,
|
||||
location = window.location,
|
||||
onSignInError,
|
||||
...props
|
||||
}) => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [userData, setUserData] = useState(null);
|
||||
const [userManager] = useState(() => initUserManager(props));
|
||||
const isMountedRef = useRef(false);
|
||||
|
||||
const signOutHooks = useCallback(async ()=> {
|
||||
setUserData(null);
|
||||
if (onSignOut) {
|
||||
await onSignOut();
|
||||
}
|
||||
}, [onSignOut]);
|
||||
const signInPopupHooks = useCallback(async ()=> {
|
||||
const userFromPopup = await userManager.signinPopup();
|
||||
setUserData(userFromPopup);
|
||||
if (onSignIn) {
|
||||
await onSignIn(userFromPopup);
|
||||
}
|
||||
await userManager.signinPopupCallback();
|
||||
}, [userManager, onSignIn]);
|
||||
|
||||
/**
|
||||
* Handles user auth flow on initial render.
|
||||
*/
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
isMountedRef.current = true;
|
||||
setIsLoading(true);
|
||||
void (async () => {
|
||||
if (!userManager) {
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await userManager.getUser();
|
||||
|
||||
// isMountedRef cannot be used here as its value is updated by next useEffect.
|
||||
// We intend to keep context of current useEffect.
|
||||
if (isMounted && (!user || user.expired)) {
|
||||
// If the user is returning back from the OIDC provider, get and set the user data.
|
||||
if (hasCodeInUrl(location)) {
|
||||
try {
|
||||
const user = await userManager.signinCallback();
|
||||
if (user) {
|
||||
setUserData(user);
|
||||
if (onSignIn) {
|
||||
await onSignIn(user);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (onSignInError) {
|
||||
onSignInError(error);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If autoSignIn is enabled, redirect to the OIDC provider.
|
||||
else if (autoSignIn) {
|
||||
const state = onBeforeSignIn ? onBeforeSignIn() : undefined;
|
||||
await userManager.signinRedirect({ ...autoSignInArgs, state });
|
||||
}
|
||||
}
|
||||
// Otherwise if the user is already signed in, set the user data.
|
||||
else if (isMountedRef.current) {
|
||||
setUserData(user);
|
||||
}
|
||||
setIsLoading(false);
|
||||
})();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
isMountedRef.current = false;
|
||||
};
|
||||
}, [
|
||||
location,
|
||||
userManager,
|
||||
autoSignIn,
|
||||
onBeforeSignIn,
|
||||
onSignIn,
|
||||
onSignInError,
|
||||
autoSignInArgs,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Registers UserManager event callbacks for handling changes to user state due to automaticSilentRenew, session expiry, etc.
|
||||
*/
|
||||
useEffect(() => {
|
||||
const updateUserData = (user) => {
|
||||
if (isMountedRef.current) {
|
||||
setUserData(user);
|
||||
}
|
||||
};
|
||||
const onSilentRenewError =
|
||||
async () => {
|
||||
if (autoSignOut) {
|
||||
await signOutHooks();
|
||||
await userManager.signoutRedirect(autoSignOutArgs);
|
||||
}
|
||||
};
|
||||
userManager.events.addUserLoaded(updateUserData);
|
||||
userManager.events.addSilentRenewError(onSilentRenewError);
|
||||
return () => {
|
||||
userManager.events.removeUserLoaded(updateUserData);
|
||||
userManager.events.removeSilentRenewError(onSilentRenewError);
|
||||
};
|
||||
}, [userManager, autoSignOut, signOutHooks, autoSignOutArgs]);
|
||||
|
||||
const value = useMemo(() => {
|
||||
return {
|
||||
signIn: async (args) => {
|
||||
await userManager.signinRedirect(args);
|
||||
},
|
||||
signInPopup: async () => {
|
||||
await signInPopupHooks();
|
||||
},
|
||||
signOut: async ()=> {
|
||||
await userManager.removeUser();
|
||||
await signOutHooks();
|
||||
},
|
||||
signOutRedirect: async (args) => {
|
||||
await userManager.signoutRedirect(args);
|
||||
await signOutHooks();
|
||||
},
|
||||
userManager,
|
||||
userData,
|
||||
isLoading,
|
||||
};
|
||||
}, [userManager, isLoading, userData, signInPopupHooks, signOutHooks]);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
};
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import {AuthProvider} from "./auth-context";
|
||||
|
||||
function keycloak({children}) {
|
||||
return <AuthProvider
|
||||
authority="https://keycloak.novox.be/realms/Novox"
|
||||
autoSignIn={false}
|
||||
scope="openid roles"
|
||||
loadUserInfo={true}
|
||||
clientId="photos"
|
||||
silentRedirectUri={`${window.location.protocol}//${window.location.host}/admin/signin-keycloak`}
|
||||
redirectUri={`${window.location.protocol}//${window.location.host}/admin/signin-keycloak`}
|
||||
postLogoutRedirectUri={`${window.location.protocol}//${window.location.host}/admin/signout-keycloak`}
|
||||
>
|
||||
{children}
|
||||
</AuthProvider>;
|
||||
}
|
||||
export default keycloak;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from './auth-context';
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
'AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component.',
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import {useAuth} from "./authentication/use-auth";
|
||||
|
||||
export default function useAuthorizedApi() {
|
||||
const {userData, signOut} = useAuth();
|
||||
return {
|
||||
get: request('GET'),
|
||||
post: request('POST'),
|
||||
put: request('PUT'),
|
||||
patch: request('PATCH'),
|
||||
doDelete: request('DELETE')
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string} method
|
||||
* @return {function(*, *): Promise<*>}
|
||||
*/
|
||||
function request(method) {
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {?any} [body]
|
||||
*/
|
||||
return async (url, body) => {
|
||||
/** @type {RequestInit} **/
|
||||
const requestOptions = {
|
||||
method,
|
||||
headers: authHeader(url)
|
||||
};
|
||||
if (body) {
|
||||
if (body instanceof FormData) {
|
||||
requestOptions.body = body;
|
||||
} else {
|
||||
requestOptions.headers['Content-Type'] = 'application/json';
|
||||
requestOptions.body = JSON.stringify(body);
|
||||
}
|
||||
}
|
||||
return handleResponse(await fetch(url, requestOptions));
|
||||
}
|
||||
}
|
||||
|
||||
function authHeader(url) {
|
||||
// return auth header with jwt if user is logged in and request is to the api url
|
||||
const token = userData?.access_token;
|
||||
const isLoggedIn = !!token;
|
||||
const isApiUrl = url.startsWith(window._env_.REACT_APP_API_URL);
|
||||
if (isLoggedIn && isApiUrl) {
|
||||
return {Authorization: `Bearer ${token}`};
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResponse(response) {
|
||||
const text = await response.text()
|
||||
|
||||
const data = text && JSON.parse(text);
|
||||
|
||||
if (!response.ok) {
|
||||
if ([401, 403].includes(response.status) && userData?.access_token) {
|
||||
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
|
||||
localStorage.removeItem('user');
|
||||
await signOut();
|
||||
}
|
||||
|
||||
const error = (data && data.message) || response.statusText;
|
||||
return Promise.reject(error);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import useAuthorizedApi from "../authorized-api";
|
||||
import {Instance} from "../../models/instance";
|
||||
import {useState} from "react";
|
||||
|
||||
const apiUrl = window._env_.REACT_APP_API_URL;
|
||||
|
||||
export default function useInstancesApi() {
|
||||
const {get, post, put, doDelete} = useAuthorizedApi();
|
||||
const [instanceApiError, setInstanceApiError] = useState(null);
|
||||
|
||||
const tryApiCall = async (func) => {
|
||||
try {
|
||||
return await func();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (typeof err === "string" && err.toLowerCase().indexOf("already exist") >= 0) {
|
||||
setInstanceApiError(err);
|
||||
} else if (typeof err === "string" && err.toLowerCase().indexOf("mimetype") >= 0) {
|
||||
setInstanceApiError(err);
|
||||
} else {
|
||||
setInstanceApiError("The API is currently unavailable, please contact the administrator");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const fetchInstances = async () => tryApiCall(async () => {
|
||||
const response = await get(`${apiUrl}/api/instances`);
|
||||
return response?.data.map(inst => new Instance(inst));
|
||||
});
|
||||
|
||||
const updateInstance = async (instance) => tryApiCall(async () => {
|
||||
const response = await put(`${apiUrl}/api/instances/${instance.instanceId}`, instance);
|
||||
return new Instance(response.data);
|
||||
});
|
||||
|
||||
const deleteInstance = async (instanceId) => tryApiCall(async () => {
|
||||
const response = await doDelete(`${apiUrl}/api/instances/${instanceId}`);
|
||||
return new Instance(response.data);
|
||||
});
|
||||
|
||||
const createInstance = (instance) => tryApiCall(async () => {
|
||||
const response = await post(`${apiUrl}/api/instances`, instance);
|
||||
return new Instance(response.data);
|
||||
});
|
||||
|
||||
const uploadCoverPhoto = (instanceId, formData) => tryApiCall(async () => {
|
||||
const response = await post(
|
||||
`${apiUrl}/api/instances/${instanceId}/upload-cover-photo`,
|
||||
formData
|
||||
);
|
||||
return new Instance(response.data);
|
||||
});
|
||||
|
||||
return {
|
||||
fetchInstances,
|
||||
updateInstance,
|
||||
deleteInstance,
|
||||
createInstance,
|
||||
uploadCoverPhoto,
|
||||
instanceApiError,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import React, {useEffect, useState} from "react";
|
||||
import useInstancesApi from "./instances-api";
|
||||
import {useAuth} from "../authentication/use-auth";
|
||||
import {useLocation, useNavigate} from "react-router-dom";
|
||||
import {Instance} from "../../models/instance";
|
||||
|
||||
export const InstancesContext = React.createContext(
|
||||
undefined
|
||||
);
|
||||
|
||||
export const InstancesProvider = ({children}) => {
|
||||
const navigate = useNavigate();
|
||||
const {pathname} = useLocation();
|
||||
const {userData} = useAuth();
|
||||
const {fetchInstances, createInstance, deleteInstance, updateInstance, uploadCoverPhoto, instanceApiError} = useInstancesApi();
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [instances, setInstances] = useState(undefined);
|
||||
const [selectedInstance, setSelectedInstance] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
void (async () => {
|
||||
if (userData && fetchInstances) {
|
||||
if (instances === undefined) {
|
||||
setIsLoading(true);
|
||||
const instances = await fetchInstances();
|
||||
setInstances(instances);
|
||||
setIsLoading(false);
|
||||
} else {
|
||||
const possibleSelectedInstance = pathname.split('/')[1];
|
||||
if(possibleSelectedInstance){
|
||||
const selectedInstance = instances?.find(inst => inst.instanceId === possibleSelectedInstance);
|
||||
if (selectedInstance) {
|
||||
setSelectedInstance(selectedInstance);
|
||||
} else {
|
||||
navigate("/");
|
||||
}
|
||||
} else {
|
||||
setSelectedInstance(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [navigate, pathname, userData, instances, fetchInstances]);
|
||||
|
||||
const handleCreateInstance = async (instance) => {
|
||||
const newInstance = await createInstance(instance);
|
||||
setInstances([...instances, newInstance]);
|
||||
}
|
||||
const handleUpdateInstance = async (instance) => {
|
||||
const updatedInstance = await updateInstance(instance);
|
||||
const idx = instances.findIndex(i => i.instanceId === updatedInstance.instanceId);
|
||||
instances[idx] = updatedInstance;
|
||||
setInstances([...instances]);
|
||||
return updatedInstance;
|
||||
}
|
||||
const handleUpdateCoverPhoto = async (instanceId, formData) => {
|
||||
const updatedInstance = await uploadCoverPhoto(instanceId, formData);
|
||||
const idx = instances.findIndex(i => i.instanceId === updatedInstance.instanceId);
|
||||
instances[idx] = updatedInstance;
|
||||
setInstances(instances.map(i => new Instance(i)));
|
||||
return updatedInstance;
|
||||
}
|
||||
|
||||
const value = {
|
||||
isLoading,
|
||||
instances,
|
||||
selectedInstance,
|
||||
setSelectedInstance,
|
||||
createInstance: handleCreateInstance,
|
||||
deleteInstance,
|
||||
updateInstance: handleUpdateInstance,
|
||||
uploadCoverPhoto: handleUpdateCoverPhoto,
|
||||
instanceApiError,
|
||||
};
|
||||
|
||||
return <InstancesContext.Provider value={value}>{children}</InstancesContext.Provider>;
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import {useContext} from "react";
|
||||
import {InstancesContext} from "./instances-context";
|
||||
|
||||
/**
|
||||
* @return {InstancesContext}
|
||||
*/
|
||||
export const useInstances = () => {
|
||||
const context = useContext(InstancesContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
'Instances context is undefined, please verify you are calling useInstances() as child of a <InstancesProvider> component.',
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user