Initialized Project with default middlewares and helpers, connected to Atlas Instance and created Swagger Setup. Created necessary DB models and authentication-authorization logic
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { createUser, getUserByQuery } from "../models/User/operations.js";
|
||||
import bcrypt from "bcrypt";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
getAccessToken,
|
||||
getRefreshToken,
|
||||
} from "../middlewares/jwt.middleware.js";
|
||||
|
||||
export const createUserController = async (req, res, next) => {
|
||||
try {
|
||||
const { id, name, password } = req.body;
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
|
||||
const userExists = await getUserByQuery({ id });
|
||||
if (userExists) {
|
||||
throw { code: 400, message: "User already exists for this id" };
|
||||
}
|
||||
|
||||
const refreshToken = getRefreshToken();
|
||||
|
||||
const user = await createUser({
|
||||
id,
|
||||
name,
|
||||
hash: hash,
|
||||
refreshToken,
|
||||
createdOn: dayjs().toISOString(),
|
||||
});
|
||||
res.status(200).json({ result: user });
|
||||
} catch (error) {
|
||||
console.log("createUserController Error", error);
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const loginController = async (req, res, next) => {
|
||||
try {
|
||||
const { id, password } = req.body;
|
||||
const userExists = await getUserByQuery({ id });
|
||||
if (!userExists) {
|
||||
throw { code: 404, message: "User not found" };
|
||||
}
|
||||
const isPasswordValid = await bcrypt.compare(password, userExists.hash);
|
||||
if (!isPasswordValid) {
|
||||
throw { code: 400, message: "Invalid Password" };
|
||||
}
|
||||
|
||||
const accessToken = getAccessToken({ id: userExists._id });
|
||||
const refreshToken = getRefreshToken();
|
||||
|
||||
userExists.refreshToken = refreshToken;
|
||||
await userExists.save();
|
||||
|
||||
res
|
||||
.status(200)
|
||||
.json({ result: { accessToken, refreshToken, name: userExists?.name } });
|
||||
} catch (error) {
|
||||
console.log("loginController Error", error);
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const renewAccessTokenController = async (req, res, next) => {
|
||||
try {
|
||||
const { refreshToken } = req.body;
|
||||
const userExists = await getUserByQuery({ refreshToken });
|
||||
if (!userExists) {
|
||||
throw { code: 404, message: "User not found" };
|
||||
}
|
||||
const accessToken = getAccessToken({ id: userExists._id });
|
||||
res.status(200).json({ result: accessToken });
|
||||
} catch (error) {
|
||||
console.log("renewAccessTokenController Error", error);
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user