-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicAuth.js
More file actions
52 lines (48 loc) · 1.13 KB
/
basicAuth.js
File metadata and controls
52 lines (48 loc) · 1.13 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
47
48
49
50
51
52
import auth from "basic-auth";
import customerRepository from "../repositories/customer.repository.js";
async function basicAuth(req, res, next) {
const user = auth(req);
if (
user.name &&
user.name === "admin" &&
user.pass === "desafio-igti-nodejs"
) {
next();
} else {
const customer = await customerRepository.getCustomerByEmail(user.name);
if (
customer &&
customer.email.toLowerCase() === user.name.toLowerCase() &&
customer.password === user.pass
) {
next();
} else {
res.statusCode = 401;
res.end("Unautenthicated");
}
}
}
function getRole(username) {
if (username == "admin") {
return "admin";
} else {
return "user";
}
}
function authorize(...allowed) {
const isAllowed = (role) => allowed.indexOf(role) > -1;
return (req, res, next) => {
const user = auth(req);
if (user && user.name) {
const role = getRole(user.name);
if (isAllowed(role)) {
next();
} else {
res.status(401).send("Forbidden");
}
} else {
res.status(401).send("Unauthorized");
}
};
}
export { authorize, basicAuth };