Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
425c710
Merge pull request #6 from BEKIRKSU/creating-end-points
H-BAHDON Sep 14, 2023
c84f182
Updated
H-BAHDON Sep 15, 2023
c3f7630
Updated scores
H-BAHDON Sep 15, 2023
7e32071
Updated score
H-BAHDON Sep 15, 2023
da03625
Updated authController.js
H-BAHDON Sep 15, 2023
4dffa11
Updated authController.js
H-BAHDON Sep 15, 2023
19165e3
Updated authController.js
H-BAHDON Sep 15, 2023
12a4074
Updated authController.js
H-BAHDON Sep 15, 2023
4ba5d70
Updated authController.js
H-BAHDON Sep 15, 2023
3e656e7
Updated authController.js
H-BAHDON Sep 15, 2023
fbe9b51
Updated authController.js
H-BAHDON Sep 15, 2023
c9416ab
Updated authController.js
H-BAHDON Sep 15, 2023
d709b31
Updated authController.js
H-BAHDON Sep 15, 2023
90b4679
Updated authController.js
H-BAHDON Sep 15, 2023
2e56e69
Updated authController.js
H-BAHDON Sep 15, 2023
4af7760
Updated authController.js
H-BAHDON Sep 15, 2023
653bf38
Updated Back-end to Localhost
H-BAHDON Sep 19, 2023
15761e4
Updated githubController.js
H-BAHDON Sep 19, 2023
bf4377e
Updated authController.js
H-BAHDON Sep 19, 2023
b993e77
.
H-BAHDON Sep 19, 2023
5d7a3fa
.
H-BAHDON Sep 19, 2023
7a585c4
.
H-BAHDON Sep 19, 2023
bc7ed94
authController.js
H-BAHDON Sep 19, 2023
870d4b2
Updated
H-BAHDON Oct 19, 2023
88b8319
Updated
H-BAHDON Oct 26, 2023
6070be5
Updated auth
H-BAHDON Oct 30, 2023
8092a30
Updated
H-BAHDON Oct 30, 2023
6618c0b
Updated the token
H-BAHDON Nov 1, 2023
700ec5b
Updated authController.js
H-BAHDON Nov 2, 2023
95956fb
Updated secret
H-BAHDON Nov 2, 2023
ba1a1eb
Updated
H-BAHDON Nov 2, 2023
0e150ab
Updated login flow
H-BAHDON Nov 4, 2023
4f51907
Updated app.js
H-BAHDON Nov 4, 2023
95e4704
"Updated env files"
H-BAHDON Jan 10, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,19 @@ NODE_ENV=production
PORT=3001


# REACT_APP_API_URL=http://localhost:3001
REACT_APP_API_URL='https://mm-code-api-b4f2aff44087.herokuapp.com'
REACT_APP_API_URL=http://localhost:3001
# REACT_APP_API_URL='https://mm-code-api-b4f2aff44087.herokuapp.com'

REACT_APP_SECRET_KEY=abcdef123456


# Client_SIDE_BASE_URL=http://localhost:3000
Client_SIDE_BASE_URL=https://www.mmcode.io
Client_SIDE_BASE_URL="http://localhost:3000"
# Client_SIDE_BASE_URL=https://www.mmcode.io

GOOGLE_CLIENT_SECRET="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"
GOOGLE_CLIENT_ID="617409105699-u5senri6ujm3b655n5gkb0g6f7r8r5j1.apps.googleusercontent.com"

GITHUB_CLIENT_ID="613427a2df3476638f43"
GITHUB_CLIENT_SECRET="417c54c316a47b3ead02087f71bce99b75c856bf"

SECRET_KEY=melly
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules/
node_modules/
.env
6 changes: 2 additions & 4 deletions Auth/auth.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const passport = require('passport');
const GoogleStrategy = require('./googleStrategy'); // Import the exported Google strategy
const githubStrategy = require('./githubStrategy'); // Import the exported GitHub strategy
const GoogleStrategy = require('./googleStrategy');
const githubStrategy = require('./githubStrategy');

// Use the Google and GitHub strategies with their respective names
passport.use('google', GoogleStrategy);
passport.use('github', githubStrategy);

