remind me to refactor form stuff

This commit is contained in:
Skye 2022-11-26 01:11:30 +09:00
commit 0425586027
Signed by: me
GPG key ID: 0104BC05F41B77B8
41 changed files with 3670 additions and 0 deletions

13
.eslintignore Normal file
View file

@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

20
.eslintrc.cjs Normal file
View file

@ -0,0 +1,20 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
plugins: ['svelte3', '@typescript-eslint'],
ignorePatterns: ['*.cjs'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
es2017: true,
node: true
}
};

10
.gitignore vendored Normal file
View file

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View file

@ -0,0 +1 @@
engine-strict=true

13
.prettierignore Normal file
View file

@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

9
.prettierrc Normal file
View file

@ -0,0 +1,9 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"pluginSearchDirs": ["."],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

38
README.md Normal file
View file

@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

47
package.json Normal file
View file

@ -0,0 +1,47 @@
{
"name": "-rkesl-s",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"test": "playwright test",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --plugin-search-dir . --check . && eslint .",
"format": "prettier --plugin-search-dir . --write ."
},
"devDependencies": {
"@playwright/test": "1.25.0",
"@sveltejs/adapter-auto": "next",
"@sveltejs/adapter-node": "^1.0.0-next.101",
"@sveltejs/kit": "next",
"@tailwindcss/forms": "^0.5.2",
"@typescript-eslint/eslint-plugin": "^5.27.0",
"@typescript-eslint/parser": "^5.27.0",
"autoprefixer": "^10.4.7",
"daisyui": "^2.18.1",
"eslint": "^8.16.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-svelte3": "^4.0.0",
"postcss": "^8.4.14",
"postcss-load-config": "^4.0.1",
"prettier": "^2.6.2",
"prettier-plugin-svelte": "^2.7.0",
"svelte": "^3.44.0",
"svelte-check": "^2.7.1",
"svelte-preprocess": "^4.10.7",
"tailwindcss": "^3.1.5",
"tslib": "^2.3.1",
"typescript": "^4.7.4",
"vite": "^3.1.0"
},
"type": "module",
"dependencies": {
"@ory/client": "^0.2.0-alpha.60",
"@ory/hydra-client": "^2.0.2",
"@ory/integrations": "^0.2.8",
"svelte-i18n": "^3.5.2"
}
}

10
playwright.config.ts Normal file
View file

@ -0,0 +1,10 @@
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
webServer: {
command: 'npm run build && npm run preview',
port: 4173
}
};
export default config;

13
postcss.config.cjs Normal file
View file

@ -0,0 +1,13 @@
const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');
const config = {
plugins: [
//Some plugins, like tailwindcss/nesting, need to run before Tailwind,
tailwindcss(),
//But others, like autoprefixer, need to run after,
autoprefixer
]
};
module.exports = config;

9
src/app.d.ts vendored Normal file
View file

@ -0,0 +1,9 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
// interface Locals {}
// interface PageData {}
// interface Error {}
// interface Platform {}
}

12
src/app.html Normal file
View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body>
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

4
src/app.postcss Normal file
View file

@ -0,0 +1,4 @@
/* Write your global styles here, in PostCSS syntax */
@tailwind base;
@tailwind components;
@tailwind utilities;

10
src/hooks.server.ts Normal file
View file

@ -0,0 +1,10 @@
import type { Handle } from '@sveltejs/kit';
import { locale } from 'svelte-i18n';
export const handle: Handle = async ({ event, resolve }) => {
const lang = event.request.headers.get('accept-language')?.split(',')[0];
if (lang) {
locale.set(lang);
}
return resolve(event);
};

11
src/lib/i18n/index.ts Normal file
View file

@ -0,0 +1,11 @@
import { browser } from '$app/environment';
import { init, register } from 'svelte-i18n';
const defaultLocale = 'en';
register('en', () => import('./locales/en.json'));
init({
fallbackLocale: defaultLocale,
initialLocale: browser ? window.navigator.language : defaultLocale
});

View file

@ -0,0 +1,4 @@
{
"oidc.scope.email": "Your Email Address",
"oidc.scope.profile": "Your Account Profile"
}

