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 Firebase adapter #3266

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
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
12 changes: 6 additions & 6 deletions docs/data/toolpad/studio/reference/api/get-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ This describes a certain context under which a backend function was called.

**Properties**

| Name | Type | Description |
| :---------- | :------------------------------------------- | :---------------------------------------------------------------------------------- |
| `cookies` | `Record<string, string>` | A dictionary mapping cookie name to cookie value. |
| `setCookie` | `(name: string, value: string) => void` | Use to set a cookie `name` with `value`. |
| `session` | `{ user: ServerContextSessionUser } \| null` | Get current [authenticated](/toolpad/studio/concepts/authentication/) session data. |
| Name | Type | Description |
| :---------- | :-------------------------------------- | :---------------------------------------------------------------------------------- |
| `cookies` | `Record<string, string>` | A dictionary mapping cookie name to cookie value. |
| `setCookie` | `(name: string, value: string) => void` | Use to set a cookie `name` with `value`. |
| `session` | `{ user: SessionUser } \| null` | Get current [authenticated](/toolpad/studio/concepts/authentication/) session data. |

### ServerContextSessionUser
### SessionUser

**Properties**

Expand Down
3 changes: 2 additions & 1 deletion packages/toolpad-studio-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"url": "https://github.com/mui/mui-toolpad/issues"
},
"dependencies": {
"@auth/core": "0.25.1",
"@auth/core": "0.27.0",
"@auth/firebase-adapter": "1.4.0",
"@mui/material": "5.15.14",
"@tanstack/react-query": "5.18.1",
"@toolpad/utils": "workspace:*",
Expand Down
55 changes: 50 additions & 5 deletions packages/toolpad-studio-runtime/src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,65 @@
import type express from 'express';
import { JWT, getToken } from '@auth/core/jwt';
import { getToken } from '@auth/core/jwt';
import { adaptRequestFromExpressToFetch } from '@toolpad/utils/httpApiAdapters';
import { FirestoreAdapter } from '@auth/firebase-adapter';
import * as cookie from 'cookie';

export async function getUserToken(req: express.Request): Promise<JWT | null> {
let token = null;
interface SessionUser {
name?: string | null;
email?: string | null;
avatar?: string | null;
roles?: string[];
}

export type Session = { user: SessionUser } | null;

export async function getSession(req: express.Request): Promise<Session | null> {
const session = null;
if (process.env.TOOLPAD_AUTH_SECRET) {
const firebaseAdapter = FirestoreAdapter();

if (process.env.GOOGLE_APPLICATION_CREDENTIALS && firebaseAdapter.getSessionAndUser) {
const parsedCookies = cookie.parse(req.headers.cookie ?? '');

const sessionToken = parsedCookies['authjs.session-token'];

const firebaseSessionAndUser = sessionToken
? await firebaseAdapter.getSessionAndUser(sessionToken)
: null;

return (
firebaseSessionAndUser && {
user: {
name: firebaseSessionAndUser.user.name,
email: firebaseSessionAndUser.user.email,
avatar: firebaseSessionAndUser.user.image,
roles: [],
},
}
);
}

const request = adaptRequestFromExpressToFetch(req);

// @TODO: Library types are wrong as salt should not be required, remove once fixed
// Github discussion: https://github.com/nextauthjs/next-auth/discussions/9133
// @ts-ignore
token = await getToken({
const token = await getToken({
req: request,
secret: process.env.TOOLPAD_AUTH_SECRET,
});

return (
token && {
user: {
name: token.name,
email: token.email,
avatar: token.picture,
roles: token.roles,
},
}
);
}

return token;
return session;
}
21 changes: 3 additions & 18 deletions packages/toolpad-studio-runtime/src/serverRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,7 @@ import { IncomingMessage, ServerResponse } from 'node:http';
import * as cookie from 'cookie';
import { isWebContainer } from '@webcontainer/env';
import type express from 'express';
import { getUserToken } from './auth';

interface ServerContextSessionUser {
name?: string | null;
email?: string | null;
avatar?: string | null;
roles?: string[];
}
import { getSession, Session } from './auth';

export interface ServerContext {
/**
Expand All @@ -24,7 +17,7 @@ export interface ServerContext {
/**
* Data about current authenticated session.
*/
session: { user: ServerContextSessionUser } | null;
session: Session;
}

const contextStore = new AsyncLocalStorage<ServerContext>();
Expand All @@ -39,15 +32,7 @@ export async function createServerContext(
): Promise<ServerContext> {
const cookies = cookie.parse(req.headers.cookie || '');

const token = await getUserToken(req as express.Request);
const session = token && {
user: {
name: token.name,
email: token.email,
avatar: token.picture,
roles: token.roles,
},
};
const session = await getSession(req as express.Request);

return {
cookies,
Expand Down
4 changes: 3 additions & 1 deletion packages/toolpad-studio/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
}
},
"dependencies": {
"@auth/core": "0.25.1",
"@auth/core": "0.27.0",
"@auth/firebase-adapter": "1.4.0",
"@emotion/cache": "11.11.0",
"@emotion/react": "11.11.3",
"@emotion/server": "11.11.0",
Expand Down Expand Up @@ -86,6 +87,7 @@
"execa": "8.0.1",
"express": "4.18.2",
"find-up": "7.0.0",
"firebase-admin": "12.0.0",
"fractional-indexing": "3.2.0",
"get-port": "7.0.0",
"glob": "10.3.10",
Expand Down
8 changes: 7 additions & 1 deletion packages/toolpad-studio/src/runtime/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,13 @@ export function useAuth({ dom, basename, signInPagePath }: UseAuthInput): AuthPa
},
});
if (isResponseJSON(sessionResponse)) {
setSession(await sessionResponse.json());
const currentSession = await sessionResponse.json();

setSession(currentSession);

if (!currentSession) {
signOut();
}
} else {
signOut();
}
Expand Down
15 changes: 8 additions & 7 deletions packages/toolpad-studio/src/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import { Auth } from '@auth/core';
import GithubProvider, { GitHubEmail, GitHubProfile } from '@auth/core/providers/github';
import GoogleProvider from '@auth/core/providers/google';
import AzureADProvider from '@auth/core/providers/azure-ad';
import { FirestoreAdapter } from '@auth/firebase-adapter';
import CredentialsProvider from '@auth/core/providers/credentials';
import { AuthConfig, TokenSet } from '@auth/core/types';
import { OAuthConfig } from '@auth/core/providers';
import chalk from 'chalk';
import * as appDom from '@toolpad/studio-runtime/appDom';
import { adaptRequestFromExpressToFetch } from '@toolpad/utils/httpApiAdapters';
import { getUserToken } from '@toolpad/studio-runtime/auth';
import { getSession } from '@toolpad/studio-runtime/auth';
import { asyncHandler } from '../utils/express';
import type { ToolpadProject } from './localMode';

Expand Down Expand Up @@ -163,6 +164,8 @@ export function createAuthHandler(project: ToolpadProject): Router {
},
});

