8000 initial setup · vishal-coder/CRM_backend@6dd4ae7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6dd4ae7

Browse files
committed
initial setup
1 parent 8f9f428 commit 6dd4ae7

File tree

11 files changed

+4346
-0
lines changed

11 files changed

+4346
-0
lines changed

.gitignore

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

controllers/AuthController.js

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
import bcrypt from "bcrypt";
2+
import Crypto from "crypto";
3+
import jwt from "jsonwebtoken";
4+
import {
5+
activatateUser,
6+
getDBUserByEmail,
7+
insertAccountConfirmationCode,
8+
insertToken,
9+
registerUser,
10+
updatePassword,
11+
verifyEmailToken,
12+
} from "../models/AuthModel.js";
13+
import { getHashedPassword } from "../util/hashing.js";
14+
import {
15+
sendAccountVerificationMail,
16+
sendPasswordResetMail,
17+
} from "../util/mailer.js";
18+
19+
/**
20+
* POST /signup
21+
*
22+
*/
23+
export const signup = async (req, res) => {
24+
console.log("signup requested", req.body);
25+
const { firstname, lastname, phone, address, username, password, about } =
26+
req.body;
27+
const dBUserByEmail = await getDBUserByEmail({ username: username });
28+
if (dBUserByEmail) {
29+
return res.status(401).send({ message: "User Already Exists" });
30+
}
31+
32+
let hashedPassword = await getHashedPassword(password);
33+
const registerResult = await registerUser({
34+
firstname: firstname,
35+
lastname: lastname,
36+
username: username,
37+
password: hashedPassword,
38+
phone: phone,
39+
address: address,
40+
about: about,
41+
});
42+
43+
var confirmationToken = await jwt.sign(
44+
{ id: registerResult.insertedId.toString() },
45+
process.env.SECRET_KEY
46+
);
47+
48+
const isInserted = await insertAccountConfirmationCode(
49+
{ username: username },
50+
confirmationToken
51+
);
52+
console.log("isInserted", isInserted);
53+
sendAccountVerificationMail(username, confirmationToken, firstname);
54+
55+
res.status(200).send({
56+
message: "User was registered successfully! Please Verify Your Email!",
57+
success: true,
58+
});
59+
};
60+
61+
export const login = async (req, res) => {
62+
const { username, password } = req.body;
63+
64+
const dBUserByEmail = await getDBUserByEmail({ username: username });
65+
66+
if (!dBUserByEmail) {
67+
return res.send({ message: "Invalid Credentials", success: false });
68+
}
69+
70+
const isActive = dBUserByEmail.isActive;
71+
console.log("isActive", dBUserByEmail.isActive);
72+
if (!isActive) {
73+
return res.status(401).send({
74+
message: "Before login, Please verify your email",
75+
success: false,
76+
});
77+
}
78+
79+
const isPasswordMathced = await bcrypt.compare(
80+
password,
81+
dBUserByEmail.password
82+
);
83+
84+
if (!isPasswordMathced) {
85+
console.log("Invalid Credentials");
86+
return res.send({ message: "Invalid Credentials", success: false });
87+
}
88+
89+
var token = jwt.sign(
90+
{ id: dBUserByEmail._id.toString() },
91+
process.env.SECRET_KEY
92+
);
93+
res.header("x-auth-token", token);
94+
res.send({
95+
message: "user logged successfully",
96+
success: true,
97+
token: token,
98+
user: {
99+
name: dBUserByEmail.firstname,
100+
email: dBUserByEmail.username,
101+
userType: dBUserByEmail.role,
102+
address: dBUserByEmail.address,
103+
token: token,
104+
},
105+
});
106+
};
107+
108+
export const forgotPassword = async (req, res) => {
109+
const { email } = req.body;
110+
111+
const dBUserByEmail = await getDBUserByEmail({ username: email });
112+
113+
if (!dBUserByEmail) {
114+
return res.status(401).send({
115+
message: "User with given email doesn't exists.",
116+
success: false,
117+
});
118+
}
119+
120+
let resetToken = Crypto.randomBytes(16).toString("hex");
121+
let hashedResetToken = await getHashedPassword(resetToken);
122+
123+
let tokenUpdate = await insertToken({ username: email }, hashedResetToken);
124+
if (!tokenUpdate) {
125+
return res.status(401).send({
126+
message: "Something went wront..Please try again later.",
127+
success: false,
128+
});
129+
}
130+
131+
const mailsuccess = await sendPasswordResetMail(
132+
email,
133+
hashedResetToken,
134+
dBUserByEmail._id
135+
);
136+
137+
if (!mailsuccess) {
138+
return res.status(401).send({
139+
message: "Something went wront..Please try again later.",
140+
success: false,
141+
});
142+
}
143+
144+
res.status(200).send({
145+
message: "verification mail sent to your email address",
146+
success: true,
147+
});
148+
};
149+
150+
export const resetpassword = async (req, res) => {
151+
const { password } = req.body;
152+
const { token } = req.query;
153+
154+
const hashedPassword = await getHashedPassword(password);
155+
const query = { token: token };
156+
const updateQuery = { $set: { password: hashedPassword } };
157+
const updatePasswordResult = await updatePassword(query, updateQuery);
158+
159+
// const deleteTokenResult = await deleteToken(token); TODO: remove this comment and delete below line
160+
const deleteTokenResult = true;
161+
162+
if (!deleteTokenResult) {
163+
return res.send({
164+
message: "Invalid token..Please try resetting your password again!",
165+
success: false,
166+
});
167+
}
168+
169+
res.send({
170+
message: "Password reset successfully",
171+
success: true,
172+
});
173+
};
174+
175+
export const verifyEmail = async (req, res) => {
176+
const { token } = req.body;
177+
const isValidToken = await verifyEmailToken({ confirmationToken: token });
178+
179+
if (!isValidToken) {
180+
return res.status(404).send({ message: "Invalid token.", success: false });
181+
}
182+
183+
const activateUser = await activatateUser(token);
184+
185+
res.send({
186+
message: "email verified successfully !!!",
187+
success: true,
188+
});
189+
};
190+
191+
export const logoutUser = async (req, res) => {
192+
console.log("Inside handleLogoutUser");
193+
const { token } = req.body;
194+
// TODO: list token as expired or blacklisted
195+
196+
return res.send({ success: true, message: "user logged out successfully" });
197+
};

