Skip to content

Commit

Permalink
feat(nuxt-base): initial adapter setup
Browse files Browse the repository at this point in the history
  • Loading branch information
BibiSebi committed Jun 25, 2024
1 parent 02443b9 commit 543f20d
Show file tree
Hide file tree
Showing 9 changed files with 246 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ export const sessionCookieStore: AppSessionCookieStoreFactory =
(params) =>
(requestParams): AppSessionStore => {
const getCookie: GetCookie = (name) =>
getNodeCookie(requestParams.req, name);
params.adapter.getItem({
req: requestParams.req,
res: requestParams.res,
key: name,
});
const setCookie: SetCookie = (name, value) =>
setNodeCookie(requestParams.res, name, value);
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,6 @@ export type AuthHandlerParams = {
* - `https://my-app.my-domain.com/api/authenticate/storyblok/callback` as the OAuth2 callback URL
*/
endpointPrefix: string | undefined; // To make explicit, do not make this optional.
//TODO: proper adapter type
adapter?: any;
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { type AuthHandlerParams } from './AuthHandlerParams';
import { getCookie } from '../utils';
import { handleAnyRequest } from './handle-requests';
import { reconcileNodeResponse } from './reconcileNodeResponse';
import { supabaseAdapter } from '~/app-extension-auth/storyblok-auth-api/createSupabaseClient';

/**
* Auth handler for Node.js
Expand All @@ -12,6 +13,9 @@ export const authHandler = (
params: AuthHandlerParams,
): http.RequestListener => {
return async (req, res) => {
//TODO: if no adapter save to cookies and console log warning about deprecation!
const adapter = supabaseAdapter;

const { url } = req;
if (typeof url !== 'string') {
res.writeHead(400).end();
Expand All @@ -21,6 +25,7 @@ export const authHandler = (
params,
url,
getCookie: (name) => getCookie(req, name),
adapter,
});
reconcileNodeResponse(res, responseElement);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { createClient } from '@supabase/supabase-js';

export const supabaseClient = createClient(
process.env.SUPABASE_URL || '',
process.env.SUPABASE_KEY || '',
);

type AppSession = {
appClientId: string;
userId: string | number;
spaceId: string | number;
refreshToken: string;
accessToken: string;
expiresAt: number;
roles: string[];
spaceName: string;
userName: string;
region: string;
};

type GetSessionParams = Pick<AppSession, 'spaceId' | 'userId' | 'appClientId'>;

type SetSession = (session: AppSession) => Promise<void>;
type GetSession = (params: GetSessionParams) => Promise<void>;

export type Adapter = {
getSession: GetSession;
setSession: SetSession;
};

// ADD: update session to supabase?
// ADD: isSessionValid?
export const createSupabaseClient = (url: string, key: string): Adapter => {
const supabaseClient = createClient(url || '', key || '');

const setSession: SetSession = async (session) => {
const {
spaceId,
spaceName,
userName,
userId,
region,
refreshToken,
roles,
expiresAt,
appClientId,
accessToken,
} = session;

const { data, error } = await supabaseClient
.from('session_kv_test')
.upsert({
space_id: spaceId,
user_id: userId,
app_client_id: appClientId,
key: 'session',
value: {
refresh_token: refreshToken,
access_token: accessToken,
expires_at: new Date(expiresAt).toISOString(),
roles,
space_name: spaceName,
user_name: userName,
region,
},
});

console.log('error', error);
};

const isSessionExpired = (session: AppSession) => {
session;
};

const getSession: GetSession = async (params) => {
//TODO: refresh session
const { spaceId, userId, appClientId } = params;
const { data, error } = await supabaseClient
.from('session_test')
.select()
.eq('space_id', spaceId)
.eq('user_id', userId)
.eq('app_client_id', appClientId);

console.log('error', error);
};

return {
getSession,
setSession,
};
};

const cookieAdapter = () => {
return {
getSession: null,
setSession: null,
};
};

export const supabaseAdapter = createSupabaseAdapter(
process.env.SUPABASE_URL || '',
process.env.SUPABASE_KEY || '',
);
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import { handleCallbackRequest } from '../handleCallback';
import { handleUnknownRequest } from '../handleUnknown';
import { getLastSlug } from './getLastSlug';
import { HandleAuthRequest } from '../HandleAuthRequest';
import type { Adapter } from '~/app-extension-auth/storyblok-auth-api/createSupabaseClient';

export const handleAnyRequest: HandleAuthRequest<{
params: AuthHandlerParams;
url: string;
getCookie: GetCookie;
}> = async ({ params, url, getCookie }) => {
adapter: Adapter;
}> = async ({ params, url, getCookie, adapter }) => {
if (!validateAppBaseUrl(params.baseUrl)) {
return {
type: 'configuration-error',
Expand All @@ -34,7 +36,7 @@ export const handleAnyRequest: HandleAuthRequest<{
case signinEndpoint:
return handleSignInRequest({ params });
case callbackEndpoint:
return handleCallbackRequest({ url, getCookie, params });
return handleCallbackRequest({ url, getCookie, params, adapter });
default:
return handleUnknownRequest({ params });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { AuthHandlerParams } from '../../AuthHandlerParams';
import { regionFromUrl } from './spaceIdFromUrl';
import { HandleAuthRequest } from '../HandleAuthRequest';
import { fetchAppSession } from './fetchAppSession';
import type { Adapter } from '~/app-extension-auth/storyblok-auth-api/createSupabaseClient';

export type AppSessionQueryParams = Record<
keyof Pick<AppSession, 'spaceId' | 'userId'>,
Expand All @@ -21,7 +22,8 @@ export const handleCallbackRequest: HandleAuthRequest<{
params: AuthHandlerParams;
url: string;
getCookie: GetCookie;
}> = async ({ params, url, getCookie }) => {
adapter: Adapter;
}> = async ({ params, url, getCookie, adapter }) => {
try {
const region = regionFromUrl(url);
if (!region) {
Expand Down Expand Up @@ -58,6 +60,8 @@ export const handleCallbackRequest: HandleAuthRequest<{
};
}

await adapter.setSession(appSession);

const queryParams: AppSessionQueryParams = {
spaceId: appSession.spaceId.toString(),
userId: appSession.userId.toString(),
Expand Down
11 changes: 5 additions & 6 deletions space-plugins/nuxt-base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,21 @@
"postinstall": "nuxt prepare"
},
"dependencies": {
"@storyblok/region-helper": "^1.1.0",
"@supabase/supabase-js": "^2.43.5",
"jsonwebtoken": "^9.0.0",
"openid-client": "^5.4.2",
"@storyblok/region-helper": "^1.1.0"
"openid-client": "^5.4.2"
},
"devDependencies": {
"@nuxt/devtools": "latest",
"@types/cookie": "^0.5.1",
"@types/cookies": "^0.7.7",
"@types/jsonwebtoken": "^8.5.8",
"@types/node": "14.18.47",
"dotenv": "^16.0.0",
"require": "^2.4.20",
"typescript": "^5.0.4",

"@nuxt/devtools": "latest",
"h3": "^1.8.2",
"nuxt": "3.11.1",
"require": "^2.4.20",
"typescript": "^5.1.3",
"vue": "^3.3.4",
"vue-router": "^4.2.5"
Expand Down
79 changes: 79 additions & 0 deletions space-plugins/nuxt-base/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 543f20d

Please sign in to comment.