Expand All @@ -15,5 +14,4 @@ passport.serializeUser(function(user, done) {
passport.deserializeUser(function(user, done) {
done(null, user);
});
// Export the configured passport
module.exports = passport;
2 changes: 1 addition & 1 deletion Auth/githubStrategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const db = require('../config/db/db'); // Import your database configuration
const githubStrategy = new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: `https://mm-code-api-b4f2aff44087.herokuapp.com/auth/github/callback`,
callbackURL: `${process.env.REACT_APP_API_URL}/auth/github/callback`,
scope: ['user:email'],
},
async function (accessToken, refreshToken, profile, done) {
Expand Down
8 changes: 6 additions & 2 deletions Auth/googleStrategy.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const db = require('../config/db/db'); // Import your database configuration
const passport = require('passport');




const googleStrategy = new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: `https://mm-code-api-b4f2aff44087.herokuapp.com/auth/google/callback`,
callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`,
passReqToCallback: true,
}, function (request, accessToken, refreshToken, profile, done) {

Expand All @@ -18,7 +22,7 @@ const googleStrategy = new GoogleStrategy({

if (result.rows.length === 0) {
const insertUserQuery = 'INSERT INTO users (full_name, email, accounts) VALUES ($1, $2, $3)';
const insertUserValues = [profile.displayName, profile.emails[0].value, 'Google']; // Set the account provider to 'Google'
const insertUserValues = [profile.displayName, profile.emails[0].value, 'Google'];

db.query(insertUserQuery, insertUserValues, (err) => {
if (err) {
Expand Down
27 changes: 17 additions & 10 deletions app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,22 @@ const passport = require('passport');
const morgan = require('morgan');
const bodyParser = require('body-parser');
require('dotenv').config();
const session = require('express-session');

const authRoutes = require('../app/routes/authRoutes');
const githubRoutes = require('../app/routes/githubRoutes');
const googleRoutes = require('../app/routes/googleRoute'); // Replace with the correct path to your Google OAuth route file

const googleRoutes = require('../app/routes/googleRoute');

const GoogleStrategy = require('../Auth/googleStrategy');
const GithubStrategy = require('../Auth/githubStrategy');
passport.use(GoogleStrategy);

passport.use(GithubStrategy);

app.set('view engine', 'ejs');
app.use(cookieParser());
app.use(
cors({
origin: 'https://www.mmcode.io',
origin: ["https://www.mmcode.io"],
methods: ['GET', 'POST'],
credentials: true,
})
Expand All @@ -42,22 +41,30 @@ app.use(
secure: true,
})
);

app.set('trust proxy', 1);


app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user, done) => {
// Serialize the user to the session
passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser((user, done) => {
// Deserialize the user from the session
done(null, user);
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});


app.use('/', authRoutes);
app.use('/', githubRoutes);
app.use('/', googleRoutes);

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

module.exports = app;
49 changes: 4 additions & 45 deletions app/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const db = require('../../config/db/db');

function platform(req, res) {
req.session.randomValue = Math.random();
const storedRandomValue = req.session.randomValue;
Expand All @@ -9,63 +9,22 @@ function platform(req, res) {

function homePage(req, res) {
res.send("Home page running well.")
}

function getUser(req, res) {
if (req.isAuthenticated()) {
const userId = req.user.id; // Assuming you have a unique identifier for users
db.query('SELECT full_name, email FROM users WHERE id = $1', [userId])
.then(result => {
if (result.rows.length === 0) {
// User not found in the database, use backup method
const userData = {
displayName: req.user.displayName || req.user.username, // Use username if displayName is not available
email: req.user.email,
};
req.session.userData = userData;
res.json(userData);
} else {
// User found in the database
const userData = {
displayName: result.rows[0].full_name,
email: result.rows[0].email,
};
req.session.userData = userData;
res.json(userData);
}
})
.catch(error => {
console.error('Error fetching user data from the database:', error);
res.status(500).json({ error: 'Internal server error' });
});
} else {
res.status(401).json({ error: 'Not authenticated' });
}
}



function checkSession(req, res) {
try {
if (req.isAuthenticated()) {
res.sendStatus(200);
} else {
res.sendStatus(401);
}
} catch (e) {
return res.status(500).json({ msg: "Error found" });
}
}



function logout(req, res) {
res.clearCookie('token');
req.logout();
res.status(200).json({ success : true });
}

module.exports = {
homePage,
platform,
getUser,
checkSession,
logout,
};
24 changes: 20 additions & 4 deletions app/controllers/googleController.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
const passport = require("passport");
const jwt = require('jsonwebtoken');
const secretKey = process.env.SECRET_KEY;

// Google OAuth authentication
function googleAuth(req, res) {
passport.authenticate('google', { scope: ['email', 'profile'] })(req, res);
}

// Callback after Google OAuth authentication
function googleCallback(req, res, next) {
passport.authenticate('google', {
successRedirect: `${process.env.Client_SIDE_BASE_URL}/platform`,
failureRedirect: '/auth/google/failure'
}, (err, user) => {
if (err) {
return next(err);
}
if (!user) {
return res.redirect(`${process.env.Client_SIDE_BASE_URL}/login`);
}

const token = jwt.sign(user, secretKey, { expiresIn: '24h' });

res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 24 * 60 * 60 * 1000,
sameSite: 'none',
});

return res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`);
})(req, res, next);
}

