How Do I check Permissions from Controller?

Mikey

Well-known member
I've searched the Development Questions / Development Tutorials forums, and all I've found is posts which say I should check permissions from the Model..

My Add on doesn't have a Model for the simple reason that it doesn't need one. I need to check if the user is an admin from the controller. I don't know how to do this..

Going back to the model thing, I suppose I could call from the User Model to check permissions from there with XenForo_Permission:: - but I'm still unsure of the general route I should be taking from there, could anyone help me out by shedding some light?

Thanks :D


 
They do this in the controller for the SpamCleaner.
Code:
if (!XenForo_Visitor::getInstance()->hasPermission('general', 'cleanSpam'))

I'm learning xF as we speak, so that may not be what you're after.
 
Okay, it was

PHP:
if (XenForo_Visitor::getInstance()->hasAdminPermission('option'))

which I was looking for.

Thanks for setting me on the right track, Martin! I should have looked in /XenForo/Visitor.php to begin with.
 
Strictly speaking you're kinda breaking MVC principles by checking permissions in the controller rather than handing it off to a model.

It's always possible to say that a controller doesn't need a model for its interactions, but by taking that route you seriously limit the extensibility of your code (don't forget that there is no reason why an add-on could not be an add-on for another add-on, rather than the XenForo core) and potentially make future maintenance more difficult.

XenForo is built on a principle of small and light controllers with heavy models, and all the caching mechanisms are set up with that idea in mind, so I'd recommend creating a model even if it contains only a couple of methods.

All that said, so long as your code works, there's no real problem :)
 
Strictly speaking you're kinda breaking MVC principles by checking permissions in the controller rather than handing it off to a model.
I agree, BUT you should mention that there are some scenarios, where it's better to check direct in the controller (for example if the whole controller is only for admins, the coder should use the _preDispatch() method...)
PHP:
class Ragtek_HSBB_ControllerPublic_Edit extends XenForo_ControllerPublic_Abstract
{

    public function _preDispatch($action)
    {
        if (!XenForo_Visitor::getInstance()->hasAdminPermission('option')) {
            throw $this->responseException($this->responseNoPermission());
        }
    }

    public function actionEdit()
    {

Here are "many" coders which started coding and now they do only the things people write here, even it's not the best way^^
 
thanks for the insights Kier and Ragtek, I'll revisit my code later to see if I can either add a _preDispatch action, or a model. :) After all, I want it to conform to XenForo standards :D
 
Top Bottom