index.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import cors from "cors";
2+
import dotenv from "dotenv";
3+
import express from "express";
4+
import { MongoClient } from "mongodb";
5+
import { authRouter } from "./routes/auth.js";
6+
import http from "http";
7+
8+
const corsOptions = {
9+
origin: "*",
10+
optionsSuccessStatus: 200,
11+
};
12+
const app = express();
13+
dotenv.config();
14+
const server = http.createServer(app);
15+
const PORT = process.env.PORT || 5000;
16+
const MONGO_URL = process.env.MONGO_URL;
17+
18+
app.use(cors(corsOptions));
19+
app.use(express.json());
20+
21+
async function createConnection() {
22+
try {
23+
const client = new MongoClient(MONGO_URL);
24+
await client.connect();
25+
console.log("connected to database");
26+
return client;
27+
} catch (error) {
28+
console.log("error while connecting to database", error);
29+
}
30+
}
31+
export const client = await createConnection();
32+
33+
server.listen(PORT, () => {
34+
console.log("listening on *:", PORT);
35+
});
36+
37+
app.get("/", (req, res) => {
38+
res.send({ message: "default request" });
39+
});
40+
41+
app.use("/auth", authRouter);

middleware/authMiddleware.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import jwt from "jsonwebtoken";
2+
3+
export const verifyAuth = (request, response, next) => {
4+
try {
5+
const token = request.header("x-auth-token");
6+
if (!token) return response.status(401).send("Access Denied");
7+
console.log("verifyAuth - ", token);
8+
const verified = jwt.verify(token, process.env.SECRET_KEY);
9+
request.user = verified;
10+
next();
11+
} catch (err) {
12+
response.status(401).send({ error: err.message });
13+
}
14+
};

models/AuthModel.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { client } from "../index.js";
2+
3+
export async function getDBUserByEmail(data) {
4+
return client.db("blog").collection("users").findOne(data);
5+
}
6+
7+
export function registerUser(data) {
8+
return client.db("blog").collection("users").insertOne(data);
9+
}
10+
11+
export function insertToken(data, hashedResetToken) {
12+
return client
13+
.db("blog")
14+
.collection("users")
15+
.updateOne(data, {
16+
$set: { token: hashedResetToken, createdAt: new Date() },
17+
});
18+
}
19+
20+
export function getToken(data) {
21+
return client.db("blog").collection("users").findOne(data);
22+
}
23+
24+
export function updatePassword(query, updateQuery) {
25+
return client.db("blog").collection("users").updateOne(query, updateQuery);
26+
}
27+
export function deleteToken(token) {
28+
return client
29+
.db("blog")
30+
.collection("users")
31+
.updateOne({ token: token }, { $unset: { token: "" } });
32+
}
33+
export async function verifyEmailToken(data) {
34+
return client.db("blog").collection("users").findOne(data);
35+
}
36+
37+
export function activatateUser(token) {
38+
return client
39+
.db("blog")
40+
.collection("users")
41+
.updateOne({ confirmationToken: token }, { $set: { isActive: true } });
42+
}
43+
44+
export function insertAccountConfirmationCode(data, confirmationToken) {
45+
return client
46+
.db("blog")
47+
.collection("users")
48+
.updateOne(data, {
49+
$set: { confirmationToken: confirmationToken },
50+
});
51+
}
52+
53+
export async function isUserActive(data) {
54+
return client.db("blog").collection("users").findOne(data);
55+
}

0 commit comments

Comments
 (0)
0