Passed
Pull Request — main (#12)
by Julia
02:02
created

server/src/models/emp.js   A

Complexity

Total Complexity 10
Complexity/F 1.67

Size

Lines of Code 129
Function Count 6

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 61
mnd 4
bc 4
fnc 6
dl 0
loc 129
rs 10
bpm 0.6666
cpm 1.6666
noi 1
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
B emp.js ➔ login 0 12 6
A emp.js ➔ comparePasswords 0 40 4
1
import bcrypt from "bcryptjs";
2
import jwt from "jsonwebtoken";
3
import { db } from "./db.js"
4
5
6
// separata modeller för emp och user eftersom
7
// inloggningen och registereringen fungerar annorlunda
8
// och checkToken funktionen kommer också skilja sig,
9
// dels ingen check för roll och dets lyfta ut idt och lägga till på req.body
10
const emp = {
11
    getOneFromDb: async function(username) {
12
        const result = await db.queryWithArgs(`CALL emp_login(?);`, [username]);
13
        return result[0];
14
    },
15
    checkToken: function(req, res, next, acceptableRoles=["admin"]) {
16
        let token = req.headers["x-access-token"];
17
18
        jwt.verify(token, process.env.JWT_SECRET, function (err, decoded) {
19
            if (err) {
20
                return res.status(500).json({
21
                    errors: {
22
                        status: 500,
23
                        source: "/login",
24
                        title: "Failed authentication",
25
                        detail: err.message
26
                    }
27
                });
28
            }
29
30
            // om inget token är med kommer det att kastas
31
            // ett fel här eftersom decoded inte kommer ha attributet role som alla token
32
            // som tillhör anställda ska ha
33
            if (!acceptableRoles.includes(decoded.role)) {
34
                // if unauthorized request it is safer
35
                // to make it look like the page does not
36
                // exist
37
                return res.status(404).json({
38
                    errors: {
39
                        status: 404,
40
                        source: req.originalUrl,
41
                        title: "Not found",
42
                        detail: "Page not found"
43
                    }
44
                });
45
            }
46
47
            req.emp = {
48
                id: decoded.id,
49
                role: decoded.role
50
            };
51
52
            console.log(req.emp);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
53
            return next();
54
        });
55
    },
56
57
    /**
58
     * @description Function that handles admin login
59
     *
60
     * @param {Request} req Request object
61
     * @param {Response} res Response object
62
     * @param {Function} next Next function
63
     *
64
     * @returns {Object} JSON object
65
     */
66
    login: async function login(req, res) {
67
        const username = req.body.username;
68
        const password = req.body.password;
69
70
        const emp = await this.getOneFromDB(username);
71
72
        // om användarnamn saknas kommer
73
        // databasen lyfta ett error
74
        // om lösenord saknas kommer det fångas i bcrypt compare
75
76
        return this.comparePasswords(res, password, emp);
77
    },
78
    /**
79
     * @description Function that compares passwords
80
     *
81
     * @param {Request} req Request object
82
     * @param {String} password Password
83
     * @param {Object} user User
84
     *
85
     * @returns {Object} JSON object
86
     */
87
    comparePasswords: function comparePasswords(res, password, emp) {
88
        bcrypt.compare(password, emp.hash, (err, result) => {
89
            if (err) {
90
                return res.status(500).json({
91
                    errors: {
92
                        status: 500,
93
                        source: "/login",
94
                        title: "bcrypt error",
95
                        detail: "bcrypt error"
96
                    }
97
                });
98
            }
99
100
            if (result) {
101
                const payload = {
102
                    id: emp.id,
103
                    role: emp.role 
104
                };
105
                const jwtToken = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: "24h" });
106
107
                return res.json({
108
                    data: {
109
                        type: "success",
110
                        message: "User logged in",
111
                        user: payload,
112
                        token: jwtToken
113
                    }
114
                });
115
            }
116
117
            return res.status(401).json({
118
                errors: {
119
                    status: 401,
120
                    source: "/login",
121
                    title: "Wrong password",
122
                    detail: "Password is incorrect."
123
                }
124
            });
125
        });
126
    }
127
};
128
129
export default emp;