Skip to content

Commit

Permalink
remove auth from other nextjs example too
Browse files Browse the repository at this point in the history
  • Loading branch information
dcousens committed Apr 13, 2023
1 parent 5b77e59 commit 62af1a9
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 156 deletions.
14 changes: 6 additions & 8 deletions examples/nextjs-keystone-app-directory/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@ import { keystoneContext } from '../keystone/context';
import { DocumentRender } from './DocumentRender';

export default async function HomePage() {
/*
`keystoneContext` object doesn't have user's session information.
You need an authenticated context to CRUD data behind access control.
keystoneContext.withSession(session) - passing in a session object that
aligns with your access control - gives you a `context` object with
session info and an elevated sudo context to bypass access control if needed (context.sudo()).
*/
const users = await keystoneContext.query.User.findMany({
// WARNING: this does nothing for now
// you will probably use getServerSession from 'next/auth'
// https://next-auth.js.org/configuration/nextjs#in-app-directory
const session = {}
const users = await keystoneContext.withSession(session).query.User.findMany({
query: 'id name about { document }',
});

return (
<section>
<h1>Keystone 🤝 Next.js</h1>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { list } from '@keystone-6/core';
import { allowAll, denyAll, allOperations } from '@keystone-6/core/access';
import { allowAll } from '@keystone-6/core/access';
import { text, timestamp } from '@keystone-6/core/fields';
import { document } from '@keystone-6/fields-document';
import type { Lists } from '.keystone/types';
Expand Down
30 changes: 12 additions & 18 deletions examples/nextjs-keystone/keystone.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
import { config } from '@keystone-6/core';
import { lists } from './src/keystone/schema';
import { withAuth, session } from './src/keystone/auth';
import { seedDemoData } from './src/keystone/seed';
import type { Context } from '.keystone/types';

// Next.js deploys need absolute path to sqlite db file
const dbFilePath = `${process.cwd()}/keystone.db`;
export default withAuth(
config({
db: {
provider: 'sqlite',
url: `file:${dbFilePath}`,
onConnect: async (context: Context) => {
await seedDemoData(context);
},

// WARNING: this is only needed for our monorepo examples, dont do this
prismaClientPath: 'node_modules/.myprisma/client',
export default config({
db: {
provider: 'sqlite',
url: `file:${process.cwd()}/keystone.db`, // next.js requires an absolute path for sqlite
onConnect: async (context: Context) => {
await seedDemoData(context);
},
lists,
session,
})
);

// WARNING: this is only needed for our monorepo examples, dont do this
prismaClientPath: 'node_modules/.myprisma/client',
},
lists,
});
36 changes: 0 additions & 36 deletions examples/nextjs-keystone/src/keystone/auth.ts

This file was deleted.

36 changes: 10 additions & 26 deletions examples/nextjs-keystone/src/keystone/schema.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,20 @@
import { list } from '@keystone-6/core';
import { allowAll, denyAll, allOperations } from '@keystone-6/core/access';
import { text, password, timestamp } from '@keystone-6/core/fields';
import { allowAll } from '@keystone-6/core/access';
import { text, timestamp } from '@keystone-6/core/fields';
import { document } from '@keystone-6/fields-document';
import type { Lists } from '.keystone/types';

const permissions = {
authenticatedUser: ({ session }: any) => !!session?.data,
public: () => true,
readOnly: {
operation: {
// deny create/read/update/delete
...allOperations(denyAll),
// override the deny and allow only query
query: allowAll,
},
},
};

export const lists: Lists = {
User: list({
// readonly for demo purpose
access: permissions.readOnly,
// WARNING
// for this example, anyone can create, query, update and delete anything
// if you want to prevent random people on the internet from accessing your data,
// you can find out more at https://keystonejs.com/docs/guides/auth-and-access-control
access: allowAll,

fields: {
name: text({ validation: { isRequired: true } }),
email: text({
validation: { isRequired: true },
isIndexed: 'unique',
access: {
// email only visible to authenticated users
read: permissions.authenticatedUser,
},
}),
password: password({ validation: { isRequired: true } }),
about: text(),
createdAt: timestamp({
defaultValue: { kind: 'now' },
}),
Expand Down
51 changes: 15 additions & 36 deletions examples/nextjs-keystone/src/keystone/seed.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,20 @@
import type { Context } from '.keystone/types';

const demoUsers = [
{
email: '[email protected]',
password: 'passw0rd',
name: 'Clark Kent',
},
{
email: '[email protected]',
password: 'passw0rd',
name: 'Bruce Wayne',
},
{
email: '[email protected]',
password: 'passw0rd',
name: 'Diana Prince',
},
] as const;
export async function seedDemoData(context: Context) {
if ((await context.db.User.count()) > 0) return;

const upsertUser = async ({
context,
user,
}: {
context: Context;
user: { email: string; password: string; name: string };
}) => {
const userInDb = await context.db.User.findOne({
where: { email: user.email },
});
if (userInDb) {
return userInDb;
for (const user of [
{
name: 'Clark',
},
{
name: 'Bruce',
},
{
name: 'Diana',
},
] as const) {
await context.db.User.createOne({ data: user });
}
}

return context.db.User.createOne({ data: user });
};

export const seedDemoData = (context: Context) => {
const sudoContext = context.sudo();
return Promise.all(demoUsers.map(u => upsertUser({ context: sudoContext, user: u })));
};
52 changes: 21 additions & 31 deletions examples/nextjs-keystone/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,7 @@ const Home: NextPage = ({ users }: InferGetServerSidePropsType<typeof getServerS
<section>
<h1>Keystone 🤝 Next.js</h1>
<ul>
<li>
If you are <strong>not logged in</strong>, you can <strong>only see the name</strong>{' '}
of all users in the database.
</li>
<li>
User.email is behind access control and only visible for logged in users. Once you{' '}
<strong>log in</strong>, you can <strong>see both the name and email</strong> of all
users in the database.
</li>
<li>Below you can see the names of users in the database.</li>
</ul>

<ServerRenderedContent users={users} />
Expand Down Expand Up @@ -77,16 +69,9 @@ const Home: NextPage = ({ users }: InferGetServerSidePropsType<typeof getServerS
};

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
/*
`keystoneContext` object doesn't have user's session information.
You need an authenticated context to CRUD data behind access control.
keystoneContext.withRequest(req, res) automatically unwraps the session cookie
in the request object and gives you a `context` object with session info
and an elevated sudo context to bypass access control if needed (context.sudo()).
*/
const context = await keystoneContext.withRequest(req, res);
const users = await context.query.User.findMany({
query: 'id name email',
query: 'id name about',
});
return {
props: { users: users }, // will be passed to the page component as props
Expand All @@ -104,14 +89,19 @@ function ServerRenderedContent({
<strong>Users fetched from the server (in getServerSideProps)</strong>
</p>
<ol>
{users.map(u => {
return (
<li key={u.id}>
<span>{u.name} </span>
{u.email ? <span>(email: {u.email})</span> : <span>(email: not authenticated)</span>}
</li>
);
})}
{users.map(u => {
return (
<li key={u.id}>
<span>{u.name} </span>
{u.about?.length > 1 && (
<>
<hr />
{u.about}
</>
)}
</li>
);
})}
</ol>
</div>
);
Expand All @@ -129,7 +119,7 @@ function ClientRenderedContent() {
users {
id
name
email
about
}
}
`
Expand All @@ -150,11 +140,11 @@ function ClientRenderedContent() {
return (
<li key={u.id}>
<span>{u.name} </span>

{u.email ? (
<span>(email: {u.email})</span>
) : (
<span>(email: not authenticated)</span>
{u.about?.length > 1 && (
<>
<hr />
{u.about}
</>
)}
</li>
);
Expand Down

0 comments on commit 62af1a9

Please sign in to comment.