Facebook Auth ( Node.js and Passport.js )
Tags: node, backend, passportjs, facebook
Published: 2019-10-06 14:41:53

---
title: Facebook Auth ( Node.js and Passport.js )
published: true
description: 
tags: #node #backend #passport.js #facebook
cover_image : https://thepracticaldev.s3.amazonaws.com/i/2m59m2thg7wku6htlipo.png
---

In this week, i learned about auth with social networks ( in this case, auth with Facebook ). I created a simple API with Node.js and Passport.js ( auth API ). So, let's code !

**Passport.js**
[Passport](http://www.passportjs.org) is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

Before code, is necessary make some configurations - get API key in [Facebook Developers] (https://developers.facebook.com ). I found a video explaining how to make the settings : https://www.youtube.com/watch?v=_hF099c0A9M 

**``passes as body in the request json:``** (use Postman/Insomia)
```json

{
 "access_token": "YOUR ACCESS TOKEN IN FACEBOOK DEVELOPER"
}

```
**``required dependencies``**



```json

"dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^8.1.0",
    "express": "^4.17.1",
    "express-jwt": "^5.3.1",
    "passport": "^0.4.0",
    "passport-facebook": "^3.0.0",
    "passport-facebook-token": "^3.3.0",
    "mongoose": "^5.7.1"
  }
```
**``project structure``**

```bash
├── index.js 
├── passport.js 
└── app
 └── routes.js
 └── models
    └── user.js
└── .env
```

**``index.js``**

```javascript
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();

// allow your application to be consumed
app.use(cors());

// mongodb local 
mongoose.connect(process.env.MONGODB_URL_DEV, {
    useUnifiedTopology: true ,
    useNewUrlParser : true
})

app.listen(3333, () => console.log('server on !'))
```
**``.env``**

```javascript
MONGODB_URL_DEV=mongodb://localhost:27017/YOUR_NAME_PROJECT
PRIVATE_KEY=YOUR_KEY_PRIVATE
clientID=YOUR_CLIENT_ID
clientSecret=YOUR_CLIENT_SECRET
```

**`` └── models
    └── user.js``**
```javascript
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name : String,
    facebook_id : String,
    email: String,

});

module.exports = mongoose.model('AuthFacebook',UserSchema);

```
**``passport.js``**
```javascript
const passport = require('passport');
const FacebookTokenStrategy = require('passport-facebook-token');
const User = require('./app/models/user');
require('dotenv').config();

passport.use('facebookToken', new FacebookTokenStrategy({
    clientID: process.env.clientID,
    clientSecret:process.env.clientSecret
}, async (accessToken, refreshToken, profile, done) => {
    try {
        if( await User.findOne({'facebook_id':profile.id})) return console.log('this account is already registered!')
        const email = profile.emails[0].value;
        const { id: facebook_id, displayName: name } = profile;
        const user = await User.create({
            email,facebook_id,name
        })
        await user.save();
        
        console.log(user)
    }catch(error){
        done(error,false,error.message)
    }
}));
```

**``routes.js``**

```javascript
const express = require('express');
const router = new express.Router;

router.post('/user/signin/facebook',passport.authenticate('facebookToken',{session:false}))

module.exports = router;
```

**``SEE THE RESULT``**
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/0yewgvymypmv5prwhen9.gif)