Skip to content

Commit

Permalink
Feature(OauthTwitter): Login user via social media
Browse files Browse the repository at this point in the history
- WIll allow user to login via twitter

[Delivers #164489928]
  • Loading branch information
Jaman-dedy committed Apr 17, 2019
1 parent edd972c commit 8c39a28
Show file tree
Hide file tree
Showing 10 changed files with 110 additions and 3 deletions.
22 changes: 22 additions & 0 deletions controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,28 @@ class UserController {
return res.status(200).json({ status: 200, user: `welcome: ${req.user.username}`, token: generate });
}

/**
*
* @param {Object} req
* @param {*} res
* @returns {Object} Json data
*/
async twitterLogin(req, res) {
const twitterUser = {
username: req.user.username
};
const result = await User.findOrCreate({
where: {
username: twitterUser.username
},
defaults: twitterUser
});
const { generate } = generateToken(twitterUser);
if (process.env.NODE_ENV === 'development') {
return res.status(200).json({ status: 200, Welcome: twitterUser.username, token: generate });
} return result;
}

/**
* Checks if the email exists.
* @param {object} req request
Expand Down
9 changes: 9 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import express from 'express';
import session from 'express-session';
import passport from 'passport';
import googlePassport from './middlewares/passport-google';
import passportJwt from './middlewares/passport-jwt';
Expand All @@ -11,6 +12,13 @@ const port = process.env.PORT || 3000;
// @bodyParser configuration
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// @session configuration for twiitter login
app.use(session({
resave: false,
saveUninitialized: true,
secret: process.env.secretOrKey
}));
// @passport
app.use(passport.initialize());
googlePassport(passport);
Expand All @@ -26,6 +34,7 @@ app.use((req, res) => {
});
});


app.listen(port, () => {
console.log(`Server started successfully on ${port}`);
});
Expand Down
16 changes: 16 additions & 0 deletions middlewares/authentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import passport from 'passport';
import twitterStrategy from './passport-twitter';
import twitteruser from './serialize';
/**
* Get user information from the strategy and then pass it to serialize class
*/
class Authentication {
/**
* Authentication constructor
*/
constructor() {
this.twitter = passport.use(twitterStrategy);
this.serializeTwitteruser = twitteruser(passport, this.user);
}
}
export default Authentication;
21 changes: 21 additions & 0 deletions middlewares/passport-twitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import twitterStrategy from 'passport-twitter';
import dotenv from 'dotenv';

dotenv.config();
const { TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_CALLBACK_URL } = process.env;

const twStrategy = new twitterStrategy(
{
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: TWITTER_CALLBACK_URL
},
(token, tokenSecret, profile, done) => {
const userTwitter = {
username: profile._json.name
};
done(null, userTwitter);
}
);

export default twStrategy;
12 changes: 12 additions & 0 deletions middlewares/serialize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const twitterUser = (passport, user) => {
passport.serializeUser((userTwitwer, done) => {
done(null, userTwitwer.username);
});
passport.deserializeUser((username, done) => {
user.findByPk(username).then((userTwitwer) => {
done(null, userTwitwer);
})
.catch(err => done(err, false));
});
};
export default twitterUser;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"errorhandler": "^1.5.0",
"express": "^4.16.3",
"express-jwt": "^5.3.1",
"express-session": "^1.15.6",
"express-session": "^1.16.1",
"googleapis": "^39.2.0",
"jsonwebtoken": "^8.3.0",
"method-override": "^2.3.10",
Expand Down
14 changes: 14 additions & 0 deletions routes/api/auth/twitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-disable no-unused-vars */
import passport from 'passport';
import express from 'express';
import authentication from '../../../middlewares/authentication';
import user from '../../../controllers/user';

const TwitwerStrategy = new authentication();

const router = express.Router();

router.get('/login/twitter', passport.authenticate('twitter',));
router.get('/login/twitter/redirect', passport.authenticate('twitter', { session: false }), user.twitterLogin);

export default router;
2 changes: 2 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from '../config/swagger.json';
import facebookAuth from './api/auth/facebook';
import twitterAuth from './api/auth/twitter';

import users from './api/users';
import article from './api/article';
Expand All @@ -12,6 +13,7 @@ import article from './api/article';
const app = express();
// @router configuration
app.use('/api/users/auth', facebookAuth);
app.use('/api/users', twitterAuth);
app.use('/api/users', users);
app.use('/api/articles', article);
// @swagger UI
Expand Down
8 changes: 7 additions & 1 deletion test/2-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ import {
invalidToken,
validToken,
profile1,
testMailer
testMailer,
userTwitterSignup
} from '../testingdata/user.json';
import models from '../models/index';
import userController from '../controllers/user';

chai.use(chaiHttp);
chai.should();
Expand Down Expand Up @@ -237,6 +239,10 @@ describe('User ', () => {
done();
});
});
it('Should let the user signup with twitter', async () => {
const result = await userController.twitterLogin(userTwitterSignup);
result[0].dataValues.should.be.a('object');
});

// Get all users
it('Should get all users ', (done) => {
Expand Down
7 changes: 6 additions & 1 deletion testingdata/user.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"email": "blaise@gmail.com"
},
"googleValidToken": {
"access_token": "ya29.GlvtBh1zpj-_QCVaZhyOkXLtLDG-s5vawM1FWGnnhtkoV3lMMile89zb-lLNmadfvzWWNbVdPyaRTMlzQin8NliZF2cOo-k6oAVkPCxmEANhgkYTsW14acaFnw0r"
"access_token": "ya29.GlvuBhu14JeCW4eQjBWjVqMjbRwFfp4U2L3pnhmaRM3wuep3JwFkUtQ8Q7ZlXX9p59AIkqKYDf2gL5SHSvSWf731joIE9AphP1JzOSNaJS8fk_uo3FGXDTNMGxhK"
},
"googleInvalidToken": {
"access_token": "ya29.GlvhBpzY2hl2ShgOMrpkni8obGgwyX0mr85Oendf2kmblu3BrRNTmYK2DVQiPciVOBFkLvR57YE90qDyffgJOqgzV68zutO3-Y9QDKooAPuxPvwsbsWM36wwVPHT"
Expand All @@ -63,5 +63,10 @@
"username": "copainFab",
"bio": "I am a badass software developer at Andela",
"image": ""
},
"userTwitterSignup": {
"user": {
"username": "EmaBush"
}
}
}

0 comments on commit 8c39a28

Please sign in to comment.