This repository was archived by the owner on Nov 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
174 lines (167 loc) · 5.45 KB
/
index.js
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
"use strict"
// require modules
const Koa = require("koa")
const Router = require("koa-router")
const Knex = require("knex")
const rp = require("request-promise")
const crypto = require("crypto")
const uuid = require("uuid")
// define constant values
const app = new Koa()
const router = new Router({prefix: "/api/v1"})
const secretKey = crypto.randomBytes(32).hexSlice()
const {client_id, client_secret, NODE_ENV} = process.env
const knex = Knex(require("./knexfile.js")[NODE_ENV || "development"])
const endpoint = "https://qiita.com/api/v2"
// Authorization control
router
.get("/auth", async (ctx, next) => {
const {callback} = ctx.query
ctx.assert(callback, 400)
const token = crypto.randomBytes(32).hexSlice()
const expires = new Date(Date.now() + 300000)
ctx.cookies
.set("callback", callback, {expires})
.set("token", crypto.createHmac("sha256", secretKey).update(token).digest("hex"), {expires})
ctx.redirect(`${endpoint}/oauth/authorize?client_id=${client_id}&scope=read_qiita&state=${token}`)
})
.get("/auth/callback", async (ctx, next) => {
const {code, state} = ctx.query
ctx.assert(ctx.cookies.get("callback") && code && state, 400)
ctx.assert(crypto.createHmac("sha256", secretKey).update(state).digest("hex") === ctx.cookies.get("token"), 400)
ctx.cookies.set("token")
await new Promise(resolve => setTimeout(resolve, 500))
await rp({
method: "POST",
uri: `${endpoint}/access_tokens`,
body: {client_id, client_secret, code},
json: true
})
.then(auth => {
ctx.assert(auth.client_id === client_id, 500)
return Promise.all([
auth.token,
rp({
uri: `${endpoint}/authenticated_user`,
headers: {"Authorization": `Bearer ${auth.token}`},
json: true
})
])
})
.then(([token, user]) => Promise.all([
user,
rp({
method: "DELETE",
uri: `${endpoint}/access_tokens/${token}`
})
]))
.then(([user]) => Promise.all([
user.id,
knex("users").first("id").where({id: user.id}),
]))
.then(([id, exists]) => {
const token = uuid.v1()
if (!exists) {
return Promise.all([
token,
knex("users").insert({id, token, revoked: false})
])
} else {
return Promise.all([
token,
knex("users").where({id}).update({revoked: false, token})
])
}
})
.then(([token]) => {
ctx.redirect(`${ctx.cookies.get("callback")}?token=${token}`)
ctx.cookies.set("callback")
})
.catch(err => {
console.error(err)
ctx.throw(500)
})
})
.delete("/auth/token/:token", async (ctx, next) => {
const {token} = ctx.params
await knex("users").first("id", "revoked").where("token", token)
.then(user => {
ctx.assert(user, 404)
ctx.assert(!user.revoked, 400)
return knex("users").where({id: user.id}).update({revoked: true})
})
.then(() => {
ctx.body = {complete: true}
})
})
// Dislike API
router
.use("/:username/items/:id", async (ctx, next) => {
// Authentication
const auth = ctx.header.authorization
ctx.assert(auth, 401)
// Token should be "Authorization: Bearer <UUID>"
const token = auth.replace(/^Bearer /, "")
// Authentication (token to user)
await knex("users").first("id").where({token, revoked: false})
.then(user => {
ctx.assert(user, 403)
ctx.user = user.id
})
await next()
})
.get("/:username/items/:id", async (ctx, next) => {
// Get disliked status and dislike count from DB
await knex("item_dislike").select("by_whom").where({id: ctx.params.id, state: true})
.then(users => {
ctx.body = {
disliked: users.map(_=>_.by_whom).includes(ctx.user),
count: users.length
}
})
})
.post("/:username/items/:id", async (ctx, next) => {
// Set disliked status and get new dislike count
const {id, username} = ctx.params
await knex("item_dislike").first("state").where({id, by_whom: ctx.user})
.then(disliked => {
if (disliked === undefined) {
return knex("item_dislike").insert({id, username, by_whom: ctx.user, state: true})
} else if (!disliked.state) {
return knex("item_dislike").where({id, by_whom: ctx.user}).update({state: true})
} else {
ctx.throw(405)
}
})
.then(() => {
ctx.body = {complete: true}
})
})
.delete("/:username/items/:id", async (ctx, next) => {
// Unset disliked status and get new dislike count
const {id, username} = ctx.params
await knex("item_dislike").first("state").where({id, by_whom: ctx.user})
.then(disliked => ctx.assert(!!disliked && disliked.state, 405))
.then(() => knex("item_dislike").where({id, by_whom: ctx.user}).update({state: false}))
.then(() => {
ctx.body = {complete: true}
})
})
// Run API Server
app
.use(async (ctx, next) => {
ctx.set("Access-Control-Allow-Origin", "*")
ctx.set("Access-Control-Allow-Headers", "Authorization")
ctx.set("Access-Control-Allow-Methods", "GET, PUT, DELETE")
ctx.req.setTimeout(10000)
try {
await next()
} catch (e) {
ctx.status = e.status || 500
ctx.type = "json"
ctx.body = {error: e.message}
}
})
.use(router.routes())
.use(router.allowedMethods({throw: true}))
.listen(3000)