Skip to content
This repository was archived by the owner on Apr 20, 2023. It is now read-only.

Commit f32bb42

Browse files
committed
Authentication complete
0 parents  commit f32bb42

File tree

10 files changed

+4995
-0
lines changed

10 files changed

+4995
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/node_modules
2+
.env

app.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const express = require("express");
2+
const mongoose = require("mongoose");
3+
const bodyParser = require("body-parser");
4+
const cookieParser = require("cookie-parser");
5+
const cors = require("cors");
6+
7+
const app = express();
8+
9+
const authRoutes = require('./routes/auth.routes');
10+
11+
require("dotenv").config();
12+
13+
app.use(bodyParser.urlencoded({ extended: true }));
14+
app.use(bodyParser.json());
15+
app.use(cookieParser(process.env.COOKIE_SECRET));
16+
app.use(
17+
cors({
18+
origin: ["http://localhost:3001"],
19+
credentials: true,
20+
allowedHeaders: ["Content-Type", "Authorization"],
21+
})
22+
);
23+
24+
app.use('/auth', authRoutes);
25+
26+
mongoose
27+
.connect("mongodb://localhost:27017/techoptimumdasboard")
28+
.then((result) => {
29+
app.listen(3000, () => {
30+
console.log("Connected!");
31+
});
32+
})
33+
.catch((err) => {
34+
console.log(err);
35+
});

controllers/auth.controllers.js

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
const User = require("../models/user.model");
2+
3+
const generateToken = require("../utils/authMethods.utils").generateAccessToken;
4+
const hashPassword = require("../utils/authMethods.utils").hashPassword;
5+
const checkPassword = require("../utils/authMethods.utils").checkPassword;
6+
7+
exports.postLoginController = (req, res) => {
8+
const email = req.body.email;
9+
const password = req.body.password;
10+
const paramsExist = Object.keys(req.query).length > 0;
11+
if (!paramsExist) {
12+
User.findOne({
13+
email,
14+
})
15+
.then((users) => {
16+
checkPassword(users.password, password).then((result) => {
17+
if (result) {
18+
generateToken(email)
19+
.then((token) => {
20+
return res
21+
.cookie("token", token, {
22+
maxAge: 1000 * 60 * 60,
23+
httpOnly: true,
24+
signed: true,
25+
})
26+
.status(200)
27+
.json({ success: true, username: users.username });
28+
})
29+
.catch((err) => {
30+
console.log(err);
31+
return res.status(505).json({
32+
success: false,
33+
errType: "tkngenerr",
34+
msg: "Internal Server Error.",
35+
});
36+
});
37+
} else {
38+
return res.status(422).json({
39+
success: false,
40+
msg: "Invalid email or password.",
41+
errType: "lgnfail",
42+
});
43+
}
44+
});
45+
})
46+
.catch((err) => {
47+
res.status(505).json({
48+
success: false,
49+
msg: "Internal Server Error.",
50+
errType: "dberr",
51+
});
52+
console.log(err);
53+
});
54+
}
55+
};
56+
57+
exports.postRegisterController = (req, res) => {
58+
const username = req.body.username;
59+
const email = req.body.email;
60+
const password = req.body.password;
61+
const confirmPassword = req.body.confirmPassword;
62+
63+
if (password === confirmPassword) {
64+
hashPassword(password).then((hashedPass) => {
65+
generateToken(email)
66+
.then((token) => {
67+
User.find({
68+
email: email,
69+
})
70+
.then((users) => {
71+
if (users.length > 0) {
72+
return res.status(422).json({
73+
success: false,
74+
msg: "Email already exists.",
75+
errType: "emalex",
76+
});
77+
} else {
78+
const user = new User({
79+
username,
80+
email,
81+
password: hashedPass,
82+
});
83+
user
84+
.save()
85+
.then((result) => {
86+
return res
87+
.cookie("token", token, {
88+
maxAge: 1000 * 60 * 60,
89+
signed: true,
90+
httpOnly: true,
91+
})
92+
.status(200)
93+
.json({
94+
success: true,
95+
username,
96+
});
97+
})
98+
.catch((err) => {
99+
res.status(505).json({
100+
msg: "There was a problem, try again later.",
101+
errType: "dberr",
102+
});
103+
console.log(err);
104+
});
105+
}
106+
})
107+
.catch((err) => {
108+
console.log(err);
109+
return res.status(505).json({
110+
success: false,
111+
errType: "dberr",
112+
msg: "Internal Server Error.",
113+
});
114+
});
115+
})
116+
.catch((err) => {
117+
console.log(err);
118+
return res.status(505).json({
119+
success: false,
120+
errType: "tkngenerr",
121+
msg: "Internal Server Error.",
122+
});
123+
});
124+
});
125+
} else {
126+
res.status(422).json({
127+
success: false,
128+
msg: "Passwords don't match.",
129+
errType: "pwdmm",
130+
});
131+
}
132+
};
133+
134+
exports.postLogoutController = (req, res) => {
135+
res.clearCookie("token").status(200).json({ success: true });
136+
};

middleware/authenticateToken.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const jwt = require('jsonwebtoken');
2+
const User = require('../models/user.model');
3+
require('dotenv').config();
4+
5+
const authenticateToken = (req, res, next) => {
6+
const authHeader = req.headers['authorization']
7+
const token = authHeader && authHeader.split(" ")[1]
8+
9+
if (token === null) return res.send({success: false, msg: "Not authorized."})
10+
11+
jwt.verify(token, String(process.env.TOKEN_SECRET), (err, user) => {
12+
console.log(err);
13+
14+
if (err) return res.send({success: false, msg: "Token invalid.", err: "tkninv"})
15+
16+
User.findOne({
17+
email: user.data,
18+
}).then(user => {
19+
req.user = user;
20+
next();
21+
}).catch(err => {
22+
console.log(err);
23+
})
24+
})
25+
}
26+
27+
module.exports = authenticateToken;

models/user.model.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const mongoose = require('mongoose');
2+
3+
const Schema = mongoose.Schema;
4+
5+
const UserSchema = new Schema({
6+
username: {
7+
type: String,
8+
required: true,
9+
},
10+
email: {
11+
type: String,
12+
required: true,
13+
},
14+
password: {
15+
type: String,
16+
required: true,
17+
}
18+
});
19+
20+
module.exports = mongoose.model('user', UserSchema);

0 commit comments

Comments
 (0)