EzDevInfo.com

ember-simple-auth

A lightweight library for implementing authentication/authorization in Ember.js applications. Ember Simple Auth - lightweight authentication/authorization library for Ember.js ember simple auth - lightweight authentication/authorization library for ember.js

Ember Simple Auth: Session lost on refresh

I'm using Ember Simple Auth Devise v 0.6.4 in an Ember-cli app.

I can log in fine but when I refresh the page the session is lost. (Tested in Firefox and Chrome.)

Right after logging in, inspecting the localStorage shows the session and after refreshing localStorage is empty.

Here's what's in the local storage when I sign in:

enter image description here


Source: (StackOverflow)

Ember: Add mixin to every route except one

Using Ember-Simple-Auth in an Ember-Cli app, I'm trying to require authentication on pretty much every route in my application. I didn't want to use the AuthenticatedRouteMixin on every route, because I don't want to have to define every route. So I added the mixin to ApplicationRoute.

However, this causes an infinite loop, because obviously the login route extends from the same ApplicationRoute and therefore now protected.

How do I include this mixin in every route except LoginRoute?


Source: (StackOverflow)

Advertisements

How to store the user in a session

I am trying to set up ember-simple-auth with a django-rest-framework backend, but I'm running into some trouble saving the user to the session. I have to be able to do something like this in my templates:

<h2>Welcome back, {{session.user}}</h2>

So following several guides I found, I have got the authentication and authorization working so that I can get a valid token and use is in requests. To get the user on the session, I have modified App.CustomAuthenticator.authenticate so that when the token is returned, the username is also stored to the session:

authenticate: function(credentials) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
        Ember.$.ajax({
            url: _this.tokenEndpoint,
            type: 'POST',
            data: JSON.stringify({username: credentials.identification, password: credentials.password }),
            contentType: 'application/json'
        }).then(function(response) {
            Ember.run(function() {
                resolve({
                    token: response.token,
                    username: credentials.identification
                });
            });
        }, function(xhr, status, error) {
            var response = JSON.parse(xhr.responseText);
            Ember.run(function() {
                reject(response.error);
            });
        });
    });
},

I then modified Application.intializer to give session a user property:

Ember.Application.initializer({
    name: 'authentication',
    before: 'simple-auth',
    initialize: function(container, application) {
        // register the custom authenticator and authorizer so Ember Simple Auth can find them
        container.register('authenticator:custom', App.CustomAuthenticator);
        container.register('authorizer:custom', App.CustomAuthorizer);
        SimpleAuth.Session.reopen({
            user: function() {
              var username = this.get('username');
              if (!Ember.isEmpty(username)) {
                return container.lookup('store:main').find('user', {username: username});
              }
            }.property('username')
        });
    }
});

However, when {{session.user.username}} is rendered it is just an empty string. My questions are:

  1. Is this really the best way to assigning a user to the session? It seems clumsy to me but I can't see anything better.
  2. I assume that the empty string is because a Promise is returned rather than a User object, so how to I resolve it?

Source: (StackOverflow)

Access user's account info with Ember Simple Auth

I'm using ember-simple-auth in my application and it's working well, but I would like to be able to display properties from the current user (such as email or name) in the UI. In the past I've used an application initializer to do this and essentially inject all controllers with the currentUser, but that required the current user to be known when the application was initialized. Since I'm using OAuth, the user is not known when the application loads.

Is there a way to get properties from the currently logged in user?


Source: (StackOverflow)

CORS preflight channel did not succeed

I'm trying to build a Ember app with PHP REST framework as my api locally. The Ember app is being served at http://localhost:4200 and the api is being served from just http://localhost. This is causing a CORS issue. I've tried everything that I can think of, but I keep getting an error back saying the request was blocked and that the preflight channel did not succeed. It doesn't succeed in Firefox or Chrome.

I've added the following to the .htaccess file for my api:

Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Origin "http://localhost:4200"
Header set Access-Control-Allow-Credentials true
Header set Access-Control-Allow-Headers "accept, content-type"

Here's my request headers:

Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:4200
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

And the response headers:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept, content-type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: http://localhost:4200
Connection: close
Content-Type: text/html; charset=utf-8
Date: Fri, 24 Jul 2015 17:10:49 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.12
Set-Cookie: 24fd751c8630b64fcf935a94e8bcef46=qih6pfnqo94d4cgi5b5d79h4i6; path=/
Transfer-Encoding: chunked
X-Powered-By: PHP/5.5.12
p3p: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"

Any ideas or solutions? Any help is appreciated. Thanks!


Source: (StackOverflow)

Workflow for Ember-simple-auth, Torii and Facebook Oauth2

After my previous question about ember-simple-auth and torii, I successfully authenticate my users with their Facebook accounts.

But currently, torii's provider facebook-oauth2 is returning an authorization code from Facebook ; when the promise resolves, I send this authorization code to my backend where I perform a request against Facebook to get the user's id and email : then I authenticate the user on my backend, generating a specific access token and sending back to my ember application.

Client code :

// app/controllers/login.js
import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';

export
default Ember.Controller.extend(LoginControllerMixin, {
    // This authenticator for a simple login/password authentication.
    authenticator: 'simple-auth-authenticator:oauth2-password-grant',
    actions: {
        // This method for login with Facebook.
        authenticateWithFacebook: function() {
            var _this = this;
            this.get('session').authenticate(
                'simple-auth-authenticator:torii',
                "facebook-oauth2"
            ).then(
                function() {
                    var authCode = _this.get('session.authorizationCode');
                    Ember.$.ajax({
                            type: "POST",
                            url: window.ENV.host + "/facebook/auth.json",
                            data: JSON.stringify({
                                    auth_code: authCode
                            }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(data) {
                                    // TODO : manage access_token and save it to the session
                            },
                            failure: function(errMsg) {
                                    // TODO : manage error
                            }
                    });
                },
                function(error) {
                    alert('There was an error when trying to sign you in: ' + error);
                }
            );
        }
    }
});

The problem is : the ember-simple-auth's session is marked as authenticated when the authenticate's promise resolves and then the app redirects to the specific authenticated route. But in this case the session should be authenticated when my backend returns the "real" access_token.

Is there a way to manage this workflow with ember-simple-auth-torii or should I write my own authenticator ?


Source: (StackOverflow)

Redirecting from HTTP to HTTPS w/ Simple Auth

I was hoping to get some recommendations on how to approach redirecting users from HTTP to HTTPS using an ember initializer with ember-simple-auth.

`import ENV from 'cio/config/environment'`

SSLInitializer =
  name: 'ssl'
  before: 'simple-auth-cookie-store'
  initialize: (container, application) ->
    application.deferReadiness()

    # Redirect if hitting HTTP and SSL is enabled
    if ENV.SSL and window.location.protocol is "http:"
      window.location.href = "https:" + window.location.href.substring(window.location.protocol.length)
      return false

    application.advanceReadiness()

`export default SSLInitializer`

But it seems that the cookie gets invalidated even when the if statement evaluates to true. I've tried several things, including:

  • before: 'simple-auth'
  • before: 'store'
  • application.destroy() within the if statement, before the window.location.href is set

From what I can tell, after debugging. The app does redirect to HTTPS, but then the cookieName is not found in document.cookie. (https://github.com/simplabs/ember-simple-auth/blob/master/packages/ember-simple-auth-cookie-store/lib/simple-auth-cookie-store/stores/cookie.js#L154)

Before this method worked because we had simple snippet in the index.html, but w/ CSP we'd like to keep it in an initializer. Any recommendations?

Thanks!


Source: (StackOverflow)

ember-simple-auth deferReadiness until user is loaded

I am using ember-cli-simple-auth and have extended the session object to include the currentUser which is retrieved from the /me endpoint. However, when the page is reloaded and the user is logged in there is a delay until the logged in user information is loaded. I would like to defer the apps readiness until the user is retrieved.

I have this in a custom-session initializer.

import Session from 'simple-auth/session';
export default {
  name: 'custom-session',
  initialize: function(container, app) {
    var _app = app;
    var SessionWithCurrentUser = Session.extend({
        currentUser: function() {
            var _this = this;
            return this.container.lookup('store:main').find('me', '').then(function(data){
                _app.advanceReadiness();
                _this.set('currentUser', data);
            }, function(data){
                console.log('failed');
                return data;
            });
        }.property()
    });

    container.register('session:withCurrentUser', SessionWithCurrentUser);
    app.deferReadiness();
  }
};

It appears that advanceReadiness is never called so the app never loads. I am very new to ember and am still getting my head around the container so am unsure of how this works. What am I doing wrong?

Update

export default {
  name: 'custom-session',
  initialize: function(container, app) {
    var _app = app;
    var SessionWithCurrentUser = Session.extend({
        currentUser: function() {
            var _this = this;
            return _this.container.lookup('store:main').find('me', '').then(function(data){
                _app.advanceReadiness();
                _this.set('currentUser', data);
            }, function(data){
                console.log('failed');
                return data;
            });
        }.property()
    });

    var session = SessionWithCurrentUser.create();
    container.register('session:withCurrentUser', session, { instantiate: false });
    app.deferReadiness();
    session.currentUser();
  }
};

From the answer suggested I changed it to this but this gives the error undefined is not a function coming from the call to session.currentUser().

Stack trace

Uncaught TypeError: undefined is not a function app/initializers/custom-session.js:28
__exports__.default.initialize app/initializers/custom-session.js:28
(anonymous function) vendor.js:14807
visit vendor.js:15216
visit vendor.js:15214
visit vendor.js:15214
visit vendor.js:15214
DAG.topsort vendor.js:15312
Namespace.extend.runInitializers vendor.js:14804
Namespace.extend._initialize vendor.js:14689
Backburner.run vendor.js:12247
apply vendor.js:30430
run vendor.js:29048
runInitialize vendor.js:14488
fire vendor.js:3184
self.fireWith vendor.js:3296
jQuery.extend.ready vendor.js:3502
completed

Source: (StackOverflow)

Ember CLI + Ember Data + Simple Auth: authorize gets not called

i am using Ember CLI + Ember Data + Simple Auth. The authenticator is working fine. But when im am doing a Rest Call with Ember Data Rest Adapter this.store.findAll("user"); the authorize function in my custom authorizer don't gets called.

The Rest API Endpoint is on an other domain, so i added the url to the crossOriginWhitelist in my environment.js.

environment.js:

module.exports = function(environment) {
    var ENV = {
        // some configuration
    };

    ENV['simple-auth'] = {
        crossOriginWhitelist: ['http://api.xxxx.com'],
        authorizer: 'authorizer:xxxx',
        routeAfterAuthentication: 'dashboard',
    };

    return ENV;
};

authorizer

import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';

var XXXXAuthorizer = Base.extend({
    authorize: function(jqXHR, requestOptions) {
        // Some Code, gets not called, damn it :(
    }
});



export default {
    name: 'authorization',
    before: 'simple-auth',
    initialize: function(container) {
        container.register('authorizer:xxxx', XXXXAuthorizer);
    }
};

index.html

....
        <script>
            window.XXXXWebclientENV = {{ENV}};
            window.ENV = window.MyAppENV;
            window.EmberENV = window.XXXXWebclientENV.EmberENV;
        </script>
        <script>
            window.XXXXWebclient = require('xxxx-webclient/app')['default'].create(XXXXWebclientENV.APP);
        </script>
....

Thanks for help :)


Source: (StackOverflow)

How do I revoke a token using Ember Simple Auth and redirect to the homepage?

I have an Ember app using Ember Simple Auth. I need to revoke tokens on the server side, which I can do easy enough by setting the revoked_at column, in the oauth_access_tokens table, to a timestamp.

This causes the server to respond to Ember with a 401, which is great. However, Ember Simple Auth does not seem to fire the authorizationFailed action in the application route. I put a simple debugger in the action to test if it's getting hit.

What I want to happen is trigger any kind of authorization error to hit this action, which would allow me to manually run invalidate() if it hasn't done so yet, and redirect them to a login page.

Thanks.


Source: (StackOverflow)

Simple auth addon seems to not be reading env config

I am following the example here, and I have this in my config/environment.js file:

ENV['simple-auth'] = {
  authorizer: 'simple-auth-authorizer:devise',
  routeAfterAuthentication: 'landing-pages'
};

However, after my app authenticates it tries to go to the index route. I confirmed the configuration variable used had index as the routeAfterAuthentication property by adding a breakpoint in the sessionAuthenticationSucceeded method of the library.

I tried importing the configuration in the environment.js file ES6-style, but that doesn't seem possible.


Source: (StackOverflow)

Redirect user to the same page after logging out

Sometimes I would like to be able to have a user log out, but stay on the page they were already on.

I'm using invalidateSession to log the user out, but this reloads the application and takes them to my application's root URL - the login page. In some cases, this is not the behavior I want, and I would instead like to have the user stay on the page they're on, but show the "logged out" version of that page.

Is there a way to log a user out and either a) not reload the application, or b) specify which page they should be redirected to after log out?

