ReferenceError: Can't find variable: authenticator Ember js Error - ember.js

I got an error ReferenceError: Can't find variable: authenticator Ember error in browser console and authenticator is not defined in terminal with this code
import Controller from '#ember/controller';
import { inject } from '#ember/service';
export default Controller.extend({
session: inject('session'),
actions: {
authenticate: function(){
var credentials = this.getProperties('username','password');
authenticator = 'authenticator:jwt';
this.get('session').authenticate(authenticator,credentials).catch((reason) => {
this.set('errorMessage', reason.error || reason);
});
}
}
});

As #jelhan said in the comments, you need to declare the variable authenticator by using let. This is a requirement of JavaScript and not anything specific to Ember.
Example:
import Controller from '#ember/controller';
import { inject } from '#ember/service';
export default Controller.extend({
session: inject('session'),
actions: {
authenticate: function(){
var credentials = this.getProperties('username','password');
let authenticator = 'authenticator:jwt';
this.get('session').authenticate(authenticator,credentials).catch((reason) => {
this.set('errorMessage', reason.error || reason);
});
}
}
});

Related

Can i access ember service variables in my whole application?

I Created an ember service and i initialized its value now i updated that value in a controller. I want this updated variable in my complete application ? What should i supposed to do. Any help will be appreciated. Thanks
Just dummy example
Service
// header.js
import Service from '#ember/service';
export default Service.extend({
currentRoute: null
});
Route
import Route from '#ember/routing/route';
import { inject as service } from '#ember/service';
import { set } from '#ember/object';
export default Route.extend({
header: service(),
beforeModel() {
set(this, 'header.currentRoute', 'login');
}
});
Any controller
import Controller from '#ember/controller';
import { computed, get } from '#ember/object';
import { inject as service } from '#ember/service';
export default Controller.extend({
header: service(),
currentRoute: computed('header.currentRoute', function() {
return get(this, 'header.currentRoute');
})
});
I hope you understood the idea
Please look at this article from the ember guide https://guides.emberjs.com/release/components/triggering-changes-with-actions/#toc_invoking-actions-directly-on-component-collaborators
You did the correct thing, once you already set an updated value of that variable in your service that value will be the same until you instructed your code to change the value of that variable. To answer your question, Can i access ember service variables in my whole application? Yes you can, you can do the following to access the variable into your application.
Assuming that this is your variable and service name
//services/current-session.js
import Service from '#ember/service';
export default Service.extend({
foo: 'foo bar baz',
});
If you want to access it in your controller please do the following
import Controller from '#ember/controller';
import { computed } from '#ember/object';
import { inject as injectService } from '#ember/service';
export default Controller.extend({
currentSession: injectService(),
bar: computed('currentSession.foo', function() {
return this.currentSession.foo;
}),
});
If you want to access it in your component
import Component from '#ember/component';
import { computed } from '#ember/object';
import { inject as injectService } from '#ember/service';
export default Component.extend({
currentSession: injectService(),
bar: computed('currentSession.foo', function() {
return this.currentSession.foo;
}),
});
The approach above is based on ember-cli 3.4 Here's an ember-twiddle you can play around. https://ember-twiddle.com/b92a7d4fa03a1699a5b8a79aca5d2782?openFiles=controllers.application.js%2C
If you want to change the value of your variable in your service through your controller you can do this
import Controller from '#ember/controller';
import { set } from '#ember/object';
import { inject as injectService } from '#ember/service';
export default Controller.extend({
currentSession: injectService(),
actions: {
change() {
this.currentSession.set('foo', 'foo bar baz please');
}
}
});
working twiddle.
Steps:
1) create a service:
app/services/service-name.js
import Service from '#ember/service';
export default Service.extend({
name: "hello",
changeName(name) {
this.set('name', name);
}
});
2) Create an initializer so you need not to inject the service in every route/controller/component.
app/initializers/inject-service-name.js
export function initialize(application) {
application.inject('controller', 'serviceName', 'service:service-name');
// if needed
// application.inject('route', 'serviceName', 'service:service-name');
// application.inject('component', 'serviceName', 'service:service-name');
}
export default {
initialize
};
once initializer is created kindly restart your ember server.
3) Usage:
app/controller/application.js
import Controller from '#ember/controller';
export default Controller.extend({
init() {
this._super(...arguments);
// print initial value
console.log(this.get('serviceName').name); // hello
// change value of name property in service
this.get('serviceName').changeName("hai");
// print changed value
console.log(this.get('serviceName').name); // hai
}
});

