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

Merged
merged 5 commits into from
Jul 17, 2024
Merged
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
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
86 changes: 86 additions & 0 deletions examples/custom-session-passport/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { Router } from 'express'
import { statelessSessions } from '@keystone-6/core/session'
import { type KeystoneContext } from '@keystone-6/core/types'

import { Passport } from 'passport'
import { type VerifyCallback } from 'passport-oauth2'
import { Strategy, StrategyOptions, Profile } from 'passport-github2'

import { type 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 = {
// see 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 passportMiddleware (
commonContext: KeystoneContext<TypeInfo<Session>>
): Router {
const router = Router()
const instance = new Passport()
const strategy = new Strategy(
options,
async (_a: string, _r: string, profile: Profile, done: VerifyCallback) => {
const author = await commonContext.prisma.author.upsert({
where: { authId: profile.id },
update: { name: profile.displayName },
create: { authId: profile.id, name: profile.displayName },
})

return done(null, author)
}
)

instance.use(strategy)
const middleware = instance.authenticate('github', {
session: false, // dont use express-session
})

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)

// starts the session, and sets the cookie on context.res
await context.sessionStrategy?.start({
context,
data: req.user,
})

res.redirect('/auth/session')
})

// show the current session object
// WARNING: this is for demonstration purposes only, probably dont do this
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 { type TypeInfo } from '.keystone/types'
import { lists } from './schema'
import {
type Session,
session,
passportMiddleware
} from './auth'
import { fixPrismaPath } from '../example-utils'

export default 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(passportMiddleware(context))
},
},
})
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.0",
"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": "catalog:",
"dotenv": "^16.0.0",
"express": "catalog:",
"passport": "^0.7.0",
"passport-github2": "^0.1.12"
},
"devDependencies": {
"@types/express": "catalog:",
"@types/passport": "^1.0.16",
"@types/passport-github2": "^1.2.9",
"@types/passport-oauth2": "^1.4.16",
"prisma": "catalog:",
"typescript": "catalog:"
}
}
Loading
Loading