-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.ts
79 lines (60 loc) · 1.93 KB
/
index.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
77
78
79
import cookieParser from 'cookie-parser'
import cors from 'cors'
import express from 'express'
import {Cookies} from '@shared'
import {authMiddleware} from './auth-middleware'
import {config} from './config'
import {databaseClient} from './database'
import {getGitHubUser} from './github-adapter'
import {buildTokens, clearTokens, refreshTokens, setTokens, verifyRefreshToken} from './token-utils'
import {
createUser,
getUserByGitHubId,
getUserById,
increaseTokenVersion,
setupUserIndexes,
} from './user-service'
const app = express()
app.use(cors({credentials: true, origin: config.clientUrl}))
app.use(cookieParser())
app.get('/', (req, res) => res.send('api is healthy'))
app.get('/github', async (req, res) => {
const {code} = req.query
const gitHubUser = await getGitHubUser(code as string)
let user = await getUserByGitHubId(gitHubUser.id)
if (!user) user = await createUser(gitHubUser.name, gitHubUser.id)
const {accessToken, refreshToken} = buildTokens(user)
setTokens(res, accessToken, refreshToken)
res.redirect(`${config.clientUrl}/me`)
})
app.post('/refresh', async (req, res) => {
try {
const current = verifyRefreshToken(req.cookies[Cookies.RefreshToken])
const user = await getUserById(current.userId)
if (!user) throw 'User not found'
const {accessToken, refreshToken} = refreshTokens(current, user.tokenVersion)
setTokens(res, accessToken, refreshToken)
} catch (error) {
clearTokens(res)
}
res.end()
})
app.post('/logout', authMiddleware, (req, res) => {
clearTokens(res)
res.end()
})
app.post('/logout-all', authMiddleware, async (req, res) => {
await increaseTokenVersion(res.locals.token.userId)
clearTokens(res)
res.end()
})
app.get('/me', authMiddleware, async (req, res) => {
const user = await getUserById(res.locals.token.userId)
res.json(user)
})
async function main() {
await databaseClient.connect()
await setupUserIndexes()
app.listen(3000)
}
main()