feat: oauth-based login (#7)
This commit is contained in:
@@ -4,8 +4,13 @@ import { MAX_RESPONSE_SEGMENTS, MAX_TOKENS } from '~/lib/.server/llm/constants';
|
||||
import { CONTINUE_PROMPT } from '~/lib/.server/llm/prompts';
|
||||
import { streamText, type Messages, type StreamingOptions } from '~/lib/.server/llm/stream-text';
|
||||
import SwitchableStream from '~/lib/.server/llm/switchable-stream';
|
||||
import { handleWithAuth } from '~/lib/.server/login';
|
||||
|
||||
export async function action({ context, request }: ActionFunctionArgs) {
|
||||
export async function action(args: ActionFunctionArgs) {
|
||||
return handleWithAuth(args, chatAction);
|
||||
}
|
||||
|
||||
async function chatAction({ context, request }: ActionFunctionArgs) {
|
||||
const { messages } = await request.json<{ messages: Messages }>();
|
||||
|
||||
const stream = new SwitchableStream();
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { StreamingTextResponse, parseStreamPart } from 'ai';
|
||||
import { streamText } from '~/lib/.server/llm/stream-text';
|
||||
import { handleWithAuth } from '~/lib/.server/login';
|
||||
import { stripIndents } from '~/utils/stripIndent';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
export async function action({ context, request }: ActionFunctionArgs) {
|
||||
export async function action(args: ActionFunctionArgs) {
|
||||
return handleWithAuth(args, enhancerAction);
|
||||
}
|
||||
|
||||
async function enhancerAction({ context, request }: ActionFunctionArgs) {
|
||||
const { message } = await request.json<{ message: string }>();
|
||||
|
||||
try {
|
||||
|
||||
@@ -3,49 +3,96 @@ import {
|
||||
redirect,
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
type TypedResponse,
|
||||
redirectDocument,
|
||||
} from '@remix-run/cloudflare';
|
||||
import { Form, useActionData } from '@remix-run/react';
|
||||
import { verifyPassword } from '~/lib/.server/login';
|
||||
import { createUserSession, isAuthenticated } from '~/lib/.server/sessions';
|
||||
|
||||
interface Errors {
|
||||
password?: string;
|
||||
}
|
||||
import { useFetcher, useLoaderData } from '@remix-run/react';
|
||||
import { auth, type AuthAPI } from '@webcontainer/api';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { createUserSession, isAuthenticated, validateAccessToken } from '~/lib/.server/sessions';
|
||||
import { request as doRequest } from '~/lib/fetch';
|
||||
import { CLIENT_ID, CLIENT_ORIGIN } from '~/lib/constants';
|
||||
import { logger } from '~/utils/logger';
|
||||
|
||||
export async function loader({ request, context }: LoaderFunctionArgs) {
|
||||
const authenticated = await isAuthenticated(request, context.cloudflare.env);
|
||||
const { authenticated, response } = await isAuthenticated(request, context.cloudflare.env);
|
||||
|
||||
if (authenticated) {
|
||||
return redirect('/');
|
||||
return redirect('/', response);
|
||||
}
|
||||
|
||||
return json({});
|
||||
const url = new URL(request.url);
|
||||
|
||||
return json(
|
||||
{
|
||||
redirected: url.searchParams.has('code') || url.searchParams.has('error'),
|
||||
},
|
||||
response,
|
||||
);
|
||||
}
|
||||
|
||||
export async function action({ request, context }: ActionFunctionArgs): Promise<TypedResponse<{ errors?: Errors }>> {
|
||||
export async function action({ request, context }: ActionFunctionArgs) {
|
||||
const formData = await request.formData();
|
||||
const password = String(formData.get('password'));
|
||||
|
||||
const errors: Errors = {};
|
||||
const payload = {
|
||||
access: String(formData.get('access')),
|
||||
refresh: String(formData.get('refresh')),
|
||||
};
|
||||
|
||||
if (!password) {
|
||||
errors.password = 'Please provide a password';
|
||||
let response: Awaited<ReturnType<typeof doRequest>> | undefined;
|
||||
|
||||
try {
|
||||
response = await doRequest(`${CLIENT_ORIGIN}/oauth/token/info`, {
|
||||
headers: { authorization: `Bearer ${payload.access}` },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await response.json();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Authentication failure');
|
||||
logger.warn(error);
|
||||
|
||||
return json({ error: 'invalid-token' as const }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!verifyPassword(password, context.cloudflare.env)) {
|
||||
errors.password = 'Invalid password';
|
||||
const boltEnabled = validateAccessToken(payload.access);
|
||||
|
||||
if (!boltEnabled) {
|
||||
return json({ error: 'bolt-access' as const }, { status: 401 });
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
return json({ errors });
|
||||
}
|
||||
const tokenInfo: { expires_in: number; created_at: number } = await response.json();
|
||||
|
||||
return redirect('/', await createUserSession(request, context.cloudflare.env));
|
||||
const init = await createUserSession(request, context.cloudflare.env, { ...payload, ...tokenInfo });
|
||||
|
||||
return redirectDocument('/', init);
|
||||
}
|
||||
|
||||
type LoginState =
|
||||
| {
|
||||
kind: 'error';
|
||||
error: string;
|
||||
description: string;
|
||||
}
|
||||
| { kind: 'pending' };
|
||||
|
||||
const ERRORS = {
|
||||
'bolt-access': 'You do not have access to Bolt.',
|
||||
'invalid-token': 'Authentication failed.',
|
||||
};
|
||||
|
||||
export default function Login() {
|
||||
const actionData = useActionData<typeof action>();
|
||||
const { redirected } = useLoaderData<typeof loader>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!import.meta.hot?.data.wcAuth) {
|
||||
auth.init({ clientId: CLIENT_ID, scope: 'public', editorOrigin: CLIENT_ORIGIN });
|
||||
}
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.wcAuth = true;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
@@ -53,38 +100,93 @@ export default function Login() {
|
||||
<div>
|
||||
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">Login</h2>
|
||||
</div>
|
||||
<Form className="mt-8 space-y-6" method="post" noValidate>
|
||||
<div>
|
||||
<label htmlFor="password" className="sr-only">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
data-1p-ignore
|
||||
required
|
||||
className="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none"
|
||||
placeholder="Password"
|
||||
/>
|
||||
{actionData?.errors?.password ? (
|
||||
<em className="flex items-center space-x-1.5 p-2 mt-2 bg-negative-200 text-negative-600 rounded-lg">
|
||||
<div className="i-ph:x-circle text-xl"></div>
|
||||
<span>{actionData?.errors.password}</span>
|
||||
</em>
|
||||
) : null}
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full text-white bg-accent-600 hover:bg-accent-700 focus:ring-4 focus:outline-none font-medium rounded-lg text-sm px-5 py-2.5 text-center"
|
||||
>
|
||||
Login
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
{redirected ? 'Processing auth...' : <LoginForm />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginForm() {
|
||||
const [login, setLogin] = useState<LoginState | null>(null);
|
||||
|
||||
const fetcher = useFetcher<typeof action>();
|
||||
|
||||
useEffect(() => {
|
||||
auth.logout({ ignoreRevokeError: true });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.error) {
|
||||
auth.logout({ ignoreRevokeError: true });
|
||||
|
||||
setLogin({
|
||||
kind: 'error' as const,
|
||||
...{ error: fetcher.data.error, description: ERRORS[fetcher.data.error] },
|
||||
});
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
async function attemptLogin() {
|
||||
startAuthFlow();
|
||||
|
||||
function startAuthFlow() {
|
||||
auth.startAuthFlow({ popup: true });
|
||||
|
||||
Promise.race([authEvent(auth, 'auth-failed'), auth.loggedIn()]).then((error) => {
|
||||
if (error) {
|
||||
setLogin({ kind: 'error', ...error });
|
||||
} else {
|
||||
onTokens();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function onTokens() {
|
||||
const tokens = auth.tokens()!;
|
||||
|
||||
fetcher.submit(tokens, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
setLogin({ kind: 'pending' });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className="w-full text-white bg-accent-600 hover:bg-accent-700 focus:ring-4 focus:outline-none font-medium rounded-lg text-sm px-5 py-2.5 text-center"
|
||||
onClick={attemptLogin}
|
||||
disabled={login?.kind === 'pending'}
|
||||
>
|
||||
{login?.kind === 'pending' ? 'Authenticating...' : 'Continue with StackBlitz'}
|
||||
</button>
|
||||
|
||||
{login?.kind === 'error' && (
|
||||
<div>
|
||||
<h2>
|
||||
<code>{login.error}</code>
|
||||
</h2>
|
||||
<p>{login.description}</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface AuthError {
|
||||
error: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
function authEvent(auth: AuthAPI, event: 'logged-out'): Promise<void>;
|
||||
function authEvent(auth: AuthAPI, event: 'auth-failed'): Promise<AuthError>;
|
||||
function authEvent(auth: AuthAPI, event: 'logged-out' | 'auth-failed') {
|
||||
return new Promise((resolve) => {
|
||||
const unsubscribe = auth.on(event as any, (arg: any) => {
|
||||
unsubscribe();
|
||||
resolve(arg);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
10
packages/bolt/app/routes/logout.tsx
Normal file
10
packages/bolt/app/routes/logout.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { LoaderFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { logout } from '~/lib/.server/sessions';
|
||||
|
||||
export async function loader({ request, context }: LoaderFunctionArgs) {
|
||||
return logout(request, context.cloudflare.env);
|
||||
}
|
||||
|
||||
export default function Logout() {
|
||||
return '';
|
||||
}
|
||||
Reference in New Issue
Block a user