-
Notifications
You must be signed in to change notification settings - Fork 465
Expand file tree
/
Copy pathgithub.ts
More file actions
194 lines (167 loc) · 5.01 KB
/
github.ts
File metadata and controls
194 lines (167 loc) · 5.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { faker } from '@faker-js/faker'
import fsExtra from 'fs-extra'
import { HttpResponse, passthrough, http, type HttpHandler } from 'msw'
import { USERNAME_MAX_LENGTH } from '#app/utils/user-validation.ts'
const { json } = HttpResponse
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const here = (...s: Array<string>) => path.join(__dirname, ...s)
const githubUserFixturePath = path.join(
here(
'..',
'fixtures',
'github',
`users.${process.env.VITEST_POOL_ID || 0}.local.json`,
),
)
await fsExtra.ensureDir(path.dirname(githubUserFixturePath))
function createGitHubUser(code?: string | null) {
const createEmail = () => ({
email: faker.internet.email(),
verified: faker.datatype.boolean(),
primary: false, // <-- can only have one of these
visibility: faker.helpers.arrayElement(['public', null]),
})
const primaryEmail = {
...createEmail(),
verified: true,
primary: true,
}
const emails = [
{
email: faker.internet.email(),
verified: false,
primary: false,
visibility: 'public',
},
{
email: faker.internet.email(),
verified: true,
primary: false,
visibility: null,
},
primaryEmail,
]
code ??= faker.string.uuid()
return {
code,
accessToken: `${code}_mock_access_token`,
profile: {
login: faker.internet.username().slice(0, USERNAME_MAX_LENGTH),
id: faker.number.int(),
name: faker.person.fullName(),
avatar_url: 'https://github.com/ghost.png',
emails: emails.map((e) => e.email),
},
emails,
primaryEmail: primaryEmail.email,
}
}
export type GitHubUser = ReturnType<typeof createGitHubUser>
async function getGitHubUsers() {
try {
if (await fsExtra.pathExists(githubUserFixturePath)) {
const json = await fsExtra.readJson(githubUserFixturePath)
return json as Array<GitHubUser>
}
return []
} catch (error) {
console.error(error)
return []
}
}
export async function deleteGitHubUser(primaryEmail: string) {
const users = await getGitHubUsers()
const user = users.find((u) => u.primaryEmail === primaryEmail)
if (!user) return null
await setGitHubUsers(users.filter((u) => u.primaryEmail !== primaryEmail))
return user
}
export async function deleteGitHubUsers() {
await fsExtra.remove(githubUserFixturePath)
}
async function setGitHubUsers(users: Array<GitHubUser>) {
await fsExtra.writeJson(githubUserFixturePath, users, { spaces: 2 })
}
export async function insertGitHubUser(code?: string | null) {
const githubUsers = await getGitHubUsers()
let user = githubUsers.find((u) => u.code === code)
if (user) {
Object.assign(user, createGitHubUser(code))
} else {
user = createGitHubUser(code)
githubUsers.push(user)
}
await setGitHubUsers(githubUsers)
return user
}
async function getUser(request: Request) {
const accessToken = request.headers
.get('authorization')
?.slice('Bearer '.length)
if (!accessToken) {
return new Response('Unauthorized', { status: 401 })
}
const user = (await getGitHubUsers()).find(
(u) => u.accessToken === accessToken,
)
if (!user) {
return new Response('Not Found', { status: 404 })
}
return user
}
const passthroughGitHub =
!process.env.GITHUB_CLIENT_ID?.startsWith('MOCK_') &&
process.env.NODE_ENV !== 'test'
export const handlers: Array<HttpHandler> = [
http.post(
'https://github.com/login/oauth/access_token',
async ({ request }) => {
if (passthroughGitHub) return passthrough()
const params = new URLSearchParams(await request.text())
const code = params.get('code')
const githubUsers = await getGitHubUsers()
let user = githubUsers.find((u) => u.code === code)
if (!user) {
user = await insertGitHubUser(code)
}
return json(
{
access_token: user.accessToken,
token_type: '__MOCK_TOKEN_TYPE__',
},
{ headers: { 'content-type': 'application/x-www-form-urlencoded' } },
)
},
),
http.get('https://api.github.com/user/emails', async ({ request }) => {
if (passthroughGitHub) return passthrough()
const user = await getUser(request)
if (user instanceof Response) return user
return json(user.emails)
}),
http.get('https://api.github.com/user/:id', async ({ params }) => {
if (passthroughGitHub) return passthrough()
const mockUser = (await getGitHubUsers()).find(
(u) => u.profile.id === Number(params.id),
)
if (mockUser) return json(mockUser.profile)
return new Response('Not Found', { status: 404 })
}),
http.get('https://api.github.com/user', async ({ request }) => {
if (passthroughGitHub) return passthrough()
const user = await getUser(request)
if (user instanceof Response) return user
return json(user.profile)
}),
http.get('https://github.com/ghost.png', async () => {
if (passthroughGitHub) return passthrough()
const buffer = await fsExtra.readFile('./tests/fixtures/github/ghost.jpg')
return new Response(buffer, {
// the .png is not a mistake even though it looks like it... It's really a jpg
// but the ghost image URL really has a png extension 😅
headers: { 'content-type': 'image/jpg' },
})
}),
]