-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsimple.ts
76 lines (64 loc) · 1.48 KB
/
simple.ts
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
import { Elysia } from 'elysia'
import oauth2, { github } from '../src'
import { randomBytes } from 'crypto'
const globalState = randomBytes(8).toString('hex')
let globalToken = null
const app = new Elysia()
const auth = oauth2({
profiles: {
github: {
provider: github(),
scope: ['user']
}
},
state: {
check(ctx, name, state) {
return state === globalState
},
generate(ctx, name) {
return globalState
}
},
storage: {
get(ctx, name) {
return globalToken
},
set(ctx, name, token) {
globalToken = token
},
delete(ctx, name) {
globalToken = null
}
}
})
function userPage(user: {}, logout: string) {
const html = `<!DOCTYPE html>
<html lang="en">
<body>
User:
<pre>${JSON.stringify(user, null, '\t')}</pre>
<a href="${logout}">Logout</a>
</body>
</html>`
return new Response(html, { headers: { 'Content-Type': 'text/html' } })
}
app
.use(auth)
.get('/', async (ctx) => {
const profiles = ctx.profiles('github')
if (await ctx.authorized('github')) {
const user = await fetch('https://api.github.com/user', {
headers: await ctx.tokenHeaders('github')
})
return userPage(await user.json(), profiles.github.logout)
}
const html = `<!DOCTYPE html>
<html lang="en">
<body>
<h2>Login with <a href="${profiles.github.login}">Github</a></h2>
</body>
</html>`
return new Response(html, { headers: { 'Content-Type': 'text/html' } })
})
.listen(3000)
console.log(`${app.server!.url}`)