View file

@ -0,0 +1,18 @@
import { env } from '$env/dynamic/private';
import { Configuration as HydraConfiguration, OAuth2Api } from '@ory/hydra-client';
import { Configuration as KratosConfiguration, V0alpha2Api, ReadApi } from '@ory/client';
export const HydraAdminApi = new OAuth2Api(
new HydraConfiguration({
basePath: env.HYDRA_ADMIN_API
})
);
export const KratosAdminApi = new V0alpha2Api(
new KratosConfiguration({
basePath: env.KRATOS_ADMIN_API
})
);
export const KratosPublicApi = new V0alpha2Api(
new KratosConfiguration({
basePath: env.KRATOS_PUBLIC_API
})
);

3
src/lib/server/config.ts Normal file
View file

@ -0,0 +1,3 @@
import { env } from '$env/dynamic/private';
export const DEFAULT_REDIRECT_URL = env.DEFAULT_REDIRECT_URL ?? '';
export const KRATOS_PUBLIC_URL = env.KRATOS_PUBLIC_URL ?? '';

View file

@ -0,0 +1,6 @@
<script>
import '../app.postcss';
import '../app.postcss';
</script>
<slot />

11
src/routes/+layout.ts Normal file
View file

@ -0,0 +1,11 @@
import { browser } from '$app/environment';
import '$lib/i18n';
import { locale, waitLocale } from 'svelte-i18n';
import type { LayoutLoad } from './$types';
export const load: LayoutLoad = async () => {
if (browser) {
locale.set(window.navigator.language);
}
await waitLocale();
};

View file

@ -0,0 +1,24 @@
import type { PageServerLoad } from './$types';
import { KratosPublicApi } from '$lib/server/APIClients.js';
export const load: PageServerLoad = async ({ request }) => {
try {
const current_user = await KratosPublicApi.toSession(
undefined,
request.headers.get('Cookie') ?? undefined
);
return {
logged_in: true,
logout_url: (
await KratosPublicApi.createSelfServiceLogoutFlowUrlForBrowsers(
request.headers.get('Cookie') ?? undefined
)
).data.logout_url,
username: current_user.data.identity.traits.username
};
} catch (error) {
return {
logged_in: false
};
}
};

20
src/routes/+page.svelte Normal file
View file

