Search code examples
ember.jspassport.jshandlebars.js

Ember app with server-side Google OAuth 2 Passport authentication (Node)


My Ember app needs to authenticate users with Google OAuth 2. I want to be able to store the authentication tokens in a database, so I decided to put the authentication process on the server side, using Passport for Node.

When the authentication is over on the server, how do you make your Ember app aware of the Passport "session"?


Solution

  • Once authenticated thanks to the passport process, the client, in all its communications with the server, sends the user session along with its requests. If you want your Handlebars template to condition on the presence of a user, my approach was to set up the following request handler on the server:

    app.get("/user", function (req,res) {
        if (req.isAuthenticated()) {
            res.json({
                authenticated: true,
                user: req.user
            })
        } else {
            res.json({
                authenticated: false,
                user: null
            })
        }
    })
    

    And in my Ember route I do the following request:

    App.ApplicationRoute = Ember.Route.extend({
        model: function () {
            return $.get("/user").then(function (response) {
                return {user: response.user};
            })
        }
    });
    

    So that in my Handlebars template I can do the following:

    {{#if user}}
        <p>Hello, {{user.name}}</p>
    {{else}}
        <p>You must authenticate</p>
    {{/if}}