Skip to content

Commit 35f5a86

Browse files
committed
login & signup
1 parent 6212172 commit 35f5a86

File tree

11 files changed

+189
-11
lines changed

11 files changed

+189
-11
lines changed

.env

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ FRONTEND_BASE_URL=http://localhost:3000/
1111

1212
# DB Credentials
1313
DB_USER = karthik-dell
14-
DB_PASS = x6cPNVZP6XuTnqh3
14+
DB_PASS =
1515
DB_NAME = ecommerce
16-
DB_HOST = cluster0.bksct.mongodb.net
16+
DB_HOST =
1717

18+
ACCESS_TOKEN_SECERT = MONGO_DB_NODE_JS_API
1819
PASSWORD_SALT = MONGO_DB_NODE_JS_API
1920
JWT_SECRET = MONGO_DB_NODE_JS_API

controller/auth.controller.js

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,67 @@ const bcrypt = require("bcrypt");
22
const jwt = require("jsonwebtoken");
33

44
const {userService} = require('../services/index');
5-
const {errorCode, successCode, InvalidLogin} = require('../utils/message')
5+
const {errorCode, successCode, InvalidLogin, InvalidOtp} = require('../utils/message');
6+
const { ACCESS_TOKEN_SECERT } = require("../utils/config");
7+
const { UnauthorizedError, handleCustomError } = require("../utils/errors");
68

79
module.exports = {
810
userSignup : async (req, res) => {
911
const { name, email, phone, password } = req.body;
1012
try {
11-
let items = {name, email, phone, password}
13+
let otp = Math.floor(Math.random() * 900000) + 100000;
14+
let hashedOTP = await bcrypt.hash(otp.toString(), 10)
15+
let current_timestamp = Math.floor(Date.now() / 1000)
16+
let signupSession = await bcrypt.hash(`${current_timestamp}-${email}`, await bcrypt.genSalt(10))
17+
let items = {name, email, phone, password, signupSession, otp:otp, otptimestamp:current_timestamp}
1218
const users = await userService.createNewUser(items);
1319
if(users.status === 0){
1420
return res.json({statusCode:errorCode, message:users.data});
1521
}
1622
if (users.status === 1){
17-
return res.json({statusCode:successCode, result:users.data, message:'successful'});
23+
return res.json({statusCode:successCode, sessionId:users.data.signupSession, message:'successful'});
1824
} else {
1925
return res.json({statusCode:errorCode, message:'Fail to registered'});
2026
}
2127
} catch (error) {
2228
console.log("controller -- userSignup :: ", error);
23-
return res.status(500).json({ message: error.message,statusCode:errorCode });
29+
return handleCustomError(res, error)
30+
}
31+
},
32+
userSignupVerifyOTP : async (req, res) => {
33+
const { signupSession, otp } = req.body;
34+
try {
35+
let update = { accountStatus:1 }
36+
let filter = { signupSession }
37+
const users = await userService.getUsersByKey({signupSession})
38+
const usersData = await userService.getUsersByEmail(users.email)
39+
40+
if (users) {
41+
let current_timestamp = Math.floor(Date.now() / 1000)
42+
if((Number(users.otptimestamp)+10020 > Number(current_timestamp) && (Number(users.otp) === Number(otp)))){
43+
// console.log("otp, users.otp", typeof otp, typeof users.otp, await bcrypt.compare(otp, users.otp));
44+
const updateData = await userService.userAccountActivate(filter, update);
45+
const accessToken = jwt.sign(
46+
{
47+
user: {
48+
name: users.name,
49+
email: users.email,
50+
id: users.id,
51+
},
52+
},
53+
ACCESS_TOKEN_SECERT,
54+
{ expiresIn: "15m" }
55+
);
56+
return res.json({statusCode:successCode, token:accessToken, data:usersData, message:'successful'});
57+
} else {
58+
throw new UnauthorizedError(InvalidOtp);
59+
}
60+
} else {
61+
throw new UnauthorizedError(InvalidLogin);
62+
}
63+
} catch (error) {
64+
console.log("controller -- userLoginVerifyOTP :: ", error);
65+
return handleCustomError(res, error)
2466
}
2567
},
2668
userLogin : async (req, res) => {

controller/product.controller.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const { blogs } = require('../services/index');
2+
const { successCode, errorCode } = require('../util/message');
3+
4+
module.exports = {
5+
addProduct : async (req, res) => {
6+
const { title, description, } = req.body;
7+
try {
8+
// const response = await blogs.createNewBlog(title, description, authorId);
9+
// return res.send({
10+
// statusCode:successCode,
11+
// message: 'New Blog created successfully'
12+
// });
13+
} catch (error) {
14+
return res.status(500).send({
15+
statusCode:errorCode,
16+
message: error.message
17+
});
18+
}
19+
}
20+
}

models/user.model.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ const userSchema = new mongoose.Schema({
2323
type: Number,
2424
default:null
2525
},
26+
signupSession : {
27+
type : String,
28+
},
29+
accountStatus : {
30+
type: Number,
31+
default:0
32+
},
33+
otp : {
34+
type: String,
35+
},
36+
otptimestamp : {
37+
type: String,
38+
},
2639
date: { type: Date, default: Date.now },
2740
})
2841

postman/signup.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
curl --location 'http://localhost:4010/api/main/signup' \
2+
--header 'Content-Type: application/json' \
3+
--data-raw '{
4+
"name":"Kartik", "email":"kartik@gmail.com", "phone":"1234567891", "password":"123456789"
5+
}'
6+
7+

