Symfony autorun function
I built a login system in Symfony. On every page that is secured I need to validate that the username matches the password. I wrote a function: isValidAuth()
in myUser.class.php. Nevertheless I need to write these lines in actions for every page:
if(!isValidAuth())
{
$t开发者_Go百科his->forward('home', 'logout');
}
which is quite inconvenient when you have multiple pages and modules that are secured. Is there any way I can run these lines like a function if the page is_secured
? Like when accessing executeIndex()
at page load?
There is a build in feature in Symfony which handle this. The manaual is for version 1.2 but it should also work for version 1.4: http://www.symfony-project.org/book/1_2/06-Inside-the-Controller-Layer.
since the config values in 1.4 have changed to true/false instead of on/off, you will have to change them: http://www.symfony-project.org/reference/1_4/en/08-Security
apps/frontend/modules/mymodule/config/security.yml
all:
is_secure: true # for all actions of a module
foo:
is_secure: false # action foo is public
in apps/frontend/config/settings.yml you will have to provide a module and action which does the login etc.
all:
.actions:
login_module: default
login_action: login
secure_module: default
secure_action: secure
And last but not least you need to setAuthenticated Flag on your User (usualy after the login ;) ):
$this->getUser()->setAuthenticated(true);
by the way. maybe you should install the sfdoctrineguardplugin which provides the user handling, login etc out of the box ;)
The best place for this would be the filterchain, I'd even suggest extending sfBasicSecurityFilter. To enable your extended class, edit apps/myapp/config/filters.yml
rendering: ~
security:
class: myExtendedSecurityFilter
# Generally, you will want to insert your own filters here
cache: ~
execution: ~
Instead of extending the sfBasicSecurityFilter, you could also create a new class that extends sfFilter. Read more about filters here:
http://www.symfony-project.org/gentle-introduction/1_4/en/06-Inside-the-Controller-Layer#chapter_06_filters
精彩评论