Commit d8f96f23 authored by janithGamage's avatar janithGamage

feature: update

desc : node server implemented
* User REST API implemented
parent c8b2dcd2
{
"cSpell.words": [
"Janith",
"SLIIT"
]
}
\ No newline at end of file
DB_PASSWORD = JppbU6MZeHfOj7sp
DB_USERNAME = admin
\ No newline at end of file
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import mongoose from 'mongoose';
import nodemailer from "nodemailer";
import { v4 as uuidv4 } from 'uuid';
import User from '../models/user.model.js';
export const signIn = async (req, res) => {
const { email, password } = req.body;
try {
if (email === null || typeof email == "undefined") return res.status(400).json({ code: "02", message: "Email Field Required" })
if (password === null || typeof password == "undefined") return res.status(400).json({ code: "02", message: "Password Field Required" })
const existingUser = await User.findOne({ email: email });
if (!existingUser) return res.status(404).json({ code: "02", message: "User doesn't exist" })
const isPasswordCorrect = await bcrypt.compare(password, existingUser.password)
if (!isPasswordCorrect) return res.status(400).json({ code: "02", message: "Invalid Credentials" })
const token = jwt.sign({ email: existingUser.email, id: existingUser._id }, 'test', { expiresIn: "1h" })
res.status(200).json({ code: "01", result: existingUser, token })
} catch (error) {
res.status(500).json({ code: "00", message: "Something went wrong" })
}
}
export const signUp = async (req, res) => {
const {
email,
password,
confirmPassword,
type,
userFirstName,
userLastName,
userContactNumber,
userAddressLine1,
userAddressLine2,
userAddressLine3,
} = req.body;
try {
if (!type) return res.status(400).json({ code: "02", message: "Type Field Required" })
if (!email) return res.status(400).json({ code: "02", message: "Email Field Required" })
if (!userFirstName) return res.status(400).json({ code: "02", message: "User First Name Field Required" })
if (!userLastName) return res.status(400).json({ code: "02", message: "User Last Name Field Required" })
if (!userContactNumber) return res.status(400).json({ code: "02", message: "User Contact Number Field Required" })
const existingUser = await User.findOne({ email })
if (existingUser) return res.status(400).json({ code: "02", message: "User already exists" })
if (type === "buyer") {
if (!password) return res.status(400).json({ code: "02", message: "Password Field Required" })
if (password !== confirmPassword) return res.status(400).json({ code: "02", message: "Passwords do not match" })
const hashedPassword = await bcrypt.hash(password, 12)
const userDetails = new User({
email,
password: hashedPassword,
type,
userDetails: {
userQNumber: uuidv4(),
userEmail: email,
userName: `${userFirstName} ${userLastName}`,
userContactNumber,
userAddress: `${userAddressLine1}, ${userAddressLine2}, ${userAddressLine3}`,
userType: type,
}
})
const userResult = await userDetails.save()
const token = jwt.sign({ email: userResult.email, id: userResult._id }, 'test', { expiresIn: "1h" })
res.status(200).json({ code: "01", result: userResult, token })
} else if (type === "trader") {
const userDetails = new User({
email,
type,
userDetails: {
userQNumber: uuidv4(),
userEmail: email,
userName: `${userFirstName} ${userLastName}`,
userContactNumber,
userAddress: `${userAddressLine1}, ${userAddressLine2}, ${userAddressLine3}`,
userType: type,
},
states: 2
})
const userResult = await userDetails.save()
const token = jwt.sign({ email: userResult.email, id: userResult._id }, 'test', { expiresIn: "1h" })
res.status(200).json({ code: "01", result: userResult, token })
}
} catch (error) {
res.status(500).json({ code: "00", message: "Something went wrong" })
}
}
export const getUsers = async (req, res) => {
try {
const users = await User.find();
res.status(200);
res.json(users);
} catch (error) {
console.log(error)
res.status(404);
res.json({ message: error.message })
}
}
export const getUser = async (req, res) => {
const { id } = req.params;
try {
const user = await User.findById(id);
res.status(200);
res.json({
code: "01",
result: user
});
} catch (error) {
res.status(404);
res.json({ "message": error.message });
}
}
export const getUserAccordingToType = async (req, res) => {
const { userType } = req.params;
try {
const users = await User.find({ type: userType });
res.status(200);
res.json(users);
} catch (error) {
res.status(404);
res.json({ "message": error.message });
}
}
export const updateUser = async (req, res) => {
const { id } = req.params;
const data = req.body;
try {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({ code: "02", message: `No User for this id: ${id}` });
}
if (data.type == "buyer" || data.type == "admin") {
const updateUser = { ...data, _id: id }
await User.findByIdAndUpdate(id, updateUser, { new: true })
res.status(200);
res.json({ code: "01", result: updateUser })
} else if (data.type == "trader") {
var password = Math.random().toString(36).slice(-8);
const hashPassword = await bcrypt.hash(password, 12)
const updateUser = { ...data, password: hashPassword, _id: id }
await User.findByIdAndUpdate(id, updateUser, { new: true })
//call email service
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD,
clientId: process.env.OAUTH_CLIENTID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
refreshToken: process.env.OAUTH_REFRESH_TOKEN
}
});
let mailOptions = {
from: "janithgamage1.ed@gmail.com",
to: updateUser.email,
subject: 'Shop House Project',
text: `You are Successfully Approved, you're username: ${updateUser.email} , you're password : ${password}`
};
transporter.sendMail(mailOptions, function (err, data) {
if (err) {
console.log("Error " + err);
} else {
console.log("Email sent successfully");
}
});
res.status(200);
res.json({ code: "01", result: updateUser })
}
} catch (error) {
res.status(404);
res.json({ code: "00", "message": error.message });
}
}
export const deleteUser = async (req, res) => {
const { id } = req.params;
try {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({ code: "02", message: `No User for this id: ${id}` });
}
await User.findByIdAndDelete(id);
res.status(200);
res.json({ code: "01", "message": "User Deleted Successfully" });
} catch (error) {
res.status(404);
res.json({ code: "00", "message": error.message });
}
}
import jwt from 'jsonwebtoken';
const auth = async (req, res, next) => {
try {
if (req.headers.authorization != null) {
const token = req.headers.authorization.split(" ")[1];
const isCustomAuth = token.length < 500;
let decoderData;
if (token && isCustomAuth) {
decoderData = jwt.verify(token, 'test');
req.userId = decoderData?.id;
} else {
decoderData = jwt.decode(token)
req.userId = decoderData?.sub;
}
next();
}
else {
res.status(500).json({ message: 'user not authorized' })
}
} catch (error) {
console.log(error)
}
}
export default auth;
\ No newline at end of file
import mongoose from "mongoose";
const userSchema = mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String
},
type: {
type: String,
required: true
},
userDetails: {
userQNumber: {
type: String,
required: true,
unique: true
},
userEmail: {
type: String,
required: true,
},
userName: {
type: String,
required: true
},
userContactNumber: {
type: String,
required: true
},
userAddress: {
type: String
},
userType: {
type: String,
required: true
},
},
states: {
type: String,
default: "1"
},
createdAt: {
type: Date
},
updatedAt: {
type: Date
}
});
const User = mongoose.model("Users", userSchema);
export default User;
This diff is collapsed.
{
"name": "server_node",
"version": "1.0.0",
"description": "SLIIT Final Year Research Project Server (NodeJS)",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"author": "devJanith",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"mongoose": "^7.1.1",
"nodemailer": "^6.9.1",
"nodemon": "^2.0.22",
"uuid": "^9.0.0"
}
}
import express from "express";
import { deleteUser, getUser, getUserAccordingToType, getUsers, signIn, signUp, updateUser } from "../controllers/user.controller.js";
const router = express.Router();
router.post('/sign-in', signIn)
router.post('/sign-up', signUp)
router.get('/all', getUsers);
router.get('/:id', getUser);
router.get('/test/:userType', getUserAccordingToType);
router.put('/:id', updateUser);
router.delete('/:id', deleteUser);
export default router;
\ No newline at end of file
import bodyParser from "body-parser";
import cors from "cors";
import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
//import routes
import userRoutes from "./routes/user.routes.js";
dotenv.config();
const app = express();
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
//end
app.get("/", (req, res) => {
res.json({ message: "Welcome to Server Node" });
});
//implement routes
app.use("/rest_node/user", userRoutes);
const CONNECTION_URL = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@cluster0.dmza8yi.mongodb.net/?retryWrites=true&w=majority`;
const PORT = process.env.PORT || 5000;
mongoose
.connect(CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
app.listen(PORT, () =>
console.log(`Server Running on port :http://localhost:${PORT}`)
);
})
.catch((error) => {
console.error(error);
process.exit(1);
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment