Giter Club home page Giter Club logo

ember-token-auth's Introduction

Ember-Token-Auth

Current Version: 3.0.4-beta

Circle CI

This is an EmberCli addon for using the Ember-OAuth2 to handle authentication in your app.

Installation

To use the addon with your EmberCli app add it to your package.json file and run the generate to install the bower dependencies.

npm install --save-dev ember-token-auth
ember generate ember-token-auth

Getting it to work with your Ember-CLI App

Create an initialzier to setup your Ember-OAuth2 config. For more information checkout the Ember-OAuth2 README.

In addition you will need to set the name of the model that the user should be persisted to. In the example setup it is set to user.

The intializer should be configured to run before the session initializer

import Ember from 'ember';
import OAuth2 from 'ember-oauth2';

export function initialize(registry, app) {
  window.EmberENV['ember-oauth2'] = {
    model: 'user',
    google: {
      clientId: "xxxxxxxxxxxx",
      authBaseUri: 'https://accounts.google.com/o/oauth2/auth',
      redirectUri: 'https://oauth2-login-demo.appspot.com/oauth/callback',
      scope: 'public write'
    }
  }
}

export default {
  name: 'ember-oauth2-config', 
  before: 'session',
  initialize: initialize
}

Ember-Token-Auth addons session initializer injects the sessionCurrent object into controller, route and adapter in your application.

To create a protected route that requires authentication define your routes like this:

// app/routes/the-route.js

import Protected from './routes/protected';

export default Protected.extend({
  // your route 
});

Depending on the needs of your app you can create a protected route by importing it from ember-token-auth a few different ways. For more information checkout the EmberCli Addon docs.

import Protected from './routes/protected';
// or 
import Protected from 'app-module-prefix/routes/protected';
// or
import Protected from 'ember-token-auth/routes/protected';

Add the Session controller available to your controllers in the Application.js controller.

import Ember from 'ember';

export default Ember.Controller.extend({
  sessionCtrl: Ember.inject.controller('session')
  currentUser: Ember.computed.alias("sessionCtrl.currentUser")
});

Then from your template you just need to handle the authenticate method and pass in the providerId to start the authentication process.

<h2>Ember Token Auth</h2>

<button id="login" {{action 'authenticate' 'google'}}>Sign In</button>

Injecting the session controller gives you access to the currentUser, loginError, and isAuthenticated attributes of the session controller.

The current implementation looks for a User model for storing the current logged in user. Over this model in your App to config your user.

Session Model

The session model provides the interface for handling session data via Ember-OAuth2. If you need to interact with the session it provides the following properties:

methods

  • authorize - Returns a promise with the resolved or rejected response
  • signout - Removes the token from the localstorage and sets the auth and providerId to null on the session model

properties

  • provider - You can set the provider with the providerId from the OAuth2 config
  • isExpired - Returns true if the accessToken is expired otherwise false
  • isNoExpired - Returns true if the accessToken is not expired otherwise false
  • token - Return the the token from localstorage saved by EmberOAuth2 if it exists otherwise null
  • accessToken - Return the access token property value from the token saved in localstorage

Optional Config

If there is an error authorizing the user and getting the user information the session controller will set the loginError property defined in it to true. One way to handle the loggin error is to define a session view the observes the controllers loginError property. Here is one way to show the user that an error occurred logging in:

app/templates/application.hbs

<h2 id='title'>Welcome to Ember.js</h2>

{{current-session currentUser=sessionCtrl.currentUser loginError=sessionCtrl.loginError}}

{{outlet}}

app/components/current-session.js

import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['current-user'],
  loginError: false,

  didInsertElement: function() {
    Ember.addObserver(this, 'loginError', this, this.loginErrorChanged);
  },

  loginErrorChanged: function(/*comp, value*/) {
    if (this.get('loginError')) {
      Ember.run.once(this, function() {
        Ember.$('.current-user').html('<p class="error">There was an error logging in. Please try again.</p>');
      });
    }
  }
});

Running Ember-Token-Auth and the tests

  • git clone https://github.com/amkirwan/ember-token-auth.git
  • npm install -g ember-cli bower phantomjs
  • npm install && bower install
  • ember serve
  • visit http://localhost:4200 to run the demo test dummy app.
  • visit http://localhost:4200/tests to run the tests

Building

  • ember build

For more information on using ember-cli, visit EmberCli

ember-token-auth's People

Contributors

amkirwan avatar baijum avatar halfbyte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ember-token-auth's Issues

ember-token-auth and ember-oauth2 - the same thing?

Reading through the documentation and being quite new to oAuth in general, I think its very confusing if these two addons are actually the same thing.

The documentation telling you to refer to the other addon continuously isn't great...

Attempting to install ember-oauth2 resulted in a error, so I chose ember-token-auth.

Are they the same? If not, what is the difference and which one should you use when developing using Ember CLI.

Thanks in advance

How to config redirectUri?

@amkirwan

I was confused the redirectUri.
At first I've registered the redirectUri in google develop console, then added it in my app, like this:
redirectUri: http://localhost:4200/oauth/callback.
But After I chose a account to click 'Accept' in alert dialog, it just stay on /oauth/callback blank page, never sent confirm to google.

In alert dialog console, there is a error, says:"The URL '/oauth/callback' did not match any routes in your application". Need I add a route for /oauth/callback in router.js?

ember generate failure - Unexpected identifier

Hi, I was able to install it, but the generate command failed.

≻ ember --version
ember-cli: 2.10.0
node: 6.9.2
os: darwin x64

≻ npm install --save-dev ember-token-auth
[email protected] /Users/xxxx/Projects/ember-home_pager_api
└── [email protected]

≻ ember generate ember-token-auth
Unexpected identifier
/Users/xxxx/Projects/ember-home_pager_api/node_modules/ember-token-auth/blueprints/ember-token-auth/index.js:8
afterUninstall: function() {
^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Function.Blueprint.load (/Users/xxxx/Projects/ember-home_pager_api/node_modules/ember-cli/lib/models/blueprint.js:1278:29)
at Function.Blueprint.lookup (/Users/xxxx/Projects/ember-home_pager_api/node_modules/ember-cli/lib/models/blueprint.js:1255:24)

ember build errors

$ ember build
version: 0.0.40
Build failed.
Merge error: file "ember-oauth2/.bower.json" exists in vendor and vendor-addon - pass option { overwrite: true } to mergeTrees in order to have the latter file win

ember build errors pt.2

Build failed.
Line 43: Unexpected token )
File: ember-token-auth/initializers/session.js
Error: Line 43: Unexpected token )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.