Skip to content

Commit

Permalink
created middlewere for authantications
Browse files Browse the repository at this point in the history
  • Loading branch information
moovendhan-v committed Apr 21, 2024
1 parent 1c7d190 commit 3c17791
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 18 deletions.
1 change: 0 additions & 1 deletion backend/controller/components.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,6 @@ const getCategoriesList = async (req, res) => {
module.exports = { getCategoriesList };



module.exports = {
getLatestFiles,
readFilesInformations,
Expand Down
31 changes: 16 additions & 15 deletions backend/controller/github-oauth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ const {getUserInformationsByName} = require('../controller/userProfile.controlle
const { response } = require('express');

const JWT_SECRET = process.env.JWT_ACCESS_TOKEN;
const TOKEN_EXPIRE_TIMEOUT = process.env.TOKEN_EXPIRE_TIMEOUT;

async function exchangeGitHubCodeForToken(code) {
const client_id = process.env.GITHUB_CLIENT_ID;
const client_secret = process.env.GITHUB_CLIENT_SECRET;
console.log(client_secret);
const params = `?client_id=${client_id}&client_secret=${client_secret}&code=${code}`;
try {
const response = await axios.post(
Expand All @@ -27,11 +27,10 @@ async function exchangeGitHubCodeForToken(code) {
const { access_token } = response.data;
if (!access_token) {
console.error('GitHub OAuth code exchange failed. Response:', response.data);
throw new Error('Access token not received from GitHub.');
throw new Error('Bad Verifications Code Exchange');
}
return access_token;
} catch (error) {
console.error('GitHub OAuth code exchange error:', error);
throw error;
}
}
Expand Down Expand Up @@ -81,6 +80,7 @@ const signup_or_login_with_git = async (req,res)=>{
// it will create a new account if account not already existis or creates a new account

const { code } = req.body;

try {
// #TODO Upadate a auth token where authanticated by user
const githubAccessToken = await exchangeGitHubCodeForToken(code);
Expand All @@ -96,37 +96,36 @@ const signup_or_login_with_git = async (req,res)=>{
const githubUser = new GitHubUser(userInformations);
await githubUser.save();
const response ={
"token": createTokens({userId: githubUser.id, userName: githubUser.name}),
"token": createTokens({user_id: githubUser._id, name: githubUser.name}),
"user": githubUser,
"components": []
}
return res.json(jsonStatusSuccess({ message: `New Account created ${githubUser.name}`, response: response }));
}


getUserInformationsByName(existingUser.name, async (error, userProfileWithComponents) => {
if (error) {
return res.status(500).send(`Internal Server Error ${error}`);
} else {
userProfileWithComponents['token'] = createTokens({userId: existingUser.id, userName: existingUser.name});
userProfileWithComponents['token'] = createTokens({user_id: existingUser._id, name: existingUser.name});
return res.json(jsonStatusSuccess({ message: `Welcome Back ${existingUser.name}`, response: await userProfileWithComponents }));

// res.json({ success: true, githubAccessToken: await req.session.githubAccessToken, token: githubAccessToken, response: await userProfileWithComponents});
}
});
// req.session.githubAccessToken = await githubAccessToken;

} catch (error) {
console.error('Error during GitHub OAuth:', error);
res.status(500).json({ success: false, error: error });
return res.json(jsonStatusError({message: error.message}))
}
}

const createTokens = (tokenProperties)=>{
const createTokens = (user)=>{
// Assume user is authenticated via GitHub and obtain user info
// const { userId, username } = req.body;

// Create JWT token
const token = jwt.sign({ tokenProperties }, JWT_SECRET, { expiresIn: '1h' });
const token = jwt.sign({ user }, JWT_SECRET, { expiresIn: TOKEN_EXPIRE_TIMEOUT });

// Set HTTPOnly cookie with JWT token
// res.cookie('jwt', token, { httpOnly: true, secure: true });
Expand All @@ -135,14 +134,16 @@ const createTokens = (tokenProperties)=>{
}

const validateToken = (req,res)=>{
// Retrieve JWT token from cookie
// const token = req.cookies.jwt;
const { token } = req.body;

if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
const authHeader = req.headers['authorization'];
console.log(req.headers);

if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Unauthorized' });
}

const token = authHeader.split(' ')[1];

try {
// Verify JWT token
const decoded = jwt.verify(token, JWT_SECRET);
Expand Down
56 changes: 55 additions & 1 deletion backend/controller/userProfile.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,60 @@ const getUserInformationsByName = async (userName, callback) => {
}
};

const getprofileinfoprotect = async (req, res) => {
try {
const user_id = req.user.user.user_id;
console.log(req.user);
// Find user information using user_id
const existingUser = await GitHubUser.findOne({ _id: user_id });
if (!existingUser) {
return res.status(404).send('User not found');
}
// Get userComponents details using user_id
const userComponents = await UserComponents.find({ user_id: existingUser._id });

// Map user components and append file information
const updatedComponentsPromises = userComponents.map(async component => {
const folderNames = component.folder_name;
const categories = component.categories;
const data = component;
const user = existingUser;
console.log(`Component ${component}`);

return new Promise((resolve, reject) => {
readFilesInformations(categories, folderNames,{data, user}, (err, fileInfo) => {
if (err) {
reject(err);
} else {
resolve({
...component.toObject(), // Convert Mongoose document to object
component_details: fileInfo
});
}
});
});
});

// Wait for all promises to resolve
const updatedComponents = await Promise.all(updatedComponentsPromises);

// Construct the response object
const userProfileWithComponents = {
user: existingUser,
components: updatedComponents
};

// Send the success response
res.send(jsonStatusSuccess({ errorStatus: false, message: 'User data received successfully', response: userProfileWithComponents, count: userComponents.length }));

} catch (error) {
// Handle errors
console.error('Error in getUserProfileInformations:', error);
res.status(500).send(`Internal Server Error ${error}`);
}
}


const getUserInformationsByNameFromDb = async (req, res) => {
const userName = req.body.user_name;
try {
Expand All @@ -123,4 +177,4 @@ const getUserInformationsByNameFromDb = async (req, res) => {



module.exports = { getUserProfileInformations, getUserInformationsByName, getUserInformationsByNameFromDb };
module.exports = { getUserProfileInformations, getUserInformationsByName, getUserInformationsByNameFromDb, getprofileinfoprotect };
1 change: 1 addition & 0 deletions backend/copy.env
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ GITHUB_CLIENT_SECRET=
#jtw secrets
JWT_ACCESS_TOKEN =
REFRESH_TOKEN =
TOKEN_EXPIRE_TIMEOUT =

#Mongodb
MONGODB_CONNECTION_STRING=mongodb://172.28.0.2:27017/github_user
Expand Down
29 changes: 29 additions & 0 deletions backend/middleware/Auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const jwt = require('jsonwebtoken');
const {jsonStatus, jsonStatusError, jsonStatusSuccess} = require('../operations/errorhandlingOperations');
require('dotenv').config();

const JWT_SECRET = process.env.JWT_ACCESS_TOKEN;

const authanticateJwtToken = (req,res,next)=>{

const authHeader = req.headers['authorization'];
console.log(req.headers);

if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.send(jsonStatusError({message: "Unauthorised", statusCode: 401}))
}

const token = authHeader.split(' ')[1];

try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
// Token verification failed
return res.send(jsonStatusError({message: err, statusCode: 401}))
}
}


module.exports = {authanticateJwtToken}
4 changes: 3 additions & 1 deletion backend/routes/userProfile.router.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
const { Router } = require('express')
const userProfileRouter = Router()
const {getUserProfileInformations, getUserInformationsByName, getUserInformationsByNameFromDb} = require('../controller/userProfile.controller');
const {getUserProfileInformations, getUserInformationsByName, getUserInformationsByNameFromDb, getprofileinfoprotect} = require('../controller/userProfile.controller');
const {authanticateJwtToken} = require('../middleware/Auth')

userProfileRouter.post('/getuserprofileinfo', getUserProfileInformations);
userProfileRouter.get('/getprofileinfoprotect', authanticateJwtToken, getprofileinfoprotect );
userProfileRouter.post('/getprofileinfo', getUserInformationsByNameFromDb);

module.exports = {userProfileRouter};

0 comments on commit 3c17791

Please sign in to comment.