routes/auth.routes.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@ const { validateLogin, validateSignup } = require('../middleware/validation/requ
77

88
userRouter.post('/signup', validateSignup, authController.userSignup);
99
userRouter.post('/login', validateLogin, authController.userLogin);
10+
userRouter.post('/verifySignup', authController.userSignupVerifyOTP);
1011

1112
module.exports = {userRouter, adminRouter};

services/user.service.js

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,31 @@
11
const User = require("../models/user.model")
22

33
module.exports = {
4-
getUsersById : async(id) => {
4+
getUsersByKey : async(item) => {
55
try {
6-
const response = User.findOne({id})
6+
const response = User.findOne(item, {otp:0, otptimestamp:1}).select("otp otptimestamp email name signupSession")
77
return response
88
} catch (error) {
9-
console.error('Error in getUsersById : ', error);
9+
console.error('Error in getUsersByKey : ', error);
10+
throw error;
11+
}
12+
},
13+
getUsersById : async(_id) => {
14+
try {
15+
const response = User.findOne({_id})
16+
return response
17+
} catch (error) {
18+
console.error('Error in getUsersByKey : ', error);
19+
throw error;
20+
}
21+
},
22+
getUsersByEmail : async(email) => {
23+
try {
24+
// const response = User.findOne({email}).select("name email phone -_id")
25+
const response = User.findOne({email}, {name:1, email:1, phone:1, _id:0})
26+
return response
27+
} catch (error) {
28+
console.error('Error in getUsersByKey : ', error);
1029
throw error;
1130
}
1231
},
@@ -34,6 +53,20 @@ module.exports = {
3453
}
3554
}
3655
},
56+
userAccountActivate : async(filter, update) => {
57+
try {
58+
const response = await User.findOneAndUpdate(filter, update)
59+
return { status:1, data:response }
60+
} catch (error) {
61+
console.error('Error in createNewUser : ', error);
62+
let typesdata = Object.keys(error.keyValue)
63+
if(error.code === 11000){
64+
return { status:0, data:`${typesdata[0]} already exists` }
65+
} else {
66+
throw error;
67+
}
68+
}
69+
},
3770
loginUser : async(item) => {
3871
try {
3972
const response = User.findOne(item)

utils/config.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,7 @@ module.exports = {
44
PORT : process.env.PORT || 4010,
55
APP_NAME : process.env.APP_NAME,
66
SALT : process.env.PASSWORD_SALT,
7-
JWT_SECRET : process.env.JWT_SECRET
7+
JWT_SECRET : process.env.JWT_SECRET,
8+
PASSWORD_SALT : process.env.PASSWORD_SALT,
9+
ACCESS_TOKEN_SECERT : process.env.ACCESS_TOKEN_SECERT
810
};

utils/db.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ if(SERVER.toLowerCase() === 'localhost' ||
2424

2525
} else {
2626
uri = `mongodb+srv://${username}:${password}@${cluster}/${dbname}`;
27+
// uri = "mongodb+srv://karthik-dell:x6cPNVZP6XuTnqh3@cluster0.bksct.mongodb.net/ecommerce";
2728
options = {
2829
useNewUrlParser: true,
2930
useUnifiedTopology: true

utils/errors.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
const { errorCode } = require("./message");
2+
3+
class NotFoundError extends Error {
4+
constructor(message) {
5+
super(message);
6+
this.name = 'NotFoundError';
7+
this.status = 404;
8+
}
9+
}
10+
11+
class qwqwqw extends Error {
12+
constructor(message) {
13+
super(message);
14+
this.name = 'qwqwqw';
15+
this.status = 200;
16+
}
17+
}
18+
19+
class UnauthorizedError extends Error {
20+
constructor(message) {
21+
super(message);
22+
this.name = 'UnauthorizedError';
23+
this.status = 401;
24+
}
25+
}
26+
27+
class UnprocessableEntity extends Error {
28+
constructor(message) {
29+
super(message);
30+
this.name = 'UnprocessableEntity';
31+
this.status = 422;
32+
}
33+
}
34+
35+
const handleCustomError =(res, error) => {
36+
if (
37+
error instanceof NotFoundError ||
38+
error instanceof UnauthorizedError ||
39+
error instanceof UnprocessableEntity
40+
) {
41+
return res.status(error.status).send({
42+
message: error.message,
43+
statusCode: errorCode
44+
});
45+
} else {
46+
return res.status(500).send({
47+
message: error.message,
48+
statusCode: errorCode
49+
});
50+
}
51+
}
52+
53+
module.exports = {
54+
NotFoundError,
55+
UnauthorizedError,
56+
UnprocessableEntity,
57+
handleCustomError
58+
};

utils/message.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ module.exports = {
2222
IncorrectPassword: 'The password entered is incorrect!',
2323
AccountDeactivate: 'Your account has been deactivated on the platform, Please contact admin for help!',
2424
OtpTimeOut: 'Otp has timed out, new Otp! sent successfully',
25-
InvalidOtp: 'Wrong Otp',
25+
InvalidOtp: 'Otp Expired or Invalid Otp',
2626
NextDateError: 'Next action date must be greater than today',
2727
IsAdminError: 'Only Admin can Filter by this',
2828
TransitionNotAllowed:'transition not Allowed',

0 commit comments

Comments
 (0)