Keystone6 setup
Installation
PNPM
PNPM manager currently is not fully tested and we have noticed some issues with it. We recommend using NPM or Yarn for now.
To install run the following command in your Keystone6 project:
- npm
- yarn
- pnpm
npm install keystone-6-oauth
yarn add keystone-6-oauth
pnpm add keystone-6-oauth
Usage
Once installed, you will need to modify your Keystone config (by default at ./keystone.js
) file.
Import createAuth
keystone.js
import { createAuth } from "keystone-6-oauth";
Import Provider of your choice
keystone.js
import { createAuth } from "keystone-6-oauth";
import Facebook from "keystone-6-oauth/providers/Facebook";
Session Secret
Define sessionSection
and handler to ensure it is present.
keystone.js
import { createAuth } from "keystone-6-oauth";
import Facebook from "keystone-6-oauth/providers/Facebook";
// ...
let sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret) {
if (process.env.NODE_ENV === "production") {
throw new Error(
"The SESSION_SECRET environment variable must be set in production"
);
} else {
sessionSecret = "-- DEV COOKIE SECRET; CHANGE ME --";
}
}
Configure Keystone
Configure Keystone auth, including providers for Provider. For documentation on Providers and their API & options see https://next-auth.js.org/providers/.
To use a given Provider, replace next-auth/providers
with keystone-6-oauth/providers
keystone.js
import { createAuth } from "keystone-6-oauth";
import Facebook from "keystone-6-oauth/providers/Facebook";
// ...
let sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret) {
if (process.env.NODE_ENV === "production") {
throw new Error(
"The SESSION_SECRET environment variable must be set in production"
);
} else {
sessionSecret = "-- DEV COOKIE SECRET; CHANGE ME --";
}
}
const auth = createAuth({
autoCreate: true,
listKey: 'User',
identityField: 'subjectId',
keystonePath: '/admin',
onSignIn: async (props: any) => {
// Log user sign in
// Boolean to allow sign in. If returned false user will not be logged in.
return true;
},
onSignUp: async (props: any) => {
const username = props.user.name as string;
const email = props.user.email as string;
return { email, username };
},
providers: [
FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID || "NextAuthClientID",
clientSecret: process.env.FACEBOOK_CLIENT_SECRET || "NextAuthClientSecret",
}),
]
sessionData: `id name email`,
sessionSecret,
});
Final step
Wrap your keystone config in auth.withAuth()
.
keystone.js
// ...everything from previous codeblocks
export default auth.withAuth(
config({
db: {
provider: 'postgresql',
url: process.env.DATABASE_URL as string,
},
lists,
session,
ui: {
isAccessAllowed: context => !!context.session?.data,
},
})
);
Next Steps
Your Keystone app should now be ready. The next step is to setup your Next.js application.