Implementing Facebook JavaScript SDK Login Frontend + Rails API Backend

Yijing-Ball Z App Shots

Set Up

  1. Create New App. Save your APP ID. You will use this APP ID later.
# taken from generate server.xml with the following command:#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes# run as follows:#    python then in your browser, visit:#    https://localhost:4443import BaseHTTPServer, SimpleHTTPServerimport sslhttpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)httpd.serve_forever()

Facebook JavaScript SDK

document.addEventListener("DOMContentLoaded", function() {// <!-- FB SDK LOAD START -->window.fbAsyncInit = function() {FB.init({appId      : 'yourAPPID',cookie     : true,xfbml      : true,version    : 'v5.0'});FB.AppEvents.logPageView();};(function(d, s, id){var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); = id;js.src = "";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));// <!-- FB SDK LOAD END -->});
function checkLoginState() {    FB.getLoginStatus(function(response) {    statusChangeCallback(response);  });}
function statusChangeCallback(response) {   console.log(response);   if (response.status === ‘connected’) {      console.log("logged in!")   
} else { console.log(‘please login’) }}
// <!-- FB SDK LOAD START -->window.fbAsyncInit = function() {FB.init({appId      : 'yourAPPID',cookie     : true,xfbml      : true,version    : 'v5.0'});  FB.AppEvents.logPageView();  checkLoginState()};

Logging in with Facebook’s SDK

<fb:login-button scope="public_profile,email"></fb:login-button>
class User {   constructor(name, uid, id){ = name   this.uid = uid = id  }}
class ApiAdapter {   constructor() {    this.baseUrl = 'Copy and paste your Rails API url. E.g.   http://localhost:3000/'    }   userPost(attributes){     const url = `${this.baseUrl}/users`     const user = {           attributes,       }    return fetch(url, {         method: 'POST',         headers: {        'content-type': 'application/json',         },        body: JSON.stringify({ user }),         }).then(res => res.json()).catch(error => {            console.log(error.message)         })     }
const user = new User()const adapter = new ApiAdapter()function testAPI() {    console.log('Welcome!  Fetching your information.... ');    FB.api('/me', function(response) { =      user.uid =      const userAttrs = {}      userAttrs["name"] =      userAttrs["uid"] = user.uid       adapter.userPost(userAttrs).then(res => loginUser(,      });   }
def create    user = User.find_or_initialize_by(uid: user_params["attributes"]["uid"])    if !!           render json: user, status: 200   else = user_params["attributes"]["name"]       render json: user, status: 200  end  private    def user_params        params.require(:user).permit(attributes: {})    endend
function loginUser(username, userid){document.getElementById("logbtn").innerHTML = `<button type="button" class="logout" id="${userid} onclick="logout()">Logout</button>`console.log(`Welcome ${username}!`)//We will uncomment this line soon

Logging Out

function addScript(js){   const script = document.createElement('script');   script.type = 'text/javascript';   script.text = js   document.body.appendChild(script);}
const logoutScript = `function logout() {   document.querySelector(".logout").addEventListener('click',   FB.logout(function(response) {   location.reload();}));}  `





Social Entrepreneur and Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Synchronicity with Twilio Sync January 28, 2017 at 12:15AM

Apache Camel: Trace control with Zipkin

Pyspark just got a massive update

Lucky Block Blue Mod 1.8–1.7.10 Minecraft — Spiral lucky blocks —

To normalize or to denormalize, that is the question

Has Agile Become Addiction to Instant Gratification?

Database Running in Docker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Felipe Bohorquez

Felipe Bohorquez

Social Entrepreneur and Software Engineer

More from Medium

Dependency injection (DI) and DI Container with Vanilla JavaScript

DI Container

Fetch API 沒有傳送 cookies

What is URL?*nHylTd9wjy7-lE9uTi0XlQ.png

Using Rail’s Active Storage to add an upload field to a React form.