Skip to content

Commit c69d939

Browse files
author
Josh Calder
committed
Resolve example errors for new session
1 parent 1a7c6b8 commit c69d939

File tree

4 files changed

+84
-118
lines changed

4 files changed

+84
-118
lines changed

examples/custom-session/keystone.ts

Lines changed: 60 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,96 +1,79 @@
11
import { randomBytes } from 'crypto';
22
import { config, graphql } from '@keystone-6/core';
3-
import type { SessionStrategy } from '@keystone-6/core/src/types/session';
4-
import { Context } from '.keystone/types';
53
import { lists } from './schema';
4+
import { Context, TypeInfo } from '.keystone/types';
65

7-
type Session = {
8-
id: string
9-
data: {
10-
id: string
11-
}
12-
};
13-
14-
function mySessionStrategy (): SessionStrategy<Session, {
15-
id: string
16-
}> {
17-
return {
18-
async start({ data: { id }, createContext }) { // TODO: change the return type of this to unknown/T
19-
const sudoContext = createContext({}).sudo();
20-
const token = randomBytes(16).toString('hex'); // random 128-bit token
21-
22-
await sudoContext.db.Session.createOne({
23-
data: {
24-
token,
25-
user: { connect: { id } },
26-
ended: false
27-
},
28-
});
6+
async function startSession({ id, context }: { id: string; context: Context }) {
7+
const sudoContext = context.sudo();
8+
const token = randomBytes(16).toString('hex'); // random 128-bit token
299

30-
return token;
10+
await sudoContext.db.Session.createOne({
11+
data: {
12+
token,
13+
user: { connect: { id } },
14+
ended: false,
3115
},
16+
});
3217

33-
// this populates the session object
34-
async get({ req, createContext }) {
35-
const sudoContext = createContext({}).sudo();
36-
const token = req.headers?.authorization;
37-
if (!token) return; // not authenticated
38-
// TODO: hash the token for timing attack
39-
40-
const item = await sudoContext.query.Session.findOne({
41-
where: {
42-
token
43-
},
44-
query: 'user { id } ended',
45-
});
18+
return token;
19+
}
20+
async function endSession({ context }: { context: Context }) {
21+
const sudoContext = context.sudo();
22+
const token = context.req?.headers?.authorization;
23+
if (!token) return; // not authenticated
24+
25+
await sudoContext.db.Session.updateOne({
26+
where: {
27+
token,
28+
},
29+
data: {
30+
ended: true,
31+
},
32+
});
33+
}
4634

47-
// no session
48-
if (!item) return;
35+
async function getSession({ context }: { context: Context }) {
36+
const sudoContext = context.sudo();
37+
const token = context.req?.headers?.authorization;
38+
if (!token) return; // not authenticated
4939

50-
const { user, ended } = item;
51-
if (!user) return; // uh, shouldnt happen
40+
const item = await sudoContext.query.Session.findOne({
41+
where: {
42+
token,
43+
},
44+
query: 'user { id } ended',
45+
});
5246

53-
// is it still active?
54-
if (ended) return;
47+
// no session
48+
if (!item) return;
5549

56-
// they have a session
57-
return {
58-
id: user.id,
59-
data: {
60-
id: user.id
61-
}
62-
};
63-
},
50+
const { user, ended } = item;
51+
if (!user) return; // uh, shouldnt happen
6452

65-
async end({ req, createContext }) {
66-
const sudoContext = createContext({}).sudo();
67-
const token = req.headers?.authorization;
68-
if (!token) return; // not authenticated
53+
// is it still active?
54+
if (ended) return;
6955

70-
await sudoContext.db.Session.updateOne({
71-
where: {
72-
token
73-
},
74-
data: {
75-
ended: true
76-
},
77-
});
56+
// they have a session
57+
return {
58+
id: user.id,
59+
data: {
60+
id: user.id,
7861
},
7962
};
8063
}
8164

82-
export const extendGraphqlSchema = graphql.extend((base) => {
65+
export const extendGraphqlSchema = graphql.extend(base => {
8366
return {
8467
mutation: {
8568
authenticate: graphql.field({
8669
args: {
8770
id: graphql.arg({ type: graphql.nonNull(graphql.ID) }),
8871
}, // parameters
8972
type: base.object('Session'), // return type
90-
async resolve(source, { id }, context) {
91-
const token = await context.startSession({ id }); // TODO: should be an object
92-
console.log({ token })
93-
return {};
73+
async resolve(source, { id }, context: Context) {
74+
const token = await startSession({ id, context });
75+
console.log({ token });
76+
return { token };
9477
},
9578
}),
9679

@@ -99,10 +82,10 @@ export const extendGraphqlSchema = graphql.extend((base) => {
9982
id: graphql.arg({ type: graphql.nonNull(graphql.ID) }),
10083
}, // parameters
10184
type: base.object('Session'), // return type
102-
async resolve(source, { id }, context) {
85+
async resolve(source, { id }, context: Context) {
10386
if (!context.session) return {}; // only authenticated peeps
10487

105-
const token = await context.startSession({ id }); // TODO: should be an object
88+
const token = await startSession({ id, context });
10689
return { id, token };
10790
},
10891
}),
@@ -112,26 +95,25 @@ export const extendGraphqlSchema = graphql.extend((base) => {
11295
token: graphql.arg({ type: graphql.nonNull(graphql.String) }),
11396
}, // parameters
11497
type: base.object('Session'), // return type
115-
async resolve(source, { token }, context) {
116-
await context.endSession({ token }); // TODO: should be an object
98+
async resolve(source, args, context: Context) {
99+
await endSession({ context });
117100
},
118101
}),
119102
},
120103
};
121104
});
122105

123-
async function insertSeedData (context: Context) {
106+
async function insertSeedData(context: Context) {
124107
const { id } = await context.db.User.createOne({
125108
data: {
126-
name: 'Daniel'
109+
name: 'Daniel',
127110
},
128-
query: 'id'
129111
});
130112

131113
console.error('created user', { id });
132114
}
133115

134-
export default config({
116+
export default config<TypeInfo>({
135117
db: {
136118
provider: 'sqlite',
137119
url: process.env.DATABASE_URL || 'file:./keystone-example.db',
@@ -142,7 +124,7 @@ export default config({
142124
},
143125
},
144126
lists,
145-
session: mySessionStrategy(),
127+
getSession,
146128
extendGraphqlSchema,
147129
});
148130

examples/custom-session/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
"build": "keystone build"
1010
},
1111
"dependencies": {
12-
"@keystone-6/core": "^2.1.0"
12+
"@keystone-6/core": "^3.1.2"
1313
},
1414
"devDependencies": {
15-
"typescript": "^4.4.4"
15+
"typescript": "~4.7.4"
1616
},
1717
"engines": {
1818
"node": "^14.15 || ^16.13"

examples/custom-session/schema.graphql

Lines changed: 21 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@ enum PostStatusType {
1515
published
1616
}
1717

18-
scalar DateTime
19-
@specifiedBy(url: "https://datatracker.ietf.org/doc/html/rfc3339#section-5.6")
18+
scalar DateTime @specifiedBy(url: "https://datatracker.ietf.org/doc/html/rfc3339#section-5.6")
2019

2120
input PostWhereUniqueInput {
2221
id: ID
@@ -139,12 +138,7 @@ input UserRelateToOneForCreateInput {
139138
type User {
140139
id: ID!
141140
name: String
142-
posts(
143-
where: PostWhereInput! = {}
144-
orderBy: [PostOrderByInput!]! = []
145-
take: Int
146-
skip: Int! = 0
147-
): [Post!]
141+
posts(where: PostWhereInput! = {}, orderBy: [PostOrderByInput!]! = [], take: Int, skip: Int! = 0): [Post!]
148142
postsCount(where: PostWhereInput! = {}): Int
149143
}
150144

@@ -252,10 +246,7 @@ input SessionCreateInput {
252246
"""
253247
The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
254248
"""
255-
scalar JSON
256-
@specifiedBy(
257-
url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf"
258-
)
249+
scalar JSON @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")
259250

260251
type Mutation {
261252
createPost(data: PostCreateInput!): Post
@@ -272,42 +263,23 @@ type Mutation {
272263
deleteUsers(where: [UserWhereUniqueInput!]!): [User]
273264
createSession(data: SessionCreateInput!): Session
274265
createSessions(data: [SessionCreateInput!]!): [Session]
275-
updateSession(
276-
where: SessionWhereUniqueInput!
277-
data: SessionUpdateInput!
278-
): Session
266+
updateSession(where: SessionWhereUniqueInput!, data: SessionUpdateInput!): Session
279267
updateSessions(data: [SessionUpdateArgs!]!): [Session]
280268
deleteSession(where: SessionWhereUniqueInput!): Session
281269
deleteSessions(where: [SessionWhereUniqueInput!]!): [Session]
282-
endSession: Boolean!
283270
authenticate(id: ID!): Session
284271
refresh(id: ID!): Session
285272
deauthenticate(token: String!): Session
286273
}
287274

288275
type Query {
289-
posts(
290-
where: PostWhereInput! = {}
291-
orderBy: [PostOrderByInput!]! = []
292-
take: Int
293-
skip: Int! = 0
294-
): [Post!]
276+
posts(where: PostWhereInput! = {}, orderBy: [PostOrderByInput!]! = [], take: Int, skip: Int! = 0): [Post!]
295277
post(where: PostWhereUniqueInput!): Post
296278
postsCount(where: PostWhereInput! = {}): Int
297-
users(
298-
where: UserWhereInput! = {}
299-
orderBy: [UserOrderByInput!]! = []
300-
take: Int
301-
skip: Int! = 0
302-
): [User!]
279+
users(where: UserWhereInput! = {}, orderBy: [UserOrderByInput!]! = [], take: Int, skip: Int! = 0): [User!]
303280
user(where: UserWhereUniqueInput!): User
304281
usersCount(where: UserWhereInput! = {}): Int
305-
sessions(
306-
where: SessionWhereInput! = {}
307-
orderBy: [SessionOrderByInput!]! = []
308-
take: Int
309-
skip: Int! = 0
310-
): [Session!]
282+
sessions(where: SessionWhereInput! = {}, orderBy: [SessionOrderByInput!]! = [], take: Int, skip: Int! = 0): [Session!]
311283
session(where: SessionWhereUniqueInput!): Session
312284
sessionsCount(where: SessionWhereInput! = {}): Int
313285
keystone: KeystoneMeta!
@@ -318,8 +290,6 @@ type KeystoneMeta {
318290
}
319291

320292
type KeystoneAdminMeta {
321-
enableSignout: Boolean!
322-
enableSessionItem: Boolean!
323293
lists: [KeystoneAdminUIListMeta!]!
324294
list(key: String!): KeystoneAdminUIListMeta
325295
}
@@ -339,8 +309,10 @@ type KeystoneAdminUIListMeta {
339309
pageSize: Int!
340310
labelField: String!
341311
fields: [KeystoneAdminUIFieldMeta!]!
312+
groups: [KeystoneAdminUIFieldGroupMeta!]!
342313
initialSort: KeystoneAdminUISort
343314
isHidden: Boolean!
315+
isSingleton: Boolean!
344316
}
345317

346318
type KeystoneAdminUIFieldMeta {
@@ -378,6 +350,7 @@ enum KeystoneAdminUIFieldMetaListViewFieldMode {
378350

379351
type KeystoneAdminUIFieldMetaItemView {
380352
fieldMode: KeystoneAdminUIFieldMetaItemViewFieldMode
353+
fieldPosition: KeystoneAdminUIFieldMetaItemViewFieldPosition
381354
}
382355

383356
enum KeystoneAdminUIFieldMetaItemViewFieldMode {
@@ -386,11 +359,22 @@ enum KeystoneAdminUIFieldMetaItemViewFieldMode {
386359
hidden
387360
}
388361

362+
enum KeystoneAdminUIFieldMetaItemViewFieldPosition {
363+
form
364+
sidebar
365+
}
366+
389367
enum QueryMode {
390368
default
391369
insensitive
392370
}
393371

372+
type KeystoneAdminUIFieldGroupMeta {
373+
label: String!
374+
description: String
375+
fields: [KeystoneAdminUIFieldMeta!]!
376+
}
377+
394378
type KeystoneAdminUISort {
395379
field: String!
396380
direction: KeystoneAdminUISortDirection!

examples/custom-session/schema.prisma

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,4 @@ model Session {
3939
ended Boolean @default(false)
4040
4141
@@index([userId])
42-
}
42+
}

0 commit comments

Comments
 (0)