ember.js: Make AdminRouteMixin from AuthenticatedRouteMixin? - ember.js

Is there a more elegant way to prevent unauthorized access to an admin-only route than writing this in all of my admin routes?
export default Ember.Route.extend(AuthenticatedRouteMixin, {
beforeModel: function(){
if(!this.get('session.secure.admin')) this.transitionTo("dashboard");
}
});
Perhaps it's possible to extend AuthenticatedRouteMixin itself to make this kind of check?
Thanks!

Why not just make the mixin?
import Ember from 'ember';
import AuthenticatedRouteMixin from 'wherever/it/is'.
const { Mixin } = Ember;
export default Mixin.create(AuthenticatedRouteMixin, {
beforeModel(){
if(!this.get('session.secure.admin')) {
this.transitionTo("dashboard");
}
}
})
And then import it in your routes:
import Ember from 'ember';
import AdminCheckMixin from 'yourApp/mixins/routes/admin-check';
const { Route } = Ember;
export default Route.extend(AdminCheckMixin);

Related

How to pass Error Message to Route from a different Controller in Ember js

Let, I have two routes and two controllers namely login and signup
If I signup successfully then I want to perform transition to the route login with a success message as parameter,
/app/signup/controller.js
import Controller from '#ember/controller';
export default Controller.extend({
actions: {
signup: function(){
let _this = this;
let successMessage = 'successfully registered';
var credentials = this.getProperties('name','identification','password');
let list = this.store.createRecord('user', {
name: credentials.name,
email: credentials.identification,
password: credentials.password
});
list.save().then(function(){
_this.transitionToRoute('login','successMessage');
});
}
}
});
app/login/template.hbs
<body>
{{successMessage}}
</body>
/app/router.js
import EmberRouter from '#ember/routing/router';
import config from './config/environment';
const Router = EmberRouter.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('login');
this.route('signup');
});
export default Router;
I think you sort of have 3 options:
Use a route param (query param or positional)
Use a service to manage login stuff, and read some computed property from the service representing your state / message from your login controller
Use a flash/toast style UI where the message lives outside of the app view/component hierarchy
Personally, for where you want to display your message, I'd go for #2, which would look like this:
// app/services/user-session.js
import Service from '#ember/service';
export default class extends Service {
successMessage = null;
signup(name, id, password) {
// logic
this.set('successMessage', 'yay');
}
}
// app/controllers/signup.js
import Controller from '#ember/controller';
import { service } from '#ember-decorators/service';
import { action } from '#ember-decorators/object';
export default class extends Controller {
#service userSession;
#action
signup() {
this.userSession.signup(...);
this.transition...
}
}
// app/controllers/login.js
import Controller from '#ember/controller';
import { service } from '#ember-decorators/service';
import { readOnly } from '#ember-decorators/object/computed';
export default class extends Controller {
#service userSession;
#readOnly('userSession.successMessage') successMessage;
}
Or, in the old syntax:
// app/services/user-session.js
import Service from '#ember/service';
export default Service.extend({
successMessage: null,
signup(name, id, password) {
// logic
this.set('successMessage', 'yay');
}
});
// app/controllers/signup.js
import Controller from '#ember/controller';
import { inject as service } from '#ember/service';
export default Controller.extend({
userSession: service(),
actions: {
signup() {
this.userSession.signup(...);
this.transition...
}
}
});
// app/controllers/login.js
import Controller from '#ember/controller';
import { inject as service } from '#ember/service';
import { readOnly } from '#ember/object/computed';
export default Controller.extend({
userSession: service(),
successMessage: readOnly('userSession.successMessage')
});
hope this helps

Ember: Error while processing route. Can't hit API

This code works (hardcoded):
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
let stars = [
{
key: "johnlennon",
logoUrl: "https://www.images.com/johnl.png",
name: "John Lennon",
alive: false
}
}
}
});
When I do this, it doesn't (from API):
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import config from '../../../../../config/environment';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
const token = this.get('session.data.authenticated.token');
return Ember.RSVP.hash({
stars: Ember.$.getJSON(Ember.$.getJSON(`${config.APP.starsAPI}/api/stars?authorizationToken=${token}`))
});
}
});
The error I receive:
jquery.js:9175 GET
http://localhost:4242/stars/948/connect/[object%20Object] 404 (Not
Found)
ember.debug.js:30291 Error while processing route:
stars.show.connect.stars.index
As you may have guessed, I need it to work from API. Why is that giving me the error?
It worked after this change:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import config from '../../../../../config/environment';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
const token = this.get('session.data.authenticated.token');
return Ember.$.getJSON(`${config.APP.starsApi}/api/stars?authorizationToken=${token}`).then(function(retVal){
return retVal;
});
}
});
Looks like you had chained `Ember.$.getJSON() methods.
return Ember.$.getJSON(`${config.APP.starsApi}/api/stars?authorizationToken=${token}`).then(function(retVal){
return retVal;
});
This should work fine

torii facebook ember get user and name

Hi I want to get name and email from facebook authentication via torii and simple-auth, but I don't know how recovery this data. I can login via facebook but I can't get name or email.
Could you helpme please
This is my code:
//import Base from 'ember-simple-auth/authenticators/base';
import Ember from 'ember';
import ToriiAuthenticator from 'ember-simple-auth/authenticators/torii';
export default ToriiAuthenticator.extend({
torii: Ember.inject.service()
});
This is my component login-form
import Ember from 'ember';
export default Ember.Component.extend({
actions:{
facebookLogin(){
this.get('session').authenticate('authenticator:torii', 'facebook-oauth2').then((data)=>{
alert("logueado" + data);
});
}
}
});
And my torii-provider
// app/torii-providers/facebook.js
import FacebookOauth2Provider from 'torii/providers/facebook-oauth2';
export default FacebookOauth2Provider.extend({
fetch(data) {
return data;
}
});

Unit testing using ember-qunit controller action which access the store and methods

I have built a small Ember App. It has a controller which has an action named changeStatus(id). This method access the store and try to change an attribute value. I am relatively new to Ember. I don't know whether best way is to test it with Integration test or unit test? And how to test with either way.
Here is the sample code
Controller: user.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
changeStatus(id) {
const oUser = this.store.peekRecord('user', id),
let bCurrentValue = oUser.get('active');
if (bCurrentValue) {
oUser.set('active', false);
} else {
oUser.set('active', true);
}
//oUser.save();
},
}
});
Model: user.js
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default PatientIndexController;
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
active: attr('boolean'),
});
Unit Test: user-test.js
import {moduleFor, test} from 'ember-qunit';
import Ember from 'ember';
moduleFor('controller:user', 'Unit | Controller | user', { });
test('Toggle user active status', function (assert) {
const contollerUser = this.subject();
contollerUser.send('changeStatus', 1);
assert.equal(contollerUser.store.peekRecord('user', 1).get('active'), 'true or false');
});
but I am not getting how to set some data to store. As when I call the function changeStatus() then it don't know about user model.
How to set a proper test. Thanks in advance.

how to use another controller method in ember

im' trying to use a method which is in application.js, is these a controller.
it has a method called isAuthenticated which return if a user is login or not.
in my application.hbs it works fine,
but when i call it in my posts/new.hbs it always return false.
why it?
my application controller,
import Ember from 'ember';
import App from '../app';
export default Ember.Controller.extend({
authManager: App.AuthManager,
currentUser: function() {
return App.AuthManager.get('apiKey.user');
}.property('authManager.apiKey'),
isAuthenticated: function() {
return App.AuthManager.isAuthenticated();
}.property('authManager.apiKey'),
});
solutions?