Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate Firebase/Firechat with Wordpress user or database

I'm trying to use my Wordpress users to authenticate automatically with Firebase/Firechat.

You can see here on the documentation that Firebase can use custom authentication, by using secure Json Web Tokens: https://firechat.firebaseapp.com/docs/

They also refer to this Firebase page which describes generating and using these tokens in depth: https://www.firebase.com/docs/web/guide/login/custom.html?utm_source=docs&utm_medium=site&utm_campaign=firechat

So what I'm trying to accomplish are these things:

  1. If the user is logged-in, have Firechat recognize their user-login and set their chat alias as that.

  2. If they are not logged-in, they can still see the chat but when they go to talk it should prompt them to register or login (if you take a look at the main example in the Firechat documentation using Twitter to login, you can see it using this. Also the Firechat example on their home page does this as well).

  3. Set the user as a moderator if they are the author of the page. This is not so important as I'd much rather focus on just getting the chat to work first and worry about it later.

From what I understand this is all functionality that is already in Firechat, and Firebase is apparently able to authenticate with any server/system provided it can generate the proper credentials. I just can't seem to get anything working and I must have read that documentation about a hundred times.

With all that said, here is the farthest I've gotten:

<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.0.2/firebase.js"></script>

<!-- Firechat -->
<link rel="stylesheet" href="https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.css" />
<script src="https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.js"></script>

<?php 
include('./wp-blog-header.php');
include( './wp-load.php' );

//wordpress global variables
global $user_login;
global $post;
global $wpdb;
global $user_login;
global $current_user; 
?>    
    <div id="firechat-wrapper"></div>

    <script type="text/javascript">
var FirebaseTokenGenerator = require("firebase-token-generator");
var tokenGenerator = new FirebaseTokenGenerator("firebase-secret");
var caToken = tokenGenerator.createToken({ uid: $user_login });

var chatRef = new Firebase("https://yourfirebase.firebaseio.com/chat");
chatRef.authWithCustomToken(caToken, function(authData) {
    if (authData) {
        var chat = new FirechatUI(chatRef, document.getElementById('firechat-wrapper'));
        chat.setUser(authData.uid, authData[authData.provider].displayName);
    }
});
    </script>

The problem with that is it's actually not generating the token at all, as "FirebaseTokenGenerator" is not being called on (it's not included in the CDN afaik). I'm not sure how to call on it with Javascript, but I know there is a PHP helper library that does it.

It's as simple as:

<?php
  include_once "FirebaseToken.php";
  $tokenGen = new Services_FirebaseTokenGenerator("<YOUR_FIREBASE_SECRET>");
  $token = $tokenGen->createToken(array("uid" => "custom:1"));
?>

But the problem is I've no idea how to pass that information from PHP to the Javascript. I'm also pretty confused by how it all works. Do I have to generate a new token for each user? Or do it one time for the server, and let my login system handle authentication?

Hopefully I've not left anything out, but if you need more information just ask! Thanks for reading.

like image 968
Sky Davis Avatar asked Jun 02 '15 18:06

Sky Davis


1 Answers

Congratulations!

Firebase and Firechat is just so fun!

Place the javascript in a scriptfile and localize it with the token as data. Then initialize the chat with that token.

I'm using composer to place the php-files inside back-end. You need both php-jwt and token-generator. Take a look at the Packagist browser!

"firebase/php-jwt": "^2.1",
"firebase/token-generator": "^2.0"

https://packagist.org/packages/firebase/php-jwt

https://packagist.org/packages/firebase/token-generator

If not using composer, include the downloaded source at a fixed place inside your project and include the libraries.

Implementation example

The PHP-file to initialize the chat from backend with logged-in user:

/* firechat-example.php */
$userdata = get_userdata( get_current_user_id() );
$tokenGen = new \Services_FirebaseTokenGenerator( "#your-token-from-firebase#" );
$token    = $tokenGen->createToken( array( "uid" => 'custom:'.$userdata->ID ), array( "admin" => true ) );
wp_enqueue_script( 'your-chat-js', get_stylesheet_directory_uri() . '/firechat-example.js', [ 'jquery' ], null, true );

$data = [
            'token' => $token,
            'user_id'   => $userdata->ID,
            'user_name' => $userdata->display_name,
        ];

wp_localize_script( 'your-chat-js', 'firechat_backend', $data );
echo '<div class="firechat-wrapper"></div>'

And so the js-file that is localized by WordPress, eg your theme or plugin:

/* firechat-example.js */
jQuery( document ).ready(function($) {
    var firechatRef = new Firebase('https://your-firebase-app-name.firebaseio.com/chat');
    firechatRef.authWithCustomToken( firechat_backend.token, function(error, authData) {
    if (error) {
        console.log(error);
    }
    else {
        var chat = new FirechatUI(firechatRef, document.getElementById('firechat-wrapper'));
        chat.setUser( firechat_backend.user_id, firechat_backend.user_name, function(user) {
                chat.resumeSession();
            });
        }
    });
});

The hard part is to customize the chat but it's another story using the sourcecode from the firechat github repo and then "grunting" changes to a new distribution for your WordPress-chat :-)

like image 78
Andreas Ek Avatar answered Sep 28 '22 07:09

Andreas Ek