Приветствую. Я новичек в Symfony2 и мне требуется помощь с авторизацией, т.к. после рефакторинга она не работает. Я не знаю как это сделано в других проектах, но в том, с которым мне пришлось работать сделано следующим образом.
1) Модель User (от Propel), которая реализует UserInterface интерфейс.
2) AccountController со следующими методами (я показываю лишь два).
public function authenticationAction(Request $request)
{
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR);
$session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
}
$loginForm = $this->createForm(new AccountLoginType(), new AccountLogin(), [
'action' => $this->generateUrl('account_authorization')
])->handleRequest($request);
return $this->render('noxaeternaMainBundle:Account:login.html.twig', [
'loginForm' => $loginForm->createView(),
'error' => $error
]);
}
public function authorizationAction(Request $request) {
$loginForm = $this->createForm(new AccountLoginType(), new AccountLogin(), [
'action' => $this->generateUrl('account_authorization')
])->handleRequest($request);
if ($request->getMethod() === 'POST' && $loginForm->isValid()) {
$name = $loginForm->getData()->getName();
$user = UserQuery::create()->findOneByName($name);
if (is_null($user)) {
return $this->render('noxaeternaMainBundle:Account:login.html.twig', [
'loginForm' => $loginForm->createView(),
'error' => 'Пользователя с таким именем не существует.'
]);
}
$encryptionService = $this->get('encryption_service');
$passwordHash = $encryptionService->calculateMd5($encryptionService->encrypt(
$loginForm->getData()->getPassword(),
$user->getSalt()
));
if ($user->getPasswordHash() !== $passwordHash) {
return $this->render('noxaeternaMainBundle:Account:login.html.twig', [
'loginForm' => $loginForm->createView(),
'error' => 'Пароли не совпадают.'
]);
}
$sessionKey = new SessionKey();
$sessionKey->setUserId($user->getId())
->setKey(md5(uniqid($name, true)))
->setCreationTime(new \DateTime())
->setIsExpired($loginForm->getData()->getRememberMe() ? 1 : 0)
->save();
$response = new Response();
$response->headers->setCookie(new Cookie('NOXUID', $sessionKey->getKey()));
$response->send();
return $this->redirect($this->generateUrl('index'));
}
return $this->render('noxaeternaMainBundle:Account:login.html.twig', [
'loginForm' => $loginForm->createView()
]);
}
security:
encoders:
# Symfony\Component\Security\Core\User\User: plaintext
noxaeterna\MainBundle\Model\User:
id: encryption_service
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
main:
id: nox_user_provider
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/account/login$
security: false
secured_area:
pattern: ^/
form_login:
check_path: account_authentication
login_path: account_authorization
use_referer: true
logout:
path: account_logout
target: /
remember_me:
key: "%secret%"
lifetime: 31536000 # 365 days in seconds
path: ^/
domain: ~ # Defaults to the current domain from $_SERVER
anonymous: ~
#http_basic:
# realm: "Secured Demo Area"
access_control:
- { path: ^/account/login/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/profile/change/(password|name)/$, roles: IS_AUTHENTICATED_REMEMBERED }
- { path: ^/(blog|gallery|library)/add/, roles: IS_AUTHENTICATED_REMEMBERED }
- { path: ^/(blog|gallery|library)/(post|image|book)/\d+/edit/$, roles: IS_AUTHENTICATED_REMEMBERED }
- { path: ^/profile/$, roles: IS_AUTHENTICATED_REMEMBERED}
Заранее спасибо!