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 example for custom session strategy using JWTs #8640

Merged
merged 7 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
Binary file not shown.
103 changes: 103 additions & 0 deletions examples/custom-session-jwt/keystone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import jwt from 'jsonwebtoken';
import { config } from '@keystone-6/core';
import { fixPrismaPath } from '../example-utils';
import { lists, Session } from './schema';
import type { Context, TypeInfo } from '.keystone/types';

// WARNING: this example is for demonstration purposes only
// as with each of our examples, it has not been vetted
// or tested for any particular usage

// WARNING: you need to change this
const jwtSessionSecret = '-- DEV COOKIE SECRET; CHANGE ME --';

type OurJWT = {
id: string;
};

async function jwtSign(claims: OurJWT) {
return new Promise((resolve, reject) => {
jwt.sign(
claims,
jwtSessionSecret,
{
algorithm: 'HS256', // HMAC-SHA256

// we use an expiry of 1 hour for this example
expiresIn: '1 hour',
},
(err, token) => {
if (err) return reject(err);
return resolve(token);
}
);
});
}

async function jwtVerify(token: string): Promise<OurJWT | null> {
return new Promise(resolve => {
jwt.verify(
token,
jwtSessionSecret,
{
algorithms: ['HS256'],
},
(err, result) => {
if (err || typeof result !== 'object') return resolve(null);
if (typeof result.id !== 'string') return resolve(null);
return resolve(result as OurJWT);
}
);
});
}

const jwtSessionStrategy = {
async get({ context }: { context: Context }): Promise<Session | undefined> {
if (!context.req) return;

const { cookie = '' } = context.req.headers;
const [cookieName, jwt] = cookie.split('=');
if (cookieName !== 'user') return;

const jwtResult = await jwtVerify(jwt);
if (!jwtResult) return;

const { id } = jwtResult;
const who = await context.sudo().db.User.findOne({ where: { id } });
if (!who) return;
return {
id,
admin: who.admin,
};
},

// we don't need these unless we want to support the functions
// context.sessionStrategy.start
// context.sessionStrategy.end
//
async start() {},
async end() {},
};

export default config<TypeInfo>({
db: {
provider: 'sqlite',
url: process.env.DATABASE_URL || 'file:./keystone-example.db',

// WARNING: this is only needed for our monorepo examples, dont do this
...fixPrismaPath,

onConnect: async () => {
console.error(
'Use any of the following tokens as your `user={token}` cookie for testing this session strategy',
{
Alice: await jwtSign({ id: 'clh9v6pcn0000sbhm9u0j6in0' }), // admin
Bob: await jwtSign({ id: 'clh9v762w0002sbhmhhyc0340' }),
Eve: await jwtSign({ id: 'clh9v7ahs0004sbhmpx30w85n' }),
}
);
},
},
lists,
session: jwtSessionStrategy,
});
23 changes: 23 additions & 0 deletions examples/custom-session-jwt/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "@keystone-6/example-custom-session-jwt",
"version": "0.0.1",
"private": true,
"license": "MIT",
"scripts": {
"dev": "keystone dev",
"start": "keystone start",
"build": "keystone build",
"postinstall": "keystone postinstall"
},
"dependencies": {
"@keystone-6/auth": "^7.0.0",
"@keystone-6/core": "^5.0.0",
"@prisma/client": "^4.15.0",
"jsonwebtoken": "^9.0.0"
},
"devDependencies": {
"@types/jsonwebtoken": "^9.0.2",
"prisma": "^4.15.0",
"typescript": "~5.0.0"
}
}
7 changes: 7 additions & 0 deletions examples/custom-session-jwt/sandbox.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"template": "node",
"container": {
"startScript": "keystone dev",
"node": "16"
}
}
Loading