I've tried transitioning to another route, but there doesn't seem to be a way to do this after the session is invalidated (it's not a promise).


Source: (StackOverflow)

ember-simple-auth: Any way to get session from within the Router?

I want to use analytics tracking on every transition like mentioned in Mixpanel with EmberJS

In order to do so, I need to be able to reopen the Router.

Is there any way with ember-simple-auth to get the current session there? My understanding was that it's available to all the routes and controllers, but saw no mention of the Router specifically.

EDIT:

An alternative approach I'm exploring right now is to include a mixin on all the routes where I want to do analytics identification. I have a mixin like the following:

`import Ember from 'ember'`

AnalyticsMixin = Ember.Mixin.create
  beforeModel: (transition) ->
    @_super(transition)
    userId = @get('session.user_id')
    if (!Ember.isEmpty(userId))
      user = @store.find('user', userId)
      username = user.get('username') # this doesn't work

I can get the user_id from the session object, although the Session.reopen that I did doesn't seem to include the user on its own. Nor does @store.find('user', userId) work.

The following works fine in a template:

Authentication =
  name: "authentication"
  before: "simple-auth"
  initialize: (container) ->
    Session.reopen
      user: (->
        userId = @get('user_id')
        if (!Ember.isEmpty(userId))
          return container.lookup('store:main').find('user', userId)
      ).property('userId')
    container.register("authenticator:custom", CustomAuthenticator)

Source: (StackOverflow)

Ember-Simple-Auth OAuth 2.0 not sending the right parameters

So I am setting up ember-simple-auth using the OAuth 2.0 extension. The issue is whenever I try to login and look at what's being sent as form data, it's only sending the grant_type and password parameter. However, the password parameter is always empty, and sometimes it doesn't even show up. The username parameter is always missing, I haven't seen it thus far.

Here is my login.hbs code (btw I am using ember-cli)

<form {{action 'authenticate' on='submit'}}>
  <label for="identification">Login</label>
  {{input class="form-control" id='identification' placeholder='Enter Login' value=identification}}
  <label for="password">Password</label>
  {{input class="form-control" id='password' placeholder='Enter Password' type='password' value=password}}
  <button type="submit">Login</button>
</form>

My login.js code in controllers

import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';

export default Ember.Controller.extend(LoginControllerMixin, {
  authenticator: 'simple-auth-authenticator:oauth2-password-grant'
});

My application.js code in controllers

// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin);

In my config/environment.js file

if (environment === 'development') {
  …
  ENV['simple-auth-oauth2'] = {
    serverTokenEndpoint: '/api/v1/oauth/token'
  }
  …
}

It's making the call to the right url after this change

In my initializers folder

// app/initializers/simple-auth-config.js
export default {
  name:       'simple-auth-config',
  before:     'simple-auth',
  initialize: function() {
    window.ENV = FrontENV;
  }
};

It's pretty easy to notice that most of this code is copied from the tutorial on simplelabs with some customizations. However, I can't figure out why the parameters aren't being sent correctly. Any help would be appreciated!


Source: (StackOverflow)

Capturing failed request with ember-simple-auth

I am adding functionality to allow users to reject un-expired oauth tokens. (I am using ember-simple-auth-oauth2 and a custom oauth2 implimentation).

I would like to notify clients using a rejected token that their token was manually rejected.

The 401 response from the server contains the reason the token is no longer valid ({message: "Token was expired by ip 1.1.1.1"}).

None of the invalidationSucceeded callbacks or events in the session or application mixin seem to have the 401 request passed to this info.

Is there a way to access the body of the request that returned the 401 before the redirect?


Source: (StackOverflow)