// Failure route
function googleFailure(req, res) {
res.redirect(`${process.env.Client_SIDE_BASE_URL}/login`);
// Note: You should not use `res.send` after `res.redirect` as it will not be executed.
}

module.exports = {
Expand Down
29 changes: 29 additions & 0 deletions app/controllers/tokens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const jwt = require('jsonwebtoken');

const secretKey = process.env.SECRET_KEY;

function generateToken(user) {
const token = jwt.sign({ user }, secretKey, { expiresIn: '24h' });
return token;
}

function verifyToken(req, res, next) {
const token = req.header('Authorization');

if (!token) {
return res.status(401).json({ error: 'Access denied. No token provided.' });
}

try {
const decoded = jwt.verify(token, secretKey);
req.user = decoded;
next();
} catch (error) {
return res.status(403).json({ error: 'Invalid token.' });
}
}

module.exports = {
generateToken,
verifyToken,
};
49 changes: 44 additions & 5 deletions app/routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,52 @@
const express = require('express');
const router = express.Router();
const authController = require('../controllers/authController');
// const { isLoggedIn } = require('../middleware/authenticationMiddleware');
const jwt = require('jsonwebtoken');
const secretKey = process.env.SECRET_KEY;

router.get('/', authController.homePage);

router.get('/', authController.homePage)
router.get('/platform', authController.platform);
router.get('/user', authController.getUser);
// router.get('/protected', isLoggedIn, authController.protected);
router.get('/check-session', authController.checkSession)

router.get('/user', (req, res) => {
const token = req.cookies.token;

if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}

try {
const decoded = jwt.verify(token, secretKey );
const userData = {
displayName: decoded.displayName || decoded.username || decoded.fullName,
email: decoded.email,
};

res.json({ message: 'User authenticated', userData });
} catch (error) {
console.error('Authentication Error:', error);
res.status(401).json({ error: 'Unauthorized' });
}
});

router.get('/checkSession', (req, res) => {
const token = req.cookies.token;

if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}

const decodedToken = jwt.verify(token, secretKey );

if (!decodedToken) {
return res.status(401).json({ error: 'Unauthorized' });
}

return res.status(200).json({ message: 'User is authenticated' });
})

router.get('/logout', authController.logout);

module.exports = router;


4 changes: 3 additions & 1 deletion app/routes/googleRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ const express = require('express');
const router = express.Router();
const googleController = require('../controllers/googleController');
const authenticationMiddleware = require('../middleware/authenticationMiddleware');
const passport = require('passport');

router.get('/auth/google', googleController.googleAuth);
router.get('/auth/google/callback', googleController.googleCallback);
router.get('/auth/google/failure', authenticationMiddleware.isLoggedIn, googleController.googleFailure);
router.get('/auth/google/failure', googleController.googleFailure);

module.exports = router;

5 changes: 1 addition & 4 deletions config/db/db.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
const { Pool } = require('pg');

// Create a new instance of the Pool class
const pool = new Pool({
connectionString: 'postgres://hzxxyodc:lx9EgngCHzM-uAX0GnOpdwrZXX4vsSe5@surus.db.elephantsql.com/hzxxyodc',
ssl: {
rejectUnauthorized: false
}
});

// Test the connection to the database
pool.query('SELECT NOW()')
.then(res => console.log('Database for users connected! Current time: ', res.rows[0].now))
.catch(err => console.error('Database connection error: ', err.stack));

// Export the pool object for use in other modules

module.exports = pool;
Empty file removed config/passport.js
Empty file.
Loading