Skip to content

Commit

Permalink
feature(social auth): add social authentication functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
Anguandia committed Aug 14, 2019
1 parent a9c7c9f commit 240180b
Show file tree
Hide file tree
Showing 11 changed files with 269 additions and 66 deletions.
95 changes: 47 additions & 48 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@
"runmigrations": "npm run undoseeds && npm run migration && npm run seeds",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"test": "export NODE_ENV=test && npm run undomigration && npm run migration && npm run seeds && nyc --reporter=html --reporter=text mocha ./test --no-timeout --exit --require @babel/register",
<<<<<<< HEAD
"dev": "nodemon --exec babel-node ./src/app.js"
=======
"dev": "npm run undoseeds && nodemon --exec babel-node ./src/app.js"
>>>>>>> twitter security
},
"author": "Andela Simulations Programme",
"license": "MIT",
Expand Down
14 changes: 8 additions & 6 deletions src/controllers/social.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ class Social {
static async login(req, res) {
data = req.user;
const firstname = data.name ? data.name.givenName : data.displayName.split(' ')[0];
const lastname = data.name ? data.name.middleName || data.name.familyName : data.displayName.split(' ')[1];
const lastname = data.name ? data.name.middleName : data.displayName.split(' ')[1];
const email = data.emails ? data.emails[0].value : '';
const username = `${firstname}.${lastname}`;
// check if user is in db
const registeredUser = await User.findOne(email, username);

// if yes generate token
// format response message for case of twitter user without email add and others with
const message = data.emails ? `account with name ${firstname} ${lastname} does not exist, create?`
: `account with name ${firstname} ${lastname} does not exist, to register send email in response`;
// if yes user exists, generate token
if (registeredUser) {
const payload = {
email,
Expand All @@ -46,7 +48,7 @@ class Social {
token
});
}
res.status(200).json({ message: `account with name ${firstname} ${lastname} does not exist, create?` });
res.status(200).json({ message });
}

/**
Expand All @@ -61,7 +63,7 @@ class Social {
static async signup(req, res) {
const firstname = data.name ? data.name.givenName : data.displayName.split(' ')[0];
const lastname = data.name ? data.name.middleName || data.name.familyName : data.displayName.split(' ')[1];
const email = data.emails ? data.emails[0].value : '';
const email = data.emails ? data.emails[0].value : req.body.email || req.query.email;
const username = `${firstname}.${lastname}`;
const hasspassword = Helper.hashPassword('password');
const dbSchema = {
Expand All @@ -80,7 +82,7 @@ class Social {
verifyUser(payload.email, createdUser.username, verifyUrl);
return res.status(201).json({
status: 201,
message: 'Your account has been successfully created. An email has been sent to you with detailed instructions on how to activate it.',
message: 'Your account has been successfully created. An email has been sent to you with detailed instructions on how to activate it. Your default password is password, Please change on activatio',
data: {
firstname: createdUser.firstname,
lastname: createdUser.lastname,
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class UserController {
const token = await Helper.generateToken(payload);
return res.status(200).send({
status: 200,
message: `welcome back ${theUser.firstname}`,
message: `welcome back ${theUser.firstname}`,
token
});
} catch (error) {
Expand Down
18 changes: 18 additions & 0 deletions src/middlewares/validators/socialLogin-mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import dotenv from 'dotenv';
import fakeUsers from '../../mock-data';

dotenv.config();

export const mock = (req, res, next) => {
if (req.url.includes('login/')) {
res.redirect(`/auth/fake?provider=${req.url.split('/')[2]}`);
} else {
next();
}
};

export const fakeAuth = (req, res, next) => {
req.user = fakeUsers[process.env[req.query.provider]] || fakeUsers.google_new;
// console.log(req.user);
next();
};
92 changes: 92 additions & 0 deletions src/mock-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const fakeUsers = {
facebook_existing: {
id: '2467093749978894',
username: undefined,
displayName: undefined,
name:
{
familyName: 'Kuku',
givenName: 'Anguandia',
middleName: 'Mike'
},
gender: undefined,
profileUrl: undefined,
emails: [{ value: 'anguamike@yahoo.com' }],
photos:
[{
value:
'https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=2467093749978894&height=50&width=50&ext=1568336277&hash=AeQTmX6T-4sjcO2y'
}],
provider: 'facebook'
},
google_existing: {
id: '100027718370607337396',
displayName: 'Admin Admin',
name: { familyName: 'Admin', givenName: 'Admin' },
emails: [{ value: 'admin@gmail.com', verified: true }],
photos:
[{
value:
'https://lh4.googleusercontent.com/-hwkYMcorxvo/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rec-AyRoK1mZklL6nXZuisrmnBpxw/photo.jpg'
}],
provider: 'google',
},

twitter_existing: {
id: '1159372707424854016',
username: 'MAnguandia',
displayName: 'mike anguandia',
photos:
[{
value:
'https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png'
}],
provider: 'twitter'
},
facebook_new: {
id: '2467093749978894',
username: undefined,
displayName: undefined,
name:
{
familyName: 'Kuku',
givenName: 'Anguandia',
middleName: 'Mike'
},
gender: undefined,
profileUrl: undefined,
emails: [{ value: 'user2@yahoo.com' }],
photos:
[{
value:
'https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=2467093749978894&height=50&width=50&ext=1568336277&hash=AeQTmX6T-4sjcO2y'
}],
provider: 'facebook'
},
google_new: {
id: '100027718370607337396',
displayName: 'Three Four',
name: { familyName: 'Three', givenName: 'Four' },
emails: [{ value: 'thirtyfour@gmail.com', verified: true }],
photos:
[{
value:
'https://lh4.googleusercontent.com/-hwkYMcorxvo/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rec-AyRoK1mZklL6nXZuisrmnBpxw/photo.jpg'
}],
provider: 'google'
},

twitter_new: {
id: '1159372707424854016',
username: 'Testuser4',
displayName: 'testa asera',
photos:
[{
value:
'https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png'
}],
provider: 'twitter'
}
};

export default fakeUsers;
5 changes: 5 additions & 0 deletions src/routes/api/oauth/oauth.routes.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import express from 'express';
import Social from '../../../controllers/social';
import passport from '../../../middlewares/passport';
import { fakeAuth } from '../../../middlewares/validators/socialLogin-mock';

const router = express.Router();

// test route
router.get('/auth/fake', fakeAuth, Social.login);

// social signup consent route
router.get('/signup/social', Social.signup);

router.get('/login/facebook', passport.authenticate('facebook', { scope: ['email'] }));
Expand Down
4 changes: 4 additions & 0 deletions src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import api from './api/index.route';
import oauth from './api/oauth/oauth.routes';
import error from '../middlewares/error.middleware';
import notfound from '../middlewares/404.middleware';
import { mock } from '../middlewares/validators/socialLogin-mock';

dotenv.config();

Expand All @@ -25,6 +26,9 @@ router.use(session({
},
saveUninitialized: true
}));
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
router.use(mock);
}
router.use(passport.initialize());
const apiVersion = process.env.API_VERSION;

Expand Down
Loading

0 comments on commit 240180b

Please sign in to comment.