ember-simple-auth overriding sessionAuthenticated

Folks,
I've been trying to get ESA to redirect to specific pages after login and logout events without success.
I'm trying to do this by overriding the "sessionAuthenticated" method, but have also tried setting the "routeAfterConfiguration" setting with no luck.
At the moment, login sends me to "/", and logout sends the app to "/undefined".
I'm using simple-auth-token as a JWT authenticator strategy.
The code for my application route looks like this...
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin,{
actions: {
sessionAuthenticated: function() {
console.log('sessionAuthenticated: authentications ok');
window.location.replace('/profile');
},
},
});
My login.js is as follows:
import Ember from 'ember';
const {service} = Ember.inject;
export default Ember.Route.extend({
session: service('session'),
errorMessage: null,
model: function(){
return Ember.Object.create({
identification:'',
password: '',
errorMessage: this.get('errorMessage')
});
},
setupController: function(controller, model) {
controller.set('credentials',model);
},
actions: {
authenticate: function(credentials) {
console.log(credentials);
this.get('session').authenticate('simple-auth-authenticator:jwt', credentials)
.catch((reason) => {
console.log('Login Error');
credentials.set('errorMessage', reason);
});
},
},
});
Does anyone have any idea what I might be doing wrong here?
Cheers,
Andy
OK. Found the problem. These are not actions - they're methods. So I just had to promote the methods out of the actions object and it's all come good.
So the correct routes/application.js looks like this:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin,{
sessionAuthenticated: function() {
console.log('sessionAuthenticated: authentications ok');
window.location.replace('/profile');
},
});

Ember simple auth Session not getting authenticated after calling resolve in custom authenticator

My authenticators/custom.js:
import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
export default Base.extend({
restore: function(data) {
},
authenticate: function(email, password, authenticateCallback) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
type: 'POST',
url: apiOrigin + '/api/v1/login',
data: {
email: email,
password: password
},
dataType: 'json'
}).then(function(userData){
console.log('login post success', userData)
authenticateCallback(userData)
Ember.run(function() {
resolve(userData.uuid)
})
})['catch'](function(main){
alert('login error ' + JSON.stringify(main))
console.error('\'caught\' error from login post request', arguments);
})
})
},
invalidate: function(data) {
}
});
And login/controller.js:
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
application: Ember.inject.controller(),
actions: {
authenticate() {
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:custom', identification, password, (userData) => {
//TODO set these properties on ember-simple-auth's session object instead of application controller
this.get('application').setProperties(userData)
this.transitionToRoute('associate-device')
}).catch((reason) => {
this.set('errorMessage', reason.error);
})
}
}
});
My associate-device route is an AuthenticatedRoute.. I don't get an error, but instead, the last thing printed to the console is "Preparing to transition from 'login' to 'associate-device'"
Basically, ember simple auth documents here http://ember-simple-auth.com/api/classes/BaseAuthenticator.html#method_authenticate that "A resolving promise will result in the session becoming authenticated. Any data the promise resolves with will be saved in and accessible via the session service's data.authenticated property (see data). A rejecting promise indicates that authentication failed and will result in the session remaining unauthenticated."
However, my session does not seem to be authenticated after I successfully resolve my promise.
$.ajax has no catch method. This exception was hidden because I was copy-pasting away from the documentation for writing custom authenticators. To expose any exceptions occurring in your custom authenticators authenticate method, you should probably console.log them like so:
// app/controllers/login.js
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
actions: {
authenticate() {
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:oauth2', identification, password).catch((reason) => {
// **CHANGE THE BELOW LINE**
console.error('exception in your authenticators authenticate method', reason)
});
}
}
});

