Skip to content

Commit

Permalink
Added Auto Validate for Login and Register GitHub OAuth
Browse files Browse the repository at this point in the history
  • Loading branch information
stanleyowen committed Mar 13, 2021
1 parent 71f2290 commit 1486be3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 15 deletions.
4 changes: 2 additions & 2 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const express = require('express');
const passport = require('passport');
const mongoose = require('mongoose');
const helmet = require('helmet');

const app = express();
const PORT = process.env.PORT || 5000;
Expand Down
42 changes: 29 additions & 13 deletions server/routes/oauth.route.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const router = require('express').Router();
const axios = require('axios');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const router = require('express').Router();
const jwtSecret = require('../config/jwtConfig');
let User = require('../models/users.model');

const CLIENT_ID = process.env.GITHUB_ID;
const CLIENT_URL = process.env.CLIENT_URL;
const CLIENT_SECRET = process.env.GITHUB_SECRET;

const ERR_MSG = [
Expand Down Expand Up @@ -42,18 +43,33 @@ router.get('/github', async (req, res) => {
})
.then(user => {
const email = user.data.email;
const dataModel = new User ({
email,
password: null,
thirdParty: {
isThirdParty: true,
provider: 'github',
status: 'Pending'
User.findOne({ email }, (err, user) => {
if(err) return res.status(500).json({statusCode: 500, message: ERR_MSG[0]});
else if(!user){
const dataModel = new User ({
email,
password: null,
thirdParty: {
isThirdParty: true,
provider: 'github',
status: 'Pending'
}
});
dataModel.save()
res.redirect(`${CLIENT_URL}/oauth/github/${encodeURIComponent(email)}`);
}else if(user){
if (user.thirdParty.status === "Pending") res.redirect(`${CLIENT_URL}/oauth/github/${encodeURIComponent(email)}`);
else {
const token = jwt.sign({ id: user.id }, jwtSecret.secret, { expiresIn: '1d' });
res.json({
statusCode: 200,
status: ERR_MSG[11],
id: user.id,
token: token
});
}
}
});
dataModel.save()
.then(() => res.redirect(`http://localhost:3000/oauth/github/${encodeURIComponent(email)}`))
.catch(() => res.json('Error in Registering Due to Duplicate Email Address'))
})
})
.catch(err => console.log(err))
}else res.json(result.data);
Expand Down

0 comments on commit 1486be3

Please sign in to comment.