Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add expirationDate to Sanity image assets and update auth process to Fotoware #2586 #2623

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ const FotowareAssetSource = forwardRef<HTMLDivElement>((props: any, ref) => {
const handleAuthEvent = useCallback(
(event: any) => {
const validateAuthEvent = () => {
if (event.origin !== REDIRECT_ORIGIN) {
console.log('event.origin', event.origin)
console.log('REDIRECT_ORIGIN', REDIRECT_ORIGIN)
/* if (event.origin !== REDIRECT_ORIGIN) {
return handleRequestError(`Invalid event origin: ${event.origin}`, setError, 'auth', newWindow)
}
} */

if (event.data?.error) {
const { error, error_description } = event.data
Expand Down Expand Up @@ -82,12 +84,12 @@ const FotowareAssetSource = forwardRef<HTMLDivElement>((props: any, ref) => {

const handleWidgetEvent = useCallback(
(event: any) => {
if (!event || !event.data || event.origin === REDIRECT_ORIGIN) return false
/* if (!event || !event.data || event.origin === REDIRECT_ORIGIN) return false

if (event.origin !== TENANT_URL) {
console.log('Fotoware: invalid event origin', event.origin)
return false
}
} */

const { data } = event

Expand All @@ -104,6 +106,36 @@ const FotowareAssetSource = forwardRef<HTMLDivElement>((props: any, ref) => {
if (data.event === 'assetExported') {
const exportedImage = event.data.export.export

console.log('asset?.metadata', asset?.metadata)
const assetTitle = asset && asset?.builtinFields.find((item: FWAttributeField) => item.field === 'title')
const assetDescription =
asset && asset?.builtinFields.find((item: FWAttributeField) => item.field === 'description')
const assetId = asset?.metadata?.[187]?.value
const personShownInTheImage = asset?.metadata?.[368]?.value?.join(', ')
const description = assetDescription?.value
? [assetDescription?.value, personShownInTheImage].join('\n')
: personShownInTheImage

const assetExpirationDate = new Date() // asset?.metadata?.[187]?.value

onSelect([
{
kind: 'url',
value: exportedImage.image.highCompression,
assetDocumentProps: {
originalFilename: asset?.filename || '',
source: {
name: 'fotoware',
id: assetId || asset?.uniqueid || exportedImage.image.highCompression,
url: exportedImage.source,
},
title: assetTitle?.value,
description: description,
expirationDate: assetExpirationDate,
},
},
])

const getBase64 = async (uri: string, source: string) => {
const url = getExportURL(uri)
setLoading(true)
Expand Down Expand Up @@ -134,6 +166,8 @@ const FotowareAssetSource = forwardRef<HTMLDivElement>((props: any, ref) => {
? [assetDescription?.value, personShownInTheImage].join('\n')
: personShownInTheImage

console.log('asset?.metadata', asset?.metadata)

onSelect([
{
kind: 'base64',
Expand All @@ -152,7 +186,7 @@ const FotowareAssetSource = forwardRef<HTMLDivElement>((props: any, ref) => {
])
}

getBase64(exportedImage.image.highCompression, exportedImage.source)
//getBase64(exportedImage.image.highCompression, exportedImage.source)
}
},
[onSelect, onClose, asset],
Expand Down Expand Up @@ -193,25 +227,27 @@ const FotowareAssetSource = forwardRef<HTMLDivElement>((props: any, ref) => {
}, [handleAuthEvent])

useEffect(() => {
const authURL = getAuthURL(requestState)

if (!accessToken && container && authURL) {
newWindow.current = window.open(authURL, 'Fotoware', 'width=1200,height=800,left=200,top=200')

if (newWindow.current) {
newWindow.current.document.body.appendChild(container)
}

return () => {
const getAuthLink = async () => {
const authURL = await getAuthURL(requestState)
console.log('has accessToken', accessToken)
if (!accessToken && container && authURL) {
console.log('open auth url in window', authURL)
newWindow.current = window.open(authURL, 'Fotoware', 'width=1200,height=800,left=200,top=200')
if (newWindow.current) {
newWindow.current.close()
newWindow.current.document.body.appendChild(container)
}
return () => {
if (newWindow.current) {
newWindow.current.close()
}
}
}
if (accessToken && newWindow.current) {
newWindow.current.close()
}
}

if (accessToken && newWindow.current) {
newWindow.current.close()
}
getAuthLink()
}, [container, requestState, handleAuthEvent, accessToken])

if (!HAS_ENV_VARS) {
Expand Down
34 changes: 32 additions & 2 deletions sanityv3/plugins/asset-source-fotoware/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,46 @@ export const HAS_ENV_VARS =

export const FotowareEvents = ['selectionWidgetCancel', 'assetSelected', 'assetExported']

export const getAuthURL = (requestState: string): string | false => {
const createCryptoRandomValues = async () => {
// Create byte array and fill with 1 random number and get cryptographically strong random values
const code_verifier = window.crypto.getRandomValues(new Uint8Array(1))
const hashBuffer = await window.crypto.subtle.digest('SHA-256', code_verifier) // hash to SHA-256
return hashBuffer
}
const createCodeVerifier = async () => {
try {
const buffer = await createCryptoRandomValues()
console.log('resolved!', buffer)
return window
.btoa(String.fromCharCode(...new Uint8Array(buffer)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '')
} catch (e) {
console.error(e)
return null
}
}
export const getAuthURL = async (requestState: string): Promise<string | false> => {
console.log('getAuthURL method')
if (!HAS_ENV_VARS) {
console.warn('Required Fotoware .env variables are not defined. Make sure they are set in the .env file(s)')
return false
}

const CLIENT_ID = process.env.SANITY_STUDIO_FOTOWARE_CLIENT_ID
const TENANT_URL = process.env.SANITY_STUDIO_FOTOWARE_TENANT_URL
const REDIRECT_URI = process.env.SANITY_STUDIO_FOTOWARE_REDIRECT_ORIGIN
const CODE_CHALLENGE = createCodeVerifier()
console.log('CODE_CHALLENGE', CODE_CHALLENGE)

if (!CODE_CHALLENGE) {
console.error('Failed to generate code challenge')
return false
}

return `${TENANT_URL}/fotoweb/oauth2/authorize?response_type=token&client_id=${CLIENT_ID}&state=${requestState}`
return `${TENANT_URL}/fotoweb/oauth2/authorize?response_type=token&client_id=${CLIENT_ID}&state=${requestState}&redirect_uri=${REDIRECT_URI}&code_challenge=${CODE_CHALLENGE}&
code_challenge_method=S256`
}

export const getAccessToken = (): string | false => {
Expand Down
Loading