Ember-cli - Simple-Auth :: Location for factory authenticator:custom - ember.js

Where is the proper location for factory in ember-cli. Once I have the proper location for the factory, do I register in my initializer as such
container.register('authenticator:custom', application.CustomAuthenticator);
// the custom authenticator that authenticates the session against the custom server
App.CustomAuthenticator = Ember.SimpleAuth.Authenticators.Base.extend({
tokenEndpoint: '/v4/session',
restore: function(data) {
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(data.token)) {
resolve(data);
} else {
reject();
}
});
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'POST',
data: JSON.stringify({ session: { identification: credentials.identification, password: credentials.password } }),
contentType: 'application/json'
}).then(function(response) {
Ember.run(function() {
resolve({ token: response.session.token });
});
},
function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
},
invalidate: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve) {
Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
resolve();
});
});
},
});
Thanks!

Yes, that's how you do it. Make sure though to call container.register before you fall Ember.SimpleAuth.setup.

Related

How in ember-simple-auth change "username" in request body to _username and password to _password

I can change it inside module, but after "npm install" this changes are discarded
You should create your own authenticator like that one I have created to authenticate the user with my backend. I specified the fields that I want to send in my request in the "authenticate" function:
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import request from 'ic-ajax';
export default Base.extend({
tokenEndPoint: 'http://localhost:3000/api/sessions',
restore: function(data) {
return new Ember.RSVP.Promise(function(resolve, reject){
if(!Ember.isEmpty(data.token)) {
resolve(data);
} else {
reject();
}
});
},
authenticate: function(options) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: this.tokenEndPoint,
type: 'POST',
crossDomain: true,
data: JSON.stringify({
session: {
_email: options.session.email,
_password: options.session.password
}
}),
contentType: 'application/json'
// dataType: 'json'
}).then(function(response){
console.log('LOGIN OK: ' + response.auth_token);
Ember.run(function(){
resolve({
token: response.auth_token
});
});
}, function(xhr, status, error) {
console.log('LOGIN ERROR: ' + xhr.responseText);
var response = xhr.responseText;
Ember.run(function(){
reject(response);
});
});
});
},
invalidate: function() {
console.log('Invalidate Session....');
return Ember.RSVP.resolve();
}
});

ember-cli simple-auth custom authorization

i am trying to use ember-simple-auth with custom authentication and authorization: authenticator works but authorizer doesn't. Token successfully assigned but there is no injection in ajax calls.
app/authenticator/custom.js
import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
export default Base.extend({
tokenEndpoint: 'http://...',
restore: function(data) {
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(data.token)) {
resolve(data);
} else {
reject();
}
});
},
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 });
});
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
},
invalidate: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve) {
Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
resolve();
});
});
},
});
app/authorizers/custom.js
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
export default Base.extend({
authorize: function(jqXHR, requestOptions) {
if (this.get('session.isAuthenticated') && !Ember.isEmpty(this.get('session.secure.token'))) {
jqXHR.setRequestHeader('X-CSRFToken', this.get('session.secure.token'));
}
}
});
app/initializers/authentication.js
import CustomAuthenticator from 'app/authenticators/custom';
import CustomAuthorizer from 'app/authorizers/custom';
export default {
name: 'authentication',
before: 'simple-auth',
initialize: function(container) {
container.register('authenticator:custom', CustomAuthenticator);
container.register('authorizer:custom', CustomAuthorizer);
}
};
config/environment.js
ENV['simple-auth'] = {
authorizer: 'authorizer:custom',
crossOriginWhitelist: ['http://...']
};
app/controllers/login.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
authenticate: function(){
var credentials = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:custom', credentials);
}
}
});

Uncaught TypeError: Cannot read property 'login' of undefined

I'm trying to set up OAuth with Firebase and Ember. For some reason it's returning the error
Uncaught TypeError: Cannot read property 'login' of undefined
App.LoginController = Ember.ObjectController.extend({
actions: {
login: function() {
var controller = this;
debugger;
controller.get("session").login().then(function(user) {
// Persist your users details.
}, function() {
// User rejected authentication request
});
}
},
});
I was thinking maybe the user is undefined, but I've defined it in a model:
App.User = DS.Model.extend({
username: DS.attr('string'),
});
Then I thought maybe it's the "session" that's undefined--I used the debugger to look up & it says it's an unknown mixin.
var session = Ember.Object.extend({
ref: new Firebase("https://glowing-fire.firebaseio.com/"),
addFirebaseCallback: function() {
var session = this;
this.get("ref").onAuth(function(authData) {
if (authData) {
session.set("isAuthenticated", true);
} else {
session.set("isAuthenticated", false);
}
});
}.on("init"),
login: function() {
return new Promise(function(resolve, reject) {
this.get("ref").authWithOAuthPopup("facebook", function(error, user) {
if (user) {
resolve(user);
} else {
reject(error);
}
});
});
},
currentUser: function() {
return this.get("ref").getAuth();
}.property("isAuthenticated")
});
App.Session = Ember.Object.extend({
initialize: function(container, app) {
app.register("session:main", session);
app.inject("controller", "session", "session:main");
app.inject("route", "session", "session:main");
}
});
I'd really appreciate your help!
The issue might be that you are trying to access an injected property, but the code that does the injection is never called. The recommended way to inject properties is described on this page.
More specifically the samples below (from the Ember.js website) should help
Using an application initializer:
App = Ember.Application.extend();
App.Logger = Ember.Object.extend({
log: function(m) {
console.log(m);
}
});
App.IndexRoute = Ember.Route.extend({
activate: function(){
// The logger property is injected into all routes
this.logger.log('Entered the index route!');
}
});
Ember.Application.initializer({
name: 'logger',
initialize: function(container, application) {
application.register('logger:main', App.Logger);
application.inject('route', 'logger', 'logger:main');
}
});
App.create();
or directly on the application:
App = Ember.Application.create();
App.register('logger:main', {
log: function(m) {
console.log(m);
}
}, { instantiate: false });
App.inject('route', 'logger', 'logger:main');