@ -0,0 +1,20 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center bg-base-100">
<ul class="place-self-center menu max-w-sm p-3 rounded-box shadow-xl bg-base-200 text-lg">
{#if data.logged_in}
<li class="menu-title">
<span>Hello {data.username}!</span>
</li>
<li><a href="/settings">Account Settings</a></li>
<li><a href="/verification">Email Verification</a></li>
<li><a href={data.logout_url}>Log Out</a></li>
{:else}
<li><a href="/login">Log In</a></li>
<li><a href="/signup">Sign Up</a></li>
{/if}
</ul>
</div>

View file

@ -0,0 +1,80 @@
import type { Actions, PageServerLoad } from './$types';
import { HydraAdminApi, KratosAdminApi } from '$lib/server/APIClients.js';
import { error, redirect } from '@sveltejs/kit';
import type { AxiosResponse } from 'axios';
import type { Identity } from '@ory/client';
import type { OAuth2ConsentRequest } from '@ory/hydra-client';
export const load: PageServerLoad = async ({ url }) => {
const consent_challenge = url.searchParams.get('consent_challenge');
if (consent_challenge == undefined) {
throw error(400, 'Expected consent_challenge');
}
const consent_request = await HydraAdminApi.getOAuth2ConsentRequest(consent_challenge);
if (consent_request.data.subject == undefined) {
throw error(500, 'Could not get your identity');
}
const user = await KratosAdminApi.adminGetIdentity(consent_request.data.subject);
if (consent_request.data.skip) {
await acceptRequest(consent_request, user, consent_challenge);
}
if (consent_request.data.requested_scope == undefined) {
throw error(500, 'Could not get requested scopes');
}
return {
challenge: consent_challenge,
username: user.data.traits.username,
appname: consent_request.data.client?.client_name,
scopes: consent_request.data.requested_scope.filter((e) => e != 'openid')
};
};
export const actions: Actions = {
approve: async ({ request }) => {
const consent_challenge = (await request.formData()).get('consent_challenge');
if (typeof consent_challenge != 'string') {
throw error(400, 'consent_challenge is invalid');
}
const consent_request = await HydraAdminApi.getOAuth2ConsentRequest(consent_challenge);
if (consent_request.data.subject == undefined) {
throw error(500, 'Could not get your identity');
}
const user = await KratosAdminApi.adminGetIdentity(consent_request.data.subject);
await acceptRequest(consent_request, user, consent_challenge);
},
deny: async ({ request }) => {
const consent_challenge = (await request.formData()).get('consent_challenge');
if (typeof consent_challenge != 'string') {
throw error(400, 'consent_challenge is invalid');
}
const response = await HydraAdminApi.rejectOAuth2ConsentRequest(consent_challenge, {
error: 'access_denied',
error_description: 'The resource owner denied the request'
});
throw redirect(303, response.data.redirect_to);
}
};
async function acceptRequest(
consent_request: AxiosResponse<OAuth2ConsentRequest>,
user: AxiosResponse<Identity>,
consent_challenge: string
) {
let extra_grants: Record<string, any> = {};
if (consent_request.data.requested_scope?.includes('email')) {
extra_grants.email = user.data.traits.email;
extra_grants.email_verified =
user.data.verifiable_addresses?.find((e) => e.value == user.data.traits.email)?.verified ==
true;
}
// Put more scopes here if needs arise
let response = await HydraAdminApi.acceptOAuth2ConsentRequest(consent_challenge, {
grant_scope: consent_request.data.requested_scope,
grant_access_token_audience: consent_request.data.requested_access_token_audience,
remember: true,
session: {
id_token: extra_grants
}
});
throw redirect(303, response.data.redirect_to);
}

View file

@ -0,0 +1,27 @@
<script lang="ts">
import { _ } from 'svelte-i18n';
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center">
<form method="POST" class="place-self-center form-control space-y-2 max-w-sm">
<div>
Hello {data.username}!
</div>
<h1 class="text-lg font-bold">Allow {data.appname} to access your account?</h1>
<div>
<b>{data.appname}</b> would like permission to access your account.
<b>If you do not trust it, then you should not authorize it.</b>
</div>
<h1 class="text-lg font-bold">The app wants to access:</h1>
<ul class="list-disc ml-4">
{#each data.scopes as scope}
<li>{$_(`oidc.scope.${scope}`)}</li>
{/each}
</ul>
<input type="hidden" value={data.challenge} name="consent_challenge" />
<button class="btn btn-success" formaction="?/approve">Approve</button>
<button class="btn btn-error" formaction="?/deny">Deny</button>
</form>
</div>

View file

@ -0,0 +1,76 @@
import type { PageServerLoad } from './$types';
import { KratosAdminApi, KratosPublicApi } from '$lib/server/APIClients.js';
import { redirect } from '@sveltejs/kit';
import { KRATOS_PUBLIC_URL } from '$lib/server/config';
import type { SelfServiceLoginFlow } from '@ory/client';
export const load: PageServerLoad = async ({ url, request }) => {
const flow = url.searchParams.get('flow');
const aal = url.searchParams.get('aal') ?? '';
const refresh = url.searchParams.get('refresh') ?? '';
const return_to = url.searchParams.get('return_to') ?? '';
const login_challenge = url.searchParams.get('login_challenge');
const initFlowQuery = new URLSearchParams({
aal: aal.toString(),
refresh: refresh.toString(),
return_to: return_to.toString()
});
if (login_challenge != undefined) {
initFlowQuery.append('login_challenge', login_challenge);
}
const initFlowUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/login/browser?${initFlowQuery.toString()}`;
if (flow == undefined) {
throw redirect(303, initFlowUrl);
}
const logoutUrl =
(
await KratosAdminApi.createSelfServiceLogoutFlowUrlForBrowsers(
request.headers.get('Cookie') ?? undefined
).catch(() => ({ data: { logout_url: '' } }))
).data.logout_url || '';
const { data: login_flow }: { data: SelfServiceLoginFlow & any } =
await KratosPublicApi.getSelfServiceLoginFlow(
flow,
request.headers.get('Cookie') ?? undefined
).catch((e) => {
console.log(e);
throw redirect(303, initFlowUrl);
});
const initRegistrationQuery = new URLSearchParams({
return_to: return_to.toString()
});
if (login_flow.oauth2_login_request?.challenge) {
initRegistrationQuery.set('login_challenge', login_flow.oauth2_login_request.challenge);
}
const initRegistrationUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/registration/browser?${initFlowQuery.toString()}`;
return {
nodes: login_flow.ui.nodes,
KRATOS_PUBLIC_URL: KRATOS_PUBLIC_URL,
flow: login_flow as SelfServiceLoginFlow,
title: !(login_flow.refresh || login_flow.requested_aal === 'aal2')
? 'Sign In'
: 'Two-Factor Authentication',
...(login_flow.hydra_login_request && {
subtitle: `To authenticate ${
login_flow.hydra_login_request.client_client_name ||
login_flow.hydra_login_request.client_client_id
}`
}),
forgotPasswordURL: '/recovery',
signupURL: initRegistrationUrl,
logoutURL: logoutUrl
};
};

View file

@ -0,0 +1,83 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center">
<form
action={data.flow.ui.action}
method={data.flow.ui.method}
class="place-self-center form-control space-y-2 max-w-sm"
>
<h1 class="text-lg font-bold">{data.title}</h1>
{#if data.subtitle}
<h1 class="text-lg">{data.subtitle}</h1>
{/if}
{#if data.flow.ui.messages}
{#each data.flow.ui.messages as message}
<div class="alert alert-error">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current flex-shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/></svg
>
<span>{message.text}</span>
</div>
</div>
{/each}
{/if}
{#each data.nodes as node}
<!-- <code>{JSON.stringify(node)}</code> -->
{#if node.attributes.type == 'submit'}
<button class="btn btn-primary" {...node.attributes}>{node.meta.label.text}</button>
{:else if node.meta.label}
<div class="form-control">
<label class="label" for={node.attributes.name}>
<span class="label-text">{node.meta.label.text}</span>
</label>
{#if node.attributes.type == 'text' || node.attributes.type == 'password'}
<input class="input input-bordered" id={node.attributes.name} {...node.attributes} />
{:else}
<input id={node.attributes.name} {...node.attributes} />
{/if}
</div>
{:else}
<input {...node.attributes} />
{/if}
{#each node.messages as message}
<div class="alert alert-error">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current flex-shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/></svg
>
<span>{message.text}</span>
</div>
</div>
{/each}
{/each}
{#if data.title == 'Two-Factor Authentication'}
<a class="text-xs" href={data.logoutURL}>Log out</a>
{:else}
<a class="text-xs" href={data.forgotPasswordURL}>Forgot password?</a>
<a class="text-xs" href={data.signupURL}>Sign up instead</a>
{/if}
</form>
<script src="{data.KRATOS_PUBLIC_URL}/.well-known/ory/webauthn.js" async></script>
</div>

View file

@ -0,0 +1,63 @@
import type { Actions, PageServerLoad } from './$types';
import { HydraAdminApi, KratosPublicApi } from '$lib/server/APIClients.js';
import { error, redirect } from '@sveltejs/kit';
import { DEFAULT_REDIRECT_URL } from '$lib/server/config';
export const load: PageServerLoad = async ({ url, request }) => {
const logout_challenge = url.searchParams.get('logout_challenge');
if (logout_challenge == undefined) {
throw error(400, 'Expected logout_challenge');
}
const logout_request = await HydraAdminApi.getOAuth2LogoutRequest(logout_challenge);
if (logout_request.data.subject == undefined) {
throw error(500, 'Could not get your identity');
}
try {
const current_user = await KratosPublicApi.toSession(
undefined,
request.headers.get('Cookie') ?? undefined
);
const current_user_id = current_user.data.identity.id;
const request_user_id = logout_request.data.subject;
console.log(current_user_id, request_user_id);
if (current_user_id != request_user_id) {
// The original session's gone so can't log out
// Pretty much logged out already
const response = await HydraAdminApi.acceptOAuth2LogoutRequest(logout_challenge);
throw redirect(303, response.data.redirect_to);
}
return {
username: current_user.data.identity.traits.username,
challenge: logout_challenge
};
} catch (error) {
// The original session's gone so can't log out
// Pretty much logged out already
const response = await HydraAdminApi.acceptOAuth2LogoutRequest(logout_challenge);
throw redirect(303, response.data.redirect_to);
}
};
export const actions: Actions = {
confirm: async ({ request }) => {
const logout_challenge = (await request.formData()).get('logout_challenge');
if (typeof logout_challenge != 'string') {
throw error(400, 'logout_challenge is invalid');
}
const logout_token = await KratosPublicApi.createSelfServiceLogoutFlowUrlForBrowsers(
request.headers.get('Cookie') ?? undefined
);
let logout_url = new URL(logout_token.data.logout_url);
const response = await HydraAdminApi.acceptOAuth2LogoutRequest(logout_challenge);
logout_url.searchParams.append('return_to', response.data.redirect_to);
throw redirect(303, logout_url.toString());
},
reject: async ({ request }) => {
const logout_challenge = (await request.formData()).get('logout_challenge');
if (typeof logout_challenge != 'string') {
throw error(400, 'logout_challenge is invalid');
}
const response = await HydraAdminApi.rejectOAuth2LogoutRequest(logout_challenge);
throw redirect(303, DEFAULT_REDIRECT_URL);
}
};

View file

@ -0,0 +1,16 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center">
<form method="POST" class="place-self-center form-control space-y-2 max-w-sm">
<div>
Hello {data.username}!
</div>
<h1 class="text-lg font-bold">Really log out?</h1>
<input type="hidden" value={data.challenge} name="logout_challenge" />
<button class="btn btn-success" formaction="?/confirm">Yes</button>
<button class="btn btn-error" formaction="?/reject">No</button>
</form>
</div>

View file

@ -0,0 +1,41 @@
import type { PageServerLoad } from './$types';
import { KratosPublicApi } from '$lib/server/APIClients.js';
import { redirect } from '@sveltejs/kit';
import { KRATOS_PUBLIC_URL } from '$lib/server/config';
export const load: PageServerLoad = async ({ url, request }) => {
const flow = url.searchParams.get('flow');
const return_to = url.searchParams.get('return_to') ?? '';
const initFlowUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/recovery/browser?${new URLSearchParams({
return_to: return_to.toString()
}).toString()}`;
if (flow == undefined) {
throw redirect(303, initFlowUrl);
}
const { data: recovery_flow }: { data: any } = await KratosPublicApi.getSelfServiceRecoveryFlow(
flow,
request.headers.get('Cookie') ?? undefined
).catch((e) => {
console.log(e);
throw redirect(303, initFlowUrl);
});
const initLoginUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/login/browser?${new URLSearchParams({
return_to: return_to.toString()
}).toString()}`;
return {
nodes: recovery_flow.ui.nodes,
KRATOS_PUBLIC_URL: KRATOS_PUBLIC_URL,
flow: recovery_flow,
loginURL: initLoginUrl
};
};

View file

@ -0,0 +1,57 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center">
<form
action={data.flow.ui.action}
method={data.flow.ui.method}
class="place-self-center form-control space-y-2 max-w-sm"
>
<h1 class="text-lg font-bold">Recover Account</h1>
{#if data.flow.ui.messages}
{#each data.flow.ui.messages as message}
<div class="alert alert-error">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current flex-shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/></svg
>
<span>{message.text}</span>
</div>
</div>
{/each}
{/if}
{#each data.nodes as node}
<!-- <code>{JSON.stringify(node)}</code> -->
{#if node.type == 'a'}
<a class="btn btn-primary" {...node.attributes}>{node.meta.label?.text}</a>
{:else if node.attributes.type == 'submit'}
<button class="btn btn-primary" {...node.attributes}>{node.meta.label?.text}</button>
{:else if node.meta.label}
<div class="form-control">
<label class="label" for={node.attributes.name}>
<span class="label-text">{node.meta.label.text}</span>
</label>
{#if node.attributes.type == 'text' || node.attributes.type == 'password' || node.attributes.type == 'email'}
<input class="input input-bordered" id={node.attributes.name} {...node.attributes} />
{:else}
<input id={node.attributes.name} {...node.attributes} />
{/if}
</div>
{:else}
<input {...node.attributes} />
{/if}
{/each}
<a class="text-xs" href={data.loginURL}>Sign up</a>
</form>
</div>

View file

@ -0,0 +1,61 @@
import type { PageServerLoad } from './$types';
import { KratosPublicApi } from '$lib/server/APIClients.js';
import { redirect } from '@sveltejs/kit';
import { KRATOS_PUBLIC_URL } from '$lib/server/config';
import type { SelfServiceRegistrationFlow } from '@ory/client';
export const load: PageServerLoad = async ({ url, request }) => {
const flow = url.searchParams.get('flow');
const return_to = url.searchParams.get('return_to') ?? '';
const login_challenge = url.searchParams.get('login_challenge');
const initFlowQuery = new URLSearchParams({
return_to: return_to.toString()
});
if (login_challenge != undefined) {
initFlowQuery.append('login_challenge', login_challenge);
}
const initFlowUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/registration/browser?${initFlowQuery.toString()}`;
if (flow == undefined) {
throw redirect(303, initFlowUrl);
}
const { data: registration_flow }: { data: SelfServiceRegistrationFlow & any } =
await KratosPublicApi.getSelfServiceRegistrationFlow(
flow,
request.headers.get('Cookie') ?? undefined
).catch((e) => {
console.log(e);
throw redirect(303, initFlowUrl);
});
const initLoginQuery = new URLSearchParams({
return_to: return_to.toString()
});
if (registration_flow.oauth2_login_request?.challenge) {
initLoginQuery.set('login_challenge', registration_flow.oauth2_login_request.challenge);
}
const initLoginUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/login/browser?${initFlowQuery.toString()}`;
return {
nodes: registration_flow.ui.nodes,
KRATOS_PUBLIC_URL: KRATOS_PUBLIC_URL,
flow: registration_flow as SelfServiceRegistrationFlow,
title: 'Register Account',
...(registration_flow.hydra_login_request && {
subtitle: `To authenticate ${
registration_flow.hydra_login_request.client_client_name ||
registration_flow.hydra_login_request.client_client_id
}`
}),
loginURL: initLoginUrl
};
};

View file

@ -0,0 +1,78 @@
<script lang="ts">
import type { PageData } from '../../../.svelte-kit/types/src/routes/signup/$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center">
<form
action={data.flow.ui.action}
method={data.flow.ui.method}
class="place-self-center form-control space-y-2 max-w-sm"
>
<h1 class="text-lg font-bold">{data.title}</h1>
{#if data.subtitle}
<h1 class="text-lg">{data.subtitle}</h1>
{/if}
{#if data.flow.ui.messages}
{#each data.flow.ui.messages as message}
<div class="alert alert-error">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current flex-shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/></svg
>
<span>{message.text}</span>
</div>
</div>
{/each}
{/if}
{#each data.nodes as node}
<!-- <code>{JSON.stringify(node)}</code> -->
{#if node.attributes.type == 'submit'}
<button class="btn btn-primary" {...node.attributes}>{node.meta.label.text}</button>
{:else if node.meta.label}
<div class="form-control">
<label class="label" for={node.attributes.name}>
<span class="label-text">{node.meta.label.text}</span>
</label>
{#if node.attributes.type == 'text' || node.attributes.type == 'password' || node.attributes.type == 'email'}
<input class="input input-bordered" id={node.attributes.name} {...node.attributes} />
{:else}
<input id={node.attributes.name} {...node.attributes} />
{/if}
</div>
{:else}
<input {...node.attributes} />
{/if}
{#each node.messages as message}
<div class="alert alert-error">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current flex-shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/></svg
>
<span>{message.text}</span>
</div>
</div>
{/each}
{/each}
<a class="text-xs" href={data.loginURL}>Log out</a>
</form>
<script src="{data.KRATOS_PUBLIC_URL}/.well-known/ory/webauthn.js" async></script>
</div>

View file

@ -0,0 +1,42 @@
import type { PageServerLoad } from './$types';
import { KratosPublicApi } from '$lib/server/APIClients.js';
import { redirect } from '@sveltejs/kit';
import { KRATOS_PUBLIC_URL } from '$lib/server/config';
export const load: PageServerLoad = async ({ url, request }) => {
const flow = url.searchParams.get('flow');
const return_to = url.searchParams.get('return_to') ?? '';
const initFlowUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/verification/browser?${new URLSearchParams({
return_to: return_to.toString()
}).toString()}`;
if (flow == undefined) {
throw redirect(303, initFlowUrl);
}
const { data: verification_flow }: { data: any } =
await KratosPublicApi.getSelfServiceVerificationFlow(
flow,
request.headers.get('Cookie') ?? undefined
).catch((e) => {
console.log(e);
throw redirect(303, initFlowUrl);
});
const initRegistrationUrl = `${KRATOS_PUBLIC_URL.replace(
/\/$/,
''
)}/self-service/registration/browser?${new URLSearchParams({
return_to: return_to.toString()
}).toString()}`;
return {
nodes: verification_flow.ui.nodes,
KRATOS_PUBLIC_URL: KRATOS_PUBLIC_URL,
flow: verification_flow,
signupURL: initRegistrationUrl
};
};

View file

@ -0,0 +1,57 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<div class="flex min-h-screen justify-center">
<form
action={data.flow.ui.action}
method={data.flow.ui.method}
class="place-self-center form-control space-y-2 max-w-sm"
>
<h1 class="text-lg font-bold">Verify Account</h1>
{#if data.flow.ui.messages}
{#each data.flow.ui.messages as message}
<div class="alert alert-error">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current flex-shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/></svg
>
<span>{message.text}</span>
</div>
</div>
{/each}
{/if}
{#each data.nodes as node}
<!-- <code>{JSON.stringify(node)}</code> -->
{#if node.type == 'a'}
<a class="btn btn-primary" {...node.attributes}>{node.meta.label?.text}</a>
{:else if node.attributes.type == 'submit'}
<button class="btn btn-primary" {...node.attributes}>{node.meta.label?.text}</button>
{:else if node.meta.label}
<div class="form-control">
<label class="label" for={node.attributes.name}>
<span class="label-text">{node.meta.label.text}</span>
</label>
{#if node.attributes.type == 'text' || node.attributes.type == 'password' || node.attributes.type == 'email'}
<input class="input input-bordered" id={node.attributes.name} {...node.attributes} />
{:else}
<input id={node.attributes.name} {...node.attributes} />
{/if}
</div>
{:else}
<input {...node.attributes} />
{/if}
{/each}
<a class="text-xs" href={data.signupURL}>Sign up</a>
</form>
</div>

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

19
svelte.config.js Normal file
View file

@ -0,0 +1,19 @@
import adapter from '@sveltejs/adapter-node';
import preprocess from 'svelte-preprocess';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: [
preprocess({
postcss: true
})
],
kit: {
adapter: adapter()
}
};
export default config;

13
tailwind.config.cjs Normal file
View file

@ -0,0 +1,13 @@
const daisyui = require('daisyui');
const forms = require('@tailwindcss/forms');
const config = {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {}
},
plugins: [forms, daisyui]
};
module.exports = config;

6
tests/test.ts Normal file
View file

@ -0,0 +1,6 @@
import { expect, test } from '@playwright/test';
test('index page has expected h1', async ({ page }) => {
await page.goto('/');
expect(await page.textContent('h1')).toBe('Welcome to SvelteKit');
});

17
tsconfig.json Normal file
View file

@ -0,0 +1,17 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

8
vite.config.ts Normal file
View file

@ -0,0 +1,8 @@
import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
plugins: [sveltekit()]
};
export default config;

2620
yarn.lock Normal file

File diff suppressed because it is too large Load diff