-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthorize.js
More file actions
46 lines (38 loc) · 1.3 KB
/
Copy pathauthorize.js
File metadata and controls
46 lines (38 loc) · 1.3 KB
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
const jwt = require('jsonwebtoken')
const { MongoClient } = require("mongodb");
const ObjectID = require('mongodb').ObjectId;
const dbUrl = process.env.DB_URL
async function authorize(req,res,next)
{
if(req.headers.authorization){
jwt.verify(req.headers.authorization,process.env.AUTH_KEY, async (err,decoded)=>{
if(decoded != undefined){
if(decoded.user_id == (await getById(decoded.user_id)))
{
console.log(decoded)
next()
}else{
res.status(401).json({message : "Authorization Failed"})
}
}else{
res.status(403).json({message : "Forbidden"})
}
})
}else{
res.status(401).json({message:"No Token Found"})
}
}
async function getById(id){
try {
let client = await MongoClient.connect(dbUrl);
let db = client.db('Url-Shortener');
let data = await db.collection("users").findOne({ _id : ObjectID(id)})
console.log(data._id)
let user_id = data._id;
console.log(user_id)
return user_id;
} catch (error) {
console.log(error)
}
}
module.exports = authorize ;