Ember-simple-auth custom authorizer not called

I'm trying to implement custom auth with ember-simple-auth and I stuck at the start. I have app/autheticators/digest.js
import Base from 'ember-simple-auth/authenticators/base';
import Ember from 'ember';
export default Base.extend({
restore(data) {
//
},
authenticate(email, password) {
console.log(email, password);
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.run(function() {
resolve({email: email, password: password});
});
});
},
invalidate(data) {
//
}
});
app/authorizers/digest.js
import Base from 'simple-auth/authorizers/base';
import Ember from 'ember';
export default Base.extend({
header: function() {
return "test-digest";
},
authorize: function(sessionData, block) {
console.log('authorize...');
block('Authorization', this.get('header'));
}
});
Login component:
import Ember from 'ember';
import CryptoJS from 'npm:crypto-js';
export default Ember.Component.extend({
session: Ember.inject.service('session'),
actions: {
login() {
let { email, password } = this.getProperties('email', 'password');
this.get("session").authenticate('autheticator:digest',
email, CryptoJS.SHA256(password).toString()).catch((reason) => {
this.set('errorMessage', reason.error);
});
}
}
});
Authentication called properly (I hope), but "authorize" in authorizer never called. I also tried add some values to ENV:
ENV['simple-auth'] = {
authorizer: 'authorizer:digest',
crossOriginWhitelist: ['http://prod-drunkedguru.rhcloud.com:80/'] // ['*'] I also tried
};
But nothing changed. What I'm doing wrong?
P.S. I'm using EmberJS 1.13.0 with EAS 1.0.
I assume you're using ESA 1.0. In that version the authorizer isn't automatically called anymore but you need to call it manually. There is the DataAdapterMixin that you can use to automatically authorizer Ember Data requests though. See this blog post for guidance on migrating to 1.0: http://log.simplabs.com/post/131698328145/updating-to-ember-simple-auth-10

Ember-cli-simple auth and ember-cli-simple-auth-torii how to make them work together

I am little confused on how to use ember-simple-auth with torii
I am using ember-cli-simple-auth and ember-cli-simple-auth-torii
i am getting below mentioned error
dont know waht i am missing
Uncaught Error: Assertion Failed: No application initializer named 'torii'
routes.js
Router.map(function() {
this.route('login');
this.route('application');
this.route('protected');
});
app/routes/application.js
import Ember from 'ember';
import ApplicatonRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicatonRouteMixin);
app/route/login
import Ember from 'ember';
export
default Ember.Route.extend({
actions: {
// action to trigger authentication with Facebook
authenticateWithFacebook: function () {
this.get('session').authenticate('simple-auth-authenticator:torii', 'facebook-oauth2');
}
}
});
app/routes/protected
import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend( AuthenticatedRouteMixin);
app/initializers/torii-initializer.js
import ToriiAuthenticator from 'simple-auth-torii/authenticators/torii';
export default Ember.Application.initializer({
name: 'authentication',
initialize: function(container, application) {
// register the Torii authenticator so the session can find them
container.register('simple-auth-authenticator:torii', ToriiAuthenticator);
Ember.SimpleAuth.setup(container, application);
}
});
index.html
window.AuthENV = {
{
ENV
}
};
window.EmberENV = window.AuthENV.EmberENV;
window.ENV = window.ENV || {};
window.ENV['torii'] = {
providers: {
'facebook-oauth2': {
apiKey: '63125ss',
redirectUri: document.location.href
}
}
};
login template
<h1>Login</h1>
<a {{action "authenticateWithFacebook"}}> login</a>
You need to install the torii Ember CLI Addon as well as that's currently not automatically included when you install ember-cli-simple-auth-torii:
npm install --save-dev torii