Ember-simple-auth with laravel

I'm having trouble creating a custom authenticator for my laravel backend. I'm not sure if this is the correct custom authenticator for laravel, but I'm using this as a starting point (https://github.com/simplabs/ember-simple-auth/blob/master/examples/6-custom-server.html).
My Ember.SimpleAuth is undefined. Here is what I have in my app.js.
import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
Ember.MODEL_FACTORY_INJECTIONS = true;
window.ENV = window.ENV || {};
window.ENV['simple-auth'] = {
authorizer: 'authorizer:custom'
};
Ember.Application.initializer({
name: 'authentication',
before: 'simple-auth',
initialize: function(container, application) {
//register the laravel authenticator so the session can find it
container.register('authenticator:laravel', App.LaravelAuthenticator);
container.register('authorizer:custom', App.CustomAuthorizer);
}
});
var App = Ember.Application.extend({
modulePrefix: 'ember-simple-auth-sample', // TODO: loaded via config
Resolver: Resolver
});
App.LaravelAuthenticator = Ember.SimpleAuth.Authenticators.Base.extend({
tokenEndpoint: '/v4/session',
restore: function(data) {
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(data.token)) {
resolve(data);
} else {
reject();
}
});
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'POST',
data: JSON.stringify({ session: { identification: credentials.identification, password: credentials.password } }),
contentType: 'application/json'
}).then(function(response) {
Ember.run(function() {
resolve({ token: response.session.token });
});
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
},
invalidate: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve) {
Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
resolve();
});
});
}
});
// the custom authorizer that authorizes requests against the custom server
App.CustomAuthorizer = Ember.SimpleAuth.Authorizers.Base.extend({
authorize: function(jqXHR, requestOptions) {
if (this.get('session.isAuthenticated') && !Ember.isEmpty(this.get('session.token'))) {
jqXHR.setRequestHeader('Authorization', 'Token: ' + this.get('session.token'));
}
}
});
loadInitializers(App, 'ember-simple-auth-sample');
export default App;
Ember.SimpleAuth doesn't exist anymore, it now has it's own global SimpleAuth when you use the browserified distribution. It looks like you're using ember-cli though which means you're using the AMD distribution of Ember Simple Auth anyway which doesn't define any global at all. For instructions on how to use Ember Simple Auth with ember-cli see this blog post.
Apart from that your authenticator and authorizer look fine on first glance and should generally work that way.

Uncaught TypeError: Object #<Object> has no method 'set'

When i try set my 'content' to the customerList i'll get the error:
Uncaught TypeError: Object #Object has no method 'set'
Here is my code:
App.TableController = Em.ArrayController.extend({
init: function() {
this._super();
this.getData();
},
getData: function() {
$.get('data/customer.json', function(data) {
var customerList = Ember.A([]);
data.forEach(function(item) {
var customer = App.overv.create({
incidient: item.incidient,
customer: item.customer,
machine: item.machine,
priority: item.priority
});
customerList.pushObject(customer);
});
this.set('content', customerList);
});
}});
I I also tried it with App.router.tableController.set('content',customerList) but ember doesn't recognize the controller anymore. With 1.0.0 pre 2 this second example worked great.
Now i try to figure out what i did wrong or probably understood wrong.
Keep a reference of this in a local variable _self. See code below.
App.TableController = Em.ArrayController.extend({
init: function() {
this._super();
this.getData();
},
getData: function() {
var _self = this;
$.get('data/customer.json', function(data) {
var customerList = Ember.A([]);
data.forEach(function(item) {
var customer = App.overv.create({
incidient: item.incidient,
customer: item.customer,
machine: item.machine,
priority: item.priority
});
customerList.pushObject(customer);
});
_self.set('content', customerList);
});
}});
probably just an issue with the context of the AJAX callback... you could try this:
App.TableController = Em.ArrayController.extend({
init: function() {
this._super();
this.getData();
},
getData: function() {
$.ajax({
url: 'data/customer.json',
dataType: 'json',
context: this
}).success(function(data, textStatus, jqXHR) {
var customerList = Ember.A([]);
data.forEach(function(item) {
var customer = App.overv.create({
incidient: item.incidient,
customer: item.customer,
machine: item.machine,
priority: item.priority
});
customerList.pushObject(customer);
});
this.set('content', customerList);
});
}
});
specifying TableController as the context to the callback.