How to Refresh Application Route After Login Ember
Ember Simple Auth API docs
Ember Simple Auth supports all Ember.js versions starting with 3.0. Node 12 is required
Ember Simple Auth
Ember Simple Auth is a lightweight library for implementing authentication/ dominance with Ember.js applications. It has minimal requirements with respect to application construction, routes etc. With its pluggable strategies it can support all kinds of hallmark and authorization mechanisms.
Table of Contents
Bones Information
- What does it do?
- How does it work?
- Example App
Usage
- Installation
- Walkthrough
Core Feature Guides
- The Session Service
- Authenticators
- Customizing an Authenticator
- Implementing a custom Authenticator
- Session Stores
- Store Types
- Implementing a Custom Store
- FastBoot
- Engines
- Testing
Other Guides
- Managing a current User
- GitHub authorization with torii
Other Resource
- Upgrading from Pre-1.0 versions
- API Documentation
What does information technology do?
- it maintains a client side session and synchronizes its state across multiple tabs/windows of the application
- information technology authenticates the session against the application's own server, external providers like Facebook etc.
- it is easily customizable and extensible
How does it work?
Ember Simple Auth consists of 3 chief building blocks - the session, a session shop and authenticators.
The session service is the main interface to the library. It provides methods for authenticating and invalidating the session as well equally for setting and reading session data.
The session store persists the session state so that it survives a page reload. It also synchronizes the session state across multiple tabs or windows of the application then that due east.g. a logout in i tab or window also results in a logout in all other tabs or windows of the awarding.
Authenticators authenticate the session. An application can leverage multiple authenticators to back up multiple ways of authentication such every bit sending credentials to the application'southward own backend server, Facebook, github etc.
Instance App
Ember Simple Auth comes with a test app that implements a complete auth solution including authentication against the application's own server likewise as Facebook, authorization of Ember Information requests and error handling. Check out that exam app for reference. To beginning it, run
git clone https://github.com/simplabs/ember-unproblematic-auth.git cd ember-uncomplicated-auth/packages/test-app yarn install && ember serve
and go to http://localhost:4200.
Installation
Installing the library is every bit piece of cake as:
ember install ember-elementary-auth
Upgrading from a pre-3.0 release?
The three.0 release of ember-simple-auth removes previously deprecated code, introducing some breaking changes, but thankfully there is an upgrade guide.
Walkthrough
Once the library is installed, the session service tin can be injected wherever needed in the application. In guild to brandish login/logout buttons depending on the electric current session state, inject the service into the respective controller or component and query its isAuthenticated
property in the template:
// app/controllers/application.js import Controller from '@ember/controller' ; import { inject as service } from '@ember/service' ; consign default form ApplicationController extends Controller { @service session ; … }
In the invalidateSession
action phone call the session service's invalidate
method to invalidate the session and log the user out:
// app/controllers/application.js import Controller from '@ember/controller' ; import { inject every bit service } from '@ember/service' ; import { action } from "@ember/object" ; export default grade ApplicationController extends Controller { @service session ; … @action invalidateSession ( ) { this . session . invalidate ( ) ; } }
For authenticating the session, the session service provides the authenticate
method that takes the proper name of the authenticator to apply besides as other arguments depending on specific authenticator used. To define an authenticator, add together a new file in app/authenticators
and extend one of the authenticators the library comes with, eastward.grand.:
// app/authenticators/oauth2.js import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant' ; export default form OAuth2Authenticator extends OAuth2PasswordGrant { }
With that authenticator and a login course like
the session can be authenticated with the session service'south authenticate
method:
// app/controllers/login.js import Controller from '@ember/controller' ; import { inject as service } from '@ember/service' ; import { action } from "@ember/object" ; import { tracked } from "@blink/tracking" ; export default course LoginController extends Controller { @tracked errorMessage ; @service session ; @action async cosign ( e ) { e . preventDefault ( ) ; let { identification, password } = this ; try { look this . session . authenticate ( 'authenticator:oauth2' , identification , password ) ; } take hold of ( error ) { this . errorMessage = mistake . error || fault ; } if ( this . session . isAuthenticated ) { // What to do with all this success? } } @action updateIdentification ( east ) { this . identification = e . target . value ; } @action updatePassword ( e ) { this . password = e . target . value ; } }
To make a route in the awarding accessible just when the session is authenticated, call the session service's requireAuthentication
method in the respective route'southward beforeModel
method:
// app/routes/authenticated.js import Route from '@ember/routing/route' ; import { inject as service } from '@ember/service' ; export default class AuthenticatedRoute extends Route { @service session ; beforeModel ( transition ) { this . session . requireAuthentication ( transition , 'login' ) ; } }
This volition make the road (and all of its subroutes) transition to the login
route if the session is not authenticated. Add together the login
route in the router similar this:
// app/router.js Router . map ( function ( ) { this . road ( 'login' ) ; } ) ;
It is recommended to nest all of an application's routes that require the session to exist authenticated under a mutual parent route:
// app/router.js Router . map ( part ( ) { this . road ( 'login' ) ; this . route ( 'authenticated' , { path: '' } , office ( ) { // all routes that require the session to be authenticated } ) ; } ) ;
To forestall a route from being accessed when the session is authenticated (which makes sense for login and registration routes for instance), call the session service'due south prohibitAuthentication
method in the respective road's beforeModel
method:
// app/routes/login.js import Route from '@ember/routing/road' ; import { inject as service } from '@ember/service' ; export default class LoginRoute extends Route { @service session ; beforeModel ( transition ) { this . get ( 'session' ) . prohibitAuthentication ( 'index' ) ; } }
The session service also provides the handleAuthentication
and handleInvalidation
methods for treatment authentication and invalidation of the session (which not only happens when the user submits the login class or clicks the logout push merely too when the session is authenticated or invalidated in some other tab or window of the application). The handleAuthentication
method will transition to a configurable route while the handleInvalidation
method will reload the page to articulate all potentially sensitive information from memory. In society to customize those behaviours, these methods can exist overridden when the application defines its ain session service that extends the 1 provided by Ember Simple Auth.
To add authorization information to requests, you can use the session service to check if the session is authenticated and access hallmark/dominance data, e.k. a token:
// app/adapters/awarding.js import JSONAPIAdapter from '@ember-data/adapter/json-api' ; import { computed } from '@ember/object' ; import { inject as service } from '@ember/service' ; export default class ApplicationAdapter extends JSONAPIAdapter { @service session ; @computed ( 'session.{data.authenticated.access_token,isAuthenticated}' ) get headers ( ) { let headers = { } ; if ( this . session . isAuthenticated ) { // OAuth 2 headers [ 'Say-so' ] = `Bearer ${ this . session . information . authenticated . access_token } ` ; } return headers ; } }
The Session Service
The session service is the main interface to the library. It defines the authenticate
, invalidate
and qualify
methods every bit well every bit the session events as shown higher up.
It also provides the isAuthenticated
every bit well equally the data
properties. The latter tin exist used to get and prepare the session data. While the special authenticated
section in the session data contains the data that was acquired by the authenticator when it authenticated the session and is read-simply, all other session data can be written and will also remain in the session after it is invalidated. It can exist used to store all kinds of client side information that needs to be persisted and synchronized across tabs and windows, e.one thousand.:
this . session . set ( 'information.locale' , 'de' ) ;
Authenticators
Authenticators implement the concrete steps necessary to authenticate the session. An application tin can leverage several authenticators for dissimilar kinds of authentication mechanisms (e.one thousand. the application's ain backend server, external authentication providers like Facebook etc.) while the session is merely ever authenticated with i authenticator at a time. The authenticator to use is called when hallmark is triggered via the name it is registered with in the Ember container:
this . session . cosign ( 'authenticator:some' ) ;
Ember Simple Auth comes with 4 authenticators:
-
OAuth2PasswordGrantAuthenticator
: an OAuth 2.0 authenticator that implements the "Resources Owner Password Credentials Grant Type" -
OAuth2ImplicitGrantAuthenticator
: an OAuth two.0 authenticator that implements the "Implicit Grant Type" -
DeviseAuthenticator
: an authenticator uniform with the popular Cherry on Rails authentication plugin devise -
ToriiAuthenticator
: an authenticator that wraps the torii library
To utilise any of these authenticators in an application, ascertain a new authenticator in app/authenticators
, extend if from the Ember Simple Auth authenticator
// app/authenticators/oauth2.js import OAuth2PasswordGrantAuthenticator from 'ember-simple-auth/authenticators/oauth2-countersign-grant' ; export default form OAuth2Authenticator extends OAuth2PasswordGrantAuthenticator { }
and invoke the session service's authenticate
method with the respective proper name, specifying more arguments as needed by the authenticator:
this . session . authenticate ( 'authenticator:some' , data ) ;
Customizing an Authenticator
Authenticators are easily customized past setting the respective properties, due east.one thousand.:
// app/authenticators/oauth2.js import OAuth2PasswordGrantAuthenticator from 'ember-unproblematic-auth/authenticators/oauth2-password-grant' ; consign default class OAuth2Authenticator extends OAuth2PasswordGrantAuthenticator { serverTokenEndpoint = '/custom/endpoint' ; }
Implementing a custom Authenticator
Besides extending one of the predefined authenticators, an application can likewise implement fully custom authenticators. In society to practise that, extend the abstract base authenticator that Ember Simple Auth comes with and override the authenticate
, restore
and (optionally) invalidate
methods:
// app/authenticators/custom.js import Base from 'ember-simple-auth/authenticators/base of operations' ; export default form CustomAuthenticator extends Base { restore ( data ) { … } authenticate ( options ) { … } invalidate ( information ) { … } }
Session Stores
Ember Simple Auth persists the session state via a session store so it survives page reloads. There is only ane store per application that can be defined in app/session-stores/awarding.js
:
// app/session-stores/application.js import Cookie from 'ember-simple-auth/session-stores/cookie' ; consign default class ApplicationSessionStore extends Cookie { }
If the awarding does not ascertain a session shop, the adaptive store which uses localStorage
if that is bachelor or a cookie if information technology is not, will be used past default. To customize the adaptive store, define a custom store in app/session-stores/awarding.js
that extends it and overrides the properties to customize.
Shop Types
Ember Elementary Auth comes with four stores:
Adaptive Store
The adaptive store stores its data in the browser'south localStorage
if that is bachelor or in a cookie if information technology is non; this is the default store.
localStorage
Shop
The localStorage
store stores its data in the browser's localStorage
. This is used by the adaptive shop if localStorage
is available.
Cookie Store
The Cookie store stores its data in a cookie. This is used by the adaptive store if localStorage
is non available. This shop must be used when the application uses FastBoot.
sessionStorage
Store
The sessionStorage
store stores its data in the browser'due south sessionStorage
. See the Web Storage docs for details on sessionStorage
and localStorage
. caniuse has upwardly-to-date information on browser support of sessionStorage
and localStorage
.
Ephemeral Store
The ephemeral store stores its data in memory and thus is non really persistent. This store is mainly useful for testing. Also the ephemeral store cannot keep multiple tabs or windows in sync as tabs/windows cannot share memory.
Customizing the Store
The session store is hands customized by setting the respective backdrop, e.g.:
// app/session-stores/application.js import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive' ; export default grade ApplicationSessionStore extends AdaptiveStore { cookieName = 'my-apps-session-cookie' ; }
Implementing a custom Store
Besides using ane of the predefined session stores, an awarding can besides implement fully custom stores. In order to practice that, extend the abstract base session store that Ember Unproblematic Auth comes with and implement the persist
, restore
and clear
methods:
// app/session-stores/awarding.js import Base from 'ember-simple-auth/session-stores/base' ; export default class ApplicationSessionStore extends Base of operations { persist ( ) { … } restore ( ) { … } }
FastBoot
Ember Simple Auth works with FastBoot out of the box every bit long as the Cookie session store is beingness used. In order to enable the cookie store, define it as the application store:
// app/session-stores/application.js import CookieStore from 'ember-elementary-auth/session-stores/cookie' ; export default grade ApplicationSessionStore extends CookieStore { }
If you are using the OAuth2PasswordGrantAuthenticator
, or DeviseAuthenticator
, you must add node-fetch
to your list of FastBoot whitelisted dependencies in package.json
:
{ "fastbootDependencies": [ "node-fetch" ] }
Engines
Ember Simple Auth works with engines out of the box. The host app and any engine(s) share the aforementioned session
service then they can synchronize the hallmark condition:
// my-engine/addon/routes/index.js import Application from '@ember/awarding' ; import loadInitializers from 'ember-load-initializers' ; form App extends Application { … engines = { 'my-engine': { dependencies: { services: [ 'session' ] } } } } ) ; … export default App ;
The session tin and so be authenticated or invalidated from the host app or whatever of the engines and the country will be synchronized via the service.
One thing to be enlightened of is that if the hallmark route is outside of the engine (e.g. in the host app), it is necessary to use the special transitionToExternal
method in the engine to transition to it. That can be washed by passing a callback instead of a route name to the session service'due south requireAuthentication
method in that instance:
// my-engine/addon/routes/index.js import Route from '@ember/routing/road' ; import { inject as service } from '@ember/service' ; consign default form IndexRoute extends Route { @service session ; beforeModel ( transition ) { this . get ( 'session' ) . requireAuthentication ( transition , ( ) => this . transitionToExternal ( 'login' ) ) ; } , }
Testing
Ember Simple Auth comes with a set up of test helpers that can be used in acceptance tests.
Our helpers use the more modern testing syntax and therefore crave ember-cli-qunit
4.two.0 or greater or ember-qunit
3.2.0 or greater.
We provide the post-obit helpers:
-
currentSession()
returns the current session. -
authenticateSession(sessionData)
authenticates the session asynchronously; the optionalsessionData
argument can be used to mock the response of an authentication request, to provide a specific authorisation token or user data. -
invalidateSession()
invalidates the session asynchronously.
Which can be used as shown in the following example:
import { module , test } from 'qunit' ; import { visit , currentURL } from '@ember/test-helpers' ; import { setupApplicationTest } from 'ember-qunit' ; import { currentSession , authenticateSession , invalidateSession } from 'ember-unproblematic-auth/examination-support' ; module ( 'Acceptance | app exam' , function ( hooks ) { setupApplicationTest ( hooks ) ; test ( '/login redirects to index if user is alread logged in' , async part ( assert ) { wait authenticateSession ( { authToken: '12345' , otherData: 'some-data' } ) ; wait visit ( '/login' ) ; affirm . equal ( currentURL ( ) , '/' ) ; permit sessionData = currentSession ( ) . get ( 'information.authenticated' ) ; assert . equal ( sessionData . authToken , '12345' ) ; assert . equal ( sessionData . otherData , 'some-information' ) ; } ) ; test ( '/protected redirects to /login if user is not logged in' , async role ( assert ) { await invalidateSession ( ) ; await visit ( '/protected' ) ; assert . equal ( currentURL ( ) , '/login' ) ; } ) ; } ) ;
If you're an ember-mocha
user, we can recommend to cheque out this case from the exam suite of ember-elementary-auth itself.
Other guides
- Managing current User
License
Ember Simple Auth is developed past and © simplabs GmbH and contributors. Information technology is released under the MIT License.
Ember Simple Auth is not an official part of Ember.js and is not maintained by the Ember.js Core Team.
How to Refresh Application Route After Login Ember
DOWNLOAD HERE
Source: https://www.npmjs.com/package/ember-simple-auth
Posted by: acknewstodayds.blogspot.com
comment 0 comments
more_vert