-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
334 lines (299 loc) · 8.31 KB
/
server.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
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Std libs
import {
crypto,
toHashString,
} from "https://deno.land/[email protected]/crypto/mod.ts";
import "https://deno.land/[email protected]/dotenv/load.ts";
// 3rd party libs
import { Command } from "https://deno.land/x/[email protected]/command/mod.ts";
import {
Application,
Context,
helpers,
Router,
RouterContext,
Status,
} from "https://deno.land/x/[email protected]/mod.ts";
import {
jwtVerify,
SignJWT as jwtSign,
} from "https://deno.land/x/[email protected]/index.ts";
// Interfaces & types
interface User {
uuid: string;
name: string;
email: string;
password?: string;
is_admin?: boolean;
}
type UserUpdated = Partial<User>;
interface Item {
uuid: string;
user_id: string;
[key: string]: unknown;
}
type Collection = Item[];
type ItemUpdated = Partial<Item>;
interface LoginPayload {
email: string;
password: string;
}
// Utils
async function generate(password: string) {
const a = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(password + salt),
);
return toHashString(a, "base64");
}
// Database
const kv = await Deno.openKv();
const salt = new TextEncoder().encode(Deno.env.get("SALT"));
const secret = new TextEncoder().encode(Deno.env.get("SECRET"));
const port = parseInt(Deno.env.get("PORT") || "8000");
async function getUsers() {
const iter = kv.list<User>({ prefix: ["users"] });
const users: User[] = [];
for await (const res of iter) {
delete res.value.password;
users.push(res.value);
}
return users;
}
async function getUserByEmail(email: string) {
const user = await kv.get<User>(["users_by_email", email]);
return user.value;
}
async function createUser(user: UserUpdated) {
if (!user.email) {
throw new Error("Password is required");
}
if (!user.password) {
throw new Error("Password is required");
}
// generate UUID for this user.
const uuid = crypto.randomUUID();
user.uuid = uuid;
user.password = await generate(user.password);
const primaryKey = ["users", user.uuid];
const secondaryKey = ["users_by_email", user.email];
const res = await kv.atomic()
.check({ key: primaryKey, versionstamp: null })
.check({ key: secondaryKey, versionstamp: null })
.set(primaryKey, user)
.set(secondaryKey, user)
.commit();
if (!res.ok) {
throw new Error("Unable to create user");
}
return user;
}
async function addItem(collectionName: string, item: Item) {
const uuid = crypto.randomUUID();
item.uuid = uuid;
const res = await kv.set([collectionName, uuid], item);
if (!res.ok) {
throw new Error("Unable to add item to collection");
}
return item;
}
async function getCollectionItems(collectionName: string) {
const collection = kv.list<Item>({ prefix: [collectionName] });
const items: Collection = [];
for await (const item of collection) {
items.push(item.value);
}
return items;
}
async function getItem(collectionName: string, uuid: string) {
const item = await kv.get([collectionName, uuid]);
return item.value!;
}
async function updateItem(
collectionName: string,
uuid: string,
item: ItemUpdated,
) {
const oldItem = await getItem(collectionName, uuid);
if (!oldItem) return;
item = { ...oldItem, ...item };
item.uuid = uuid;
item = Object.fromEntries(Object.entries(item).filter(([_, v]) => v != null));
const _res = await kv.set([collectionName, uuid], item);
return item;
}
async function deleteItem(collectionName: string, uuid: string) {
await kv.delete([collectionName, uuid]);
return;
}
async function deleteItems(collectionName: string) {
const collection = kv.list<Item>({ prefix: [collectionName] });
for await (const item of collection) {
kv.delete(item.key);
}
return;
}
// Web server
const { getQuery } = helpers;
const app = new Application();
const apiRouter = new Router({ prefix: "/api/v1" });
const authRouter = new Router({ prefix: "/auth" });
const collectionsRouter = new Router({ prefix: "/collections" });
// Auth routes
authRouter.post("/register", async (context: RouterContext<"/register">) => {
const body: UserUpdated = await context.request.body().value;
const user: UserUpdated = await createUser(body);
context.response.body = { user };
context.response.status = 200;
});
authRouter.post("/login", async (context: RouterContext<"/login">) => {
const body: LoginPayload = await context.request.body().value;
const user: User | null = await getUserByEmail(body.email);
const password = await generate(body.password);
if (user && password === user.password) {
const jwt = await new jwtSign({
"uuid": user.uuid,
"name": user.name,
"email": user.email,
})
.setSubject(user.uuid)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setIssuer("urn:ignacio:server")
.setAudience("urn:ignacio:app")
.setExpirationTime("2h")
.sign(secret);
context.response.body = { data: { id_token: jwt } };
context.cookies.set("id_token", jwt, { httpOnly: true });
} else {
context.response.body = { data: { message: "Unauthorize" } };
context.response.status = 403;
}
});
authRouter.get("/users", async (context: RouterContext<"/users">) => {
const users = await getUsers();
context.response.body = { data: { users } };
});
collectionsRouter.post(
"/:collection",
async (context: Context) => {
const params = getQuery(context, { mergeParams: true });
const item = await addItem(
params.collection,
await context.request.body().value,
);
context.response.body = {
data: {
...item,
},
};
},
);
collectionsRouter.delete(
"/:collection",
async (context: RouterContext<"/:collection">) => {
const params = getQuery(context, { mergeParams: true });
await deleteItems(params.collection);
context.response.status = Status.NoContent;
},
);
collectionsRouter.get(
"/:collection/items",
async (context: RouterContext<"/:collection/items">) => {
const params = getQuery(context, { mergeParams: true });
const items = await getCollectionItems(params.collection);
context.response.body = {
data: {
[params.collection]: items,
},
};
},
);
collectionsRouter.get(
"/:collection/items/:uuid",
async (context: RouterContext<"/:collection/items/:uuid">) => {
const params = getQuery(context, { mergeParams: true });
const item = await getItem(params.collection, params.uuid);
if (!item) {
context.response.status = 404;
} else {
context.response.body = {
data: {
...item,
},
};
}
},
);
collectionsRouter.put(
"/:collection/items/:uuid",
async (context: RouterContext<"/:collection/items/:uuid">) => {
const params = getQuery(context, { mergeParams: true });
const item = await updateItem(
params.collection,
params.uuid,
await context.request.body().value,
);
if (item) {
context.response.body = {
data: {
...item,
},
};
} else {
context.response.status = 404;
}
},
);
collectionsRouter.delete(
"/:collection/items/:uuid",
async (context: Context) => {
const params = getQuery(context, { mergeParams: true });
await deleteItem(params.collection, params.uuid);
context.response.status = Status.NoContent;
},
);
collectionsRouter.use(async (context: Context, next) => {
const token = await context.cookies.get("id_token");
if (!token) {
context.response.status = 401;
return;
}
try {
const jwt = await jwtVerify(token, secret, {
audience: "urn:ignacio:app",
issuer: "urn:ignacio:server",
});
context.state.user = jwt.payload;
await next();
} catch (_err) {
context.response.status = 401;
}
});
app.use(async (context, next) => {
try {
await context.send({
root: `${Deno.cwd()}/`,
index: "index.html",
});
} catch {
await next();
}
});
apiRouter.use(authRouter.routes());
apiRouter.use(authRouter.allowedMethods());
apiRouter.use(collectionsRouter.routes());
apiRouter.use(collectionsRouter.allowedMethods());
app.use(apiRouter.routes());
app.use(apiRouter.allowedMethods());
const serve = new Command()
.description("Serve app.")
.action(() => {
app.listen({ port });
});
await new Command()
.name("Milou backend server")
.description("A simple backend server for fast prototyping.")
.version("v0.0.1")
.command("serve", serve)
.parse(Deno.args);