-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
279 lines (180 loc) · 4.69 KB
/
main.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
import { App, Request, Response,logger,parser } from "https://deno.land/x/attain/mod.ts";
import { init, MongoClient } from "https://deno.land/x/mongo@v0.6.0/mod.ts";
import * as bcrypt from "https://deno.land/x/bcrypt/mod.ts";
import * as flags from "https://deno.land/std/flags/mod.ts";
const { args, exit } = Deno;
const DEFAULT_PORT = 8080;
const argPort = flags.parse(args).port;
const port = argPort ? Number(argPort) : DEFAULT_PORT;
if (isNaN(port)) {
console.log("port is not number");
exit(1);
}
import { validateJwt } from "https://deno.land/x/djwt/validate.ts";
import {
makeJwt,
setExpiration,
Jose,
Payload,
} from "https://deno.land/x/djwt/create.ts";
await init();
const client = new MongoClient();
client.connectWithUri(
"mongodb+srv://ajax:eniola@cluster0-yve81.mongodb.net/test",
);
const db = client.database('test');
const todo= db.collection('todos');
const users= db.collection('users');
const app = new App();
const key="denos";
app.use(logger);
app.use(parser);
const middleware=(req:Request,res:Response)=>{
console.log('my middle way');
}
app.use(middleware,async (req,res)=>{
let header= req.headers;
var obj = new Headers(header);
var auth= obj.get('authorization') as any;
const token = auth?.toString().split(' ')[1];
const url='http://localhost:3500'
if(req.url.toString()==url+'/auth' || req.url.toString()==url+'/reg' || req.url.toString()==url ){
}else{
if(token==null)res.status(400).send({status:'Missing token'});
try{
if( await validateJwt(token,key)){
}
else{
res.status(400).send({status:"Bad token"});
}
}catch(err){
res.status(400).send({status:"Bad token"});
}
}
})
app.get("/", (req, res) => {
res.status(200).send(`
<!doctype html>
<html lang="en">
<body>
<h1>My Todo api</h1>
</body>
</html>
`);
});
app.get("/todo", async (req, res) => {
// By the parser middleware, the body and search query get parsed and saved.
try{
const todos = await todo.find();
res.status(200).send({ data: todos });
}
catch(err){
res.status(400).send({ data: err });
}
});
app.post("/todo", async (req, res) => {
const {name,description} = req.params;
if(name!=undefined && description!=undefined){
try{
const insert = await todo.insertOne({
name:name,
description:description
})
res.status(200).send({ data: insert.$oid });
}catch(err){
res.status(400).send({ data: err });
}
}else{
res.status(400).send({ data: 'Incorrect information' });
}
});
app.put("/todo/:id", async (req, res) => {
const {id,name,description} = req.params;
if(name!=undefined && description!=undefined && id!=undefined){
try{
const update = await todo.updateOne({
_id:{
$oid:id
}
},req.params)
res.status(200).send({ data: 'Todo was updated' });
}catch(err){
res.status(400).send({ data: err });
}
}else{
res.status(400).send({ data: 'Incorrect information' });
}
});
app.delete("/todo/:id", async (req, res) => {
const {id} = req.params;
if( id!=undefined){
try{
const remove = await todo.deleteOne({
_id:{
$oid:id
}
})
res.status(400).send({ data: 'Todo removed' });
}catch(err){
res.status(400).send({ data: err });
}
}else{
res.status(400).send({ data: 'Incorrect information' });
}
});
app.post("/reg",async (req,res)=>{
const {email,password }= req.params;
if(email!=undefined && password!=undefined){
try{
const hash = bcrypt.hashpw(password);
const reg= await users.insertOne({
email:email,
password:hash
})
res.status(200).send('ACCOUNT CREATED');
}catch(err){
res.status(400).send(err);
}
}else{
res.status(400).send({ data: 'Incorrect information' });
}
})
app.post("/auth",async (req,res)=>{
try{
const user:any = await validate(req);
const payload:Payload={
iss:user._id.$oid,
}
const header:Jose={
alg:"HS256",
typ:"JWT"
}
const token = makeJwt({header,payload,key});
res.status(200).send({
token:token,
_id:user._id.$oid
});
}
catch(err){
res.status(400).send(err);
}
})
function validate(req:any){
const {email, password} = req.params;
return new Promise(async (resolve,reject)=>{
try{
const user = await users.findOne({email:email});
const pwdValidate = bcrypt.checkpw(password,user.password);
if(pwdValidate){
resolve(user);
}
else{
reject('Authentication failed.')
}
}catch(err){
reject('Authentication failed.')
}
})
}
app.listen({ port });
console.log("http://localhost:3500");