Apply global scope based on user role in Laravel 5.5 - laravel-5.5

For some model, I need to apply a global scope if the logged in user is not super admin. In model's boot() method I tried something like this:
<?php
namespace App;
use Auth;
use App\Scopes\RoleScope;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
protected static function boot()
{
parent::boot();
if( Auth::check() && ! Auth::user()->isSuperAdmin() ){
static::addGlobalScope(new RoleScope);
}
}
}
The scop never applied! What did I do wrong here? How can I achieve the goal to apply the scope based on the user role? thanks

You cannot access the currently authenticated user in the boot method of the Eloquent model - the Auth middleware hasn't run yet at this point.
What you should do is to perform the super admin check within the apply method of your RoleScope.

Related

How to retrieve the same model from another REST url in EmberJS

The models tree of my emberJS app match the tree of my API however, I have 2 different routes returning the same type of data :
/products/ and /users/:id/supported_products/ both return products data.
When I need to have the products of the app there is no problem :
this.store.query('product',params);
However I am not sure how to query products from the user path. The place to do so would be the adapter, but I need to define a secondary adapter that I would call when I need supported products,and I have no idea how to do so.
I think if it were me I would create a virtual query parameter that would instruct a custom adapter on how to change the endpoint on the fly.
For example I might have a supportedByUser flag. Then in my app/adapters/product.js do something like this:
import JSONAPIAdapter from 'ember-data/adapters/json-api';
export default JSONAPIAdapter.extend({
urlForQuery(query, modelName) {
let userId = query.supportedByUser;
delete query.supportedByUser;
return userId
? `${this.namespace || ''}/users/${userId}/supported_products`
: this._super(...arguments);
}
});
Here is an example twiddle demoing this: https://ember-twiddle.com/b406391e98ed4fda30bc227a894fa7c9

Find the class name of a relation from the instance of a model in ember JS

I have foo an instance of the ember-data model thing. thing.js has the following property :
owner: DS.belongsTo('user')
If I have foo with an empty owner, how can I, with only foo and the 'owner' string, retrieve the value 'user' representing the model of the owner relation?
EDIT: I want to allow my select-relation component to works with relations where the name is different from the class name
It sounds like you have some work to do to finish setting up your relationships. Have a read through this page of the guides.
If the relationships are set up correctly, to get the associated user, you should be able to do foo.owner. This assumes that users are already present in the store. I recommend using the Ember Inspector browser plugin to debug the relationships.
This looks like a use case for typeForRelationship.
In your example you should be able to do something like
store.modelFor('thing').typeForRelationship('owner', store);
If you don't like that approach you can use the belongsTo reference API, where you use the meta data from the relationship to get the type
foo.belongsTo('owner').type
The only thing with that approach is that the type property may not be public API and possible (though unlikely) to change at some point.
It seems I can do the following :
this.get('model').get('_internalModel._relationships.initializedRelationships.'+this.get('relation')+'.relationshipMeta.type')
model being an instance and relation the string of the relation name, it correctly return the model of the relation.
EDIT : a better solution not using private API courtesy from the ember discord :
function getRelatedModelName(record, relationName){
let ParentModelClass = record.constructor;
let meta = get(ParentModelClass, 'relationshipsByName').get(relationName);
return meta.type;
}

Adapter that converges two API sources into one model

Let's say I have a JSON API where I can access two models: cats and dogs. However, on my Ember application I only have one model: animals.
Although every time I save() an animal, it's POSTed to the API as a cat, if I receive a dog linked in any other model it should be locally stored as an animal by ember-data.
What would be the most coherent way to achieve this? Thank you!
Fixed. For future reference, it is possible to create an alias to a model, extending the ApplicationSerializer (in this case, our model is animal, and although it had an adapter that used the cat model in the API, the dog model needed to be parsed as an animal as well):
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({
typeForRoot: function(root) {
if (root == 'dog' || root == 'dogs') { root = 'animal'; }
return this._super(root);
}
);
You should be able to achieve what you want by customizing the REST adapter. Specifically, look into overriding the buildURL method to detect the type of the record passed and to construct the URL to be passed based on logic that determines whether this particular model should be persisted to the cats endpoint or dogs endpoint.

Ember Data: How to access model values after find()

How can I access the data from a model after a find() method?
In Ember-Data 1-0-Beta I can request data from my API via user = this.store.find('user',1) but how can I get the username of the user for example? Older tutorials achieves this with user.username' or user.get('username') but it seems to be that this doesn't work anymore?
I created a fiddle: http://jsfiddle.net/3zGsC/4/ (line 21/22)
After submitting the form the username should be written to the console, but its undefined.
Basically problem is that you are trying to access properties before model is resolved. You can use then method to wait for model resolution
here is a fiddle: http://jsfiddle.net/3zGsC/5/
this.store.find('user', 1).then(
function(resolveduser) {
console.log(resolveduser.get('username')+' from then');
}
);

Using Zend_Auth in Pimcore

Im new to Pimcore and I'm trying to use Zend Auth with pimcore objects. I assume this is a wise approach and it seems more or less logical to me. I've done the initial setup of the object within pimcore itself. Now I'm trying to work out how to connect it to zend auth, that is, for example when I extend zend auth and have my own login function, how do i check if the login is valid in my object?
Does someone have a guide that I could use on this perhaps? otherwise if someone could point me in the right direction that would be great
Jason
You can follow this guide: http://www.pimcore.org/forum/discussion/419/zend_auth_adapter-for-pimcore-objects , it worked well for me.
UPDATE: The link above has been taken away, so laying out the full answer here:
First, you need to put ObjectAdapter.php in website/lib/Website/Auth/ObjectAdapter.php .
Then, this is how you login your user (use as you prefer, for example in your controller init function):
$authAdapter = new Website_Auth_ObjectAdapter('Object_Users', 'o_key', 'password', '/users/');
// The parameters are 1. object you keep your users in, 2. the field that contains their username (I use o_key which is the name of the object itself, to keep unique usernames without fuzz), and 3. the password field in the user object.
// Setup auth adapter
$authAdapter->setIdentity($username)->setCredential($password);
$auth = Zend_Auth::getInstance();
// Authenticate
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// Login successful
} else {
// Login failed
}
To check for a login-session, use:
$this->auth = Zend_Auth::getInstance();
if ($this->auth->hasIdentity()) {
// We have a login session (user is logged in)
$userObject = $this->auth->getIdentity();
}
To kill a session:
Zend_Auth::getInstance()->clearIdentity();