<?php
require_once 'Sabai/Application/ControllerFilter.php';

class Plugg_User_Filter extends Sabai_Application_ControllerFilter
{
    public function before(Sabai_Application_Context $context, Sabai_Application $application)
    {
        if (!$context->user->isAuthenticated()) {
            return;
        }
        
        // Set identity data loader for lazy loading extra user data
        $identity_fetcher = $application->locator->getService('UserIdentityFetcher');
        $context->user->getIdentity()->setDataLoader(array($identity_fetcher, 'loadIdentityWithData'));
        
        if ($context->user->isSuperUser()) {
            return;
        }
        
        // Set permissions for the user
        $members = $application->pluginManager
            ->getPlugin('user')
            ->getModel()
            ->Member
            ->fetchByUser($context->user->getId())
            ->with('Role');
        foreach ($members as $member) {
            foreach ($member->Role->getPermissions() as $perm_name) {
                if ($member->Role->system) {
                    $context->user->setSuperUser(true);
                    return;
                }
                $context->user->addPermission($perm_name);
            }
        }
    }
    
    public function after(Sabai_Application_Context $context, Sabai_Application $application)
    {
    }
}