Skip to content

Commit 899998a

Browse files
committed
Simple Authentication completed
0 parents  commit 899998a

File tree

10 files changed

+1841
-0
lines changed

10 files changed

+1841
-0
lines changed

.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
2+
# Server
3+
server/node_modules
4+
server/.env
5+
server/requests.http

server/config/connect.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const mongoose = require("mongoose");
2+
3+
const dbConnect = async () => {
4+
try {
5+
await mongoose.connect(process.env.MONGO_URI, {
6+
useNewUrlParser: true,
7+
useUnifiedTopology: true,
8+
})
9+
console.log('Database Connected');
10+
} catch (err) {
11+
console.log(err);
12+
process.exit(1);
13+
}
14+
}
15+
16+
module.exports = { dbConnect };

server/controllers/authController.js

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
const asyncHandler = require("express-async-handler");
2+
const { validateRegisterInput } = require("../utils/validators");
3+
const bcryptjs = require("bcryptjs");
4+
const jwt = require("jsonwebtoken");
5+
const JWT_SECRET_KEY = process.env.JWT_SECRET_KEY
6+
const User = require("../models/User");
7+
8+
// @Desc Public
9+
// @Route /auth/register
10+
// @Access Public
11+
const register = asyncHandler(async (req, res) => {
12+
const { name, email, password } = req.body;
13+
14+
// Validating Data
15+
const validate = validateRegisterInput(email, name, password);
16+
17+
if (!validate.valid) {
18+
res.status(400)
19+
throw new Error(JSON.stringify(validate.errors))
20+
}
21+
22+
// Check if user exists
23+
const userExists = await User.findOne({ email });
24+
if (userExists) {
25+
res.status(400)
26+
throw new Error('User Already exists')
27+
}
28+
29+
// Hash Password
30+
const salt = await bcryptjs.genSalt(10);
31+
const hashedPassword = await bcryptjs.hash(password, salt);
32+
33+
// Save user in database
34+
const user = new User({
35+
name,
36+
email,
37+
password: hashedPassword
38+
})
39+
40+
await user.save();
41+
res.json({
42+
_id: user._id,
43+
name: user.name,
44+
email: user.email,
45+
token: generateToken(user._id)
46+
});
47+
})
48+
49+
// @Desc Public
50+
// @Route /auth/login
51+
// @Access Public
52+
const login = asyncHandler(async (req, res) => {
53+
const { email, password } = req.body;
54+
55+
// Check if user exists
56+
const userExists = await User.findOne({ email });
57+
if (!userExists) {
58+
res.status(400)
59+
throw new Error('No such user exists')
60+
}
61+
62+
// Verify Password
63+
const isMatch = await bcryptjs.compare(password, userExists.password);
64+
if (!isMatch) {
65+
res.status(400)
66+
throw new Error('Incorrect Password')
67+
}
68+
69+
res.json({
70+
_id: userExists._id,
71+
name: userExists.name,
72+
email: userExists.email,
73+
token: generateToken(userExists._id)
74+
});
75+
})
76+
77+
const generateToken = (id) => {
78+
const payload = { id };
79+
return jwt.sign(payload, JWT_SECRET_KEY, { expiresIn: '365d' })
80+
}
81+
82+
module.exports = {
83+
register,
84+
login
85+
}

server/middleware/errHandler.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const errHandler = (err, req, res, next) => {
2+
const statusCode = res.statusCode ? res.statusCode : 500;
3+
4+
res.status(statusCode)
5+
res.json({
6+
message: err.message,
7+
stack: process.env.NODE_ENV === 'development' ? err.stack : null
8+
})
9+
10+
}
11+
12+
module.exports = errHandler;

server/models/User.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const mongoose = require("mongoose");
2+
3+
const userSchema = new mongoose.Schema({
4+
name: {
5+
type: String,
6+
required: [true, 'Name must1 not be empty'],
7+
trim: true
8+
},
9+
email: {
10+
type: String,
11+
required: [true, 'Email can not be empty'],
12+
trim: true
13+
},
14+
password: {
15+
type: String,
16+
required: true,
17+
trim: true
18+
}
19+
}, { timestamps: true })
20+
21+
module.exports = mongoose.model('user', userSchema);

0 commit comments

Comments
 (0)