const firebaseAdapter = FirestoreAdapter();

const authConfig: AuthConfig = {
basePath: `${base}/api/auth`,
pages: {
Expand All @@ -172,6 +175,7 @@ export function createAuthHandler(project: ToolpadProject): Router {
verifyRequest: base,
},
providers: [githubProvider, googleProvider, azureADProvider, credentialsProvider],
adapter: firebaseAdapter,
secret: process.env.TOOLPAD_AUTH_SECRET,
trustHost: true,
callbacks: {
Expand Down Expand Up @@ -231,12 +235,9 @@ export function createAuthHandler(project: ToolpadProject): Router {

return token;
},
// @TODO: Types for session callback are broken as it says token does not exist but it does
// Github issue: https://github.com/nextauthjs/next-auth/issues/9437
// @ts-ignore
session({ session, token }) {
if (session.user) {
session.user.roles = token.roles ?? [];
session.user.roles = token?.roles ?? [];
}

return session;
Expand Down Expand Up @@ -289,8 +290,8 @@ export async function createRequireAuthMiddleware(project: ToolpadProject) {
!requestPath.startsWith(signInPath) &&
!requestPath.startsWith(editorPath)
) {
const token = await getUserToken(req);
if (!token) {
const session = await getSession(req);
if (!session) {
isAuthorized = false;
}
}
Expand Down
12 changes: 7 additions & 5 deletions packages/toolpad-studio/src/server/localMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,8 @@ export function getRequiredEnvVars(dom: appDom.AppDom): Set<string> {
return new Set(allVars);
}

const PRO_AUTH_PROVIDERS = ['azure-ad'];

interface PaidFeature {
id: string;
label: string;
Expand All @@ -985,13 +987,13 @@ function detectPaidFeatures(application: Application): PaidFeature[] | null {
}

const hasRoles = Boolean(application?.spec?.authorization?.roles);
const hasAzureActiveDirectory = application?.spec?.authentication?.providers?.some(
(elems) => elems.provider === 'azure-ad',
const hasProAuthProvider = application?.spec?.authentication?.providers?.some((elems) =>
PRO_AUTH_PROVIDERS.includes(elems.provider),
);
const paidFeatures = [
hasRoles ? { id: 'roles', label: 'Role based access control' } : undefined,
hasAzureActiveDirectory
? { id: 'azure-ad', label: 'Azure AD authentication provider' }
hasRoles ? { id: 'roles', label: 'Role-based access control' } : undefined,
hasProAuthProvider
? { id: 'pro-auth-provider', label: 'Some of your active authentication providers' }
: undefined,
].filter(Boolean) as PaidFeature[];
return paidFeatures.length > 0 ? paidFeatures : null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export function AppAuthenticationEditor() {
{!isPaidPlan ? (
<UpgradeAlert
type="error"
feature="Using authentication with a few specific providers (like Azure Active Directory)"
feature="Using authentication with a few specific providers (Azure AD)"
sx={{ position: 'absolute', bottom: (theme) => theme.spacing(4) }}
/>
) : (
Expand Down
Loading
Loading