Symfony 筆記 (6): User Login & Access Restriction
Posted in Symfony | By tarotoast | Tags: access, credential, login, note, php, restriction, symfony
雖然說其實翻翻文件就知道要改哪裡,在這邊記錄下來也只是方便自己不用再回去翻。其實在 Symfony 裡面要實作 Access Restriction (存取限制?) 很簡單,真的只是改 2 個 yml 檔案而已:
- apps/myapp/modules/mymodule/config/security.yml
- apps/myapp/config/settings.yml
apps/myapp/modules/mymodule/config/security.yml 定義著每個 module 下面 action 的存取限制。如果 is_secure = on 的話那就必須要有被認證過 (在 action 下面被 $this->getUser()->setAuthenticated(true);) 才能存取,不然的話依照另一個檔案的設定會被導到預設的 login page。
如果有設定 credentials 的話那除了必須要 authenticated 以外還得有被 addCrendential 過才行。
read: is_secure: off # All users can request the read action update: is_secure: on # The update action is only for authenticated users delete: is_secure: on # Only for authenticated users credentials: admin # With the admin credential all: is_secure: off # off is the default value anyway
apps/myapp/config/settings.yml 可以設定預設的 login module 和 action
all:
.actions:
login_module: default
login_action: login
secure_module: default
secure_action: secure
簡易的登入登出會是像這樣子
class myAccountActions extends sfActions
{
public function executeLogin()
{
if ($this->getRequestParameter('login') == 'foobar')
{
$this->getUser()->setAuthenticated(true);
}
}
public function executeLogout()
{
if ($this->getUser()->isAuthenticated())
{
$this->getUser()->setAuthenticated(false);
}
}
}
然後有關 Credential 的 Demo:
class myAccountActions extends sfActions
{
public function executeDoThingsWithCredentials()
{
$user = $this->getUser();
// Add one or more credentials
$user->addCredential('foo');
$user->addCredentials('foo', 'bar');
// Check if the user has a credential
echo $user->hasCredential('foo'); => true
// Check if the user has both credentials
echo $user->hasCredential(array('foo', 'bar')); => true
// Check if the user has one of the credentials
echo $user->hasCredential(array('foo', 'bar'), false); => true
// Remove a credential
$user->removeCredential('foo');
echo $user->hasCredential('foo'); => false
// Remove all credentials (useful in the logout process)
$user->clearCredentials();
echo $user->hasCredential('bar'); => false
}
}
最後是在 template 裡面要知道 credential 也是透過 $sf_user 這個看過才知道的物件。
<ul>
<li><?php echo link_to('section1', 'content/section1') ?></li>
<li><?php echo link_to('section2', 'content/section2') ?></li>
<?php if ($sf_user->hasCredential('section3')): ?>
<li><?php echo link_to('section3', 'content/section3') ?></li>
<?php endif; ?>
</ul>
Tags: access, credential, login, note, php, restriction, symfony
Recent Comments