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

docs(examples): add custom session with passport #9125

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/custom-session-passport/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
85 changes: 85 additions & 0 deletions examples/custom-session-passport/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { Router } from "express";
import { Passport } from "passport";
import { Strategy, StrategyOptions, Profile } from "passport-github2";
import { statelessSessions } from "@keystone-6/core/session";
import type { KeystoneContext } from "@keystone-6/core/types";
import type { VerifyCallback } from "passport-oauth2";
import { Author } from ".myprisma/client";
import type { TypeInfo } from ".keystone/types";

export type Session = Author

export const session = statelessSessions<Session>({
maxAge: 60 * 60 * 24 * 30,
secret: process.env.SESSION_SECRET!,
});

declare global {
namespace Express {
// Augment the global user added by Passport to be the same as the Prisma Author
interface User extends Author {}
}
}

const options: StrategyOptions = {
// https://github.com/settings/applications/new
clientID: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
callbackURL: "http://localhost:3000/auth/github/callback",
};

export function createAuthenticationMiddleware(
commonContext: KeystoneContext<TypeInfo<Session>>
): Router {
const router = Router();
const instance = new Passport();
const strategy = new Strategy(
options,
async (_a: string, _r: string, p: Profile, done: VerifyCallback) => {
const author = await commonContext.prisma.author.upsert({
where: { authId: p.id },
update: { name: p.displayName },
create: { authId: p.id, name: p.displayName },
});

return done(null, author);
}
);

instance.use(strategy);

const middleware = instance.authenticate("github", {
// No need to use express-session internally
session: false,
});

router.get("/auth/github", middleware);
router.get("/auth/github/callback", middleware, async (req, res) => {
if (!req.user) {
res.status(401).send("Authentication failed");
return;
}

const context = await commonContext.withRequest(req, res);

// Start the session in the same way authenticateItemWithPassword does
// see: packages/auth/src/gql/getBaseAuthSchema.ts
await context.sessionStrategy?.start({
context,
data: req.user,
});

res.redirect("/auth/session");
});

// This URL will show current session object
router.get("/auth/session", async (req, res) => {
const context = await commonContext.withRequest(req, res);
const session = await context.sessionStrategy?.get({ context });
res.setHeader("Content-Type", "application/json");
res.send(JSON.stringify(session));
res.end();
});

return router;
}
29 changes: 29 additions & 0 deletions examples/custom-session-passport/keystone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import "dotenv/config";
import { config } from "@keystone-6/core";
import { KeystoneConfig } from "@keystone-6/core/types";
import { TypeInfo } from ".keystone/types";
import { lists } from "./schema";
import { session, createAuthenticationMiddleware, Session } from "./auth";
import { fixPrismaPath } from "../example-utils";

const keystoneConfig: KeystoneConfig<TypeInfo<Session>> = config<
TypeInfo<Session>
>({
db: {
provider: "sqlite",
url: "file:./keystone.db",

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

server: {
extendExpressApp(app, context) {
app.use(createAuthenticationMiddleware(context));
},
},
});

export default keystoneConfig;
27 changes: 27 additions & 0 deletions examples/custom-session-passport/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@keystone-6/example-custom-session-passport",
"version": "1.0.2",
"private": true,
"scripts": {
"dev": "keystone dev",
"start": "keystone start",
"build": "keystone build",
"postinstall": "keystone build --no-ui --frozen"
},
"dependencies": {
"@keystone-6/core": "workspace:^",
"@prisma/client": "^5.13.0",
"dotenv": "^16.0.0",
"express": "^4.17.1",
"passport": "^0.7.0",
"passport-github2": "^0.1.12"
},
"devDependencies": {
"@types/express": "^4.17.14",
"@types/passport": "^1.0.16",
"@types/passport-github2": "^1.2.9",
"@types/passport-oauth2": "^1.4.16",
"prisma": "^5.13.0",
"typescript": "^5.4.5"
}
}