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 http://www.piware.de/2011/01/creating-an-https-server-in-python/# generate server.xml with the following command:#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes# run as follows:#    python simple-https-server.py# 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()
python simple-https-server.py

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); js.id = id;js.src = "https://connect.facebook.net/en_US/sdk.js";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!")   
testAPI();
} 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){   this.name = name   this.uid = uid   this.id = 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.name = response.name      user.uid = response.id      const userAttrs = {}      userAttrs["name"] = user.name      userAttrs["uid"] = user.uid       adapter.userPost(userAttrs).then(res => loginUser(user.name,      res.id))      });   }
def create    user = User.find_or_initialize_by(uid: user_params["attributes"]["uid"])    if !!user.id           render json: user, status: 200   else       user.name = user_params["attributes"]["name"]       user.save       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
//addScript(logoutScript)
}

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();}));}  `

Conclusion

--

--

--

Social Entrepreneur and Software Engineer

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

Recommended from Medium

Synchronicity with Twilio Sync

http://ift.tt/2kc3vFG 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 — Wminecraft.net

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?

https://cdn-images-1.medium.com/max/800/1*nHylTd9wjy7-lE9uTi0XlQ.png

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