在此函数中onAuthenticationSuccess我有以下代码来检查用户是否具有特定角色,然后我尝试将他重定向到正确的路径,但它似乎不起作用,还有另一种方法吗?
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
// Redirecten afhankkelijk van de user role:
$user = $token->getUser();
if (in_array("ROLE_GAST", $user->getRoles(), true)) {
return new RedirectResponse($this->urlGenerator->generate('gast_profile'));
}
else if (in_array("ROLE_MEDEWERKER", $user->getRoles(), true)){
return new RedirectResponse($this->urlGenerator->generate('app_medewerker'));
}
else if (in_array("ROLE_ADMIN", $user->getRoles())){
return new RedirectResponse($this->urlGenerator->generate('app_admin'));
}
// For example:
return new RedirectResponse($this->urlGenerator->generate('app_home'));
// throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
我试过这个: 转换为字符串错误
我一直走到实体,我添加了这个:
public function __toString() {
return $this->name;
}
不要像这样用 in_array 检查角色
$hasAccess = in_array('ROLE_ADMIN', $user->getRoles());
查看手册
https://symfony.com/doc/5.4/security.html#roles
如您所见,最佳做法是像这样在安全配置中定义角色
// config/packages/security.yaml
security:
# ...
role_hierarchy:
ROLE_INSTRUCTOR: ROLE_USER
ROLE_MEMBER: ROLE_USER
ROLE_ADMIN: [ROLE_INSTRUCTOR, ROLE_MEMBER]
然后你可以这样查看角色
$hasAccess = $this->isGranted('ROLE_ADMIN');
$this->denyAccessUnlessGranted('ROLE_ADMIN');
然后我们将创建一个用户类,通过使用make:user 命令——这个命令将创建一个安全的用户类,它会自动更新security.yaml.
遵循以下步骤:
php bin/console make:user
The name of the security user class (e.g. User) [User]:
>
Do you want to store user data in the database (via Doctrine)? (yes/no) [yes]:
>
Enter a property name that will be the unique "display" name for the user (e.g. email, username, uuid) [email]:
>
Will this app need to hash/check user passwords? Choose No if passwords are not needed or will be checked/hashed by some other system (e.g. a single sign-on server).
Does this app need to hash/check user passwords? (yes/no) [yes]:
>
created: src/Entity/User.php
created: src/Repository/UserRepository.php
updated: src/Entity/User.php
updated: config/packages/security.yaml
Success!
Next Steps:
- Review your new App\Entity\User class.
- Use make:entity to add more fields to your User entity and then run make:migration.
- Create a way to authenticate! See https://symfony.com/doc/current/security.html
然后我们就创建一个迁移文件,然后进行迁移:
执行此命令创建迁移文件:
php bin/console make:migration
php bin/console doctrine:migrations:migrate
要在 Symfony 5 上创建登录,我们可以使用 make:auth 命令——根据您的选择,此命令可以提供空验证器或完整的登录表单验证过程。
执行此命令并按照以下步骤操作: php bin/console make:auth
What style of authentication do you want? [Empty authenticator]:
[0] Empty authenticator
[1] Login form authenticator
> 1
1
The class name of the authenticator to create (e.g. AppCustomAuthenticator):
> AppCustomAuthenticator
Choose a name for the controller class (e.g. SecurityController) [SecurityController]:
>
Do you want to generate a '/logout' URL? (yes/no) [yes]:
>
created: src/Security/AppCustomAuthenticator.php
updated: config/packages/security.yaml
created: src/Controller/SecurityController.php
created: templates/security/login.html.twig
Success!
Next:
- Customize your new authenticator.
- Finish the redirect "TODO" in the App\Security\AppCustomAuthenticator::onAuthenticationSuccess() method.
- Check the user's password in App\Security\AppCustomAuthenticator::checkCredentials().
- Review & adapt the login template: templates/security/login.html.twig.
完成上述步骤后,打开文件‘src\Security\AppCustomAuthenticator.php’并更新部分代码:
src\Security\AppCustomAuthenticator.php
改变它:
see manage roles
创建登录后,我们将创建注册。我们可以使用make:registration 命令。
执行此命令并按照以下步骤操作:
php bin/console make:registration
Creating a registration form for App\Entity\User
Do you want to add a @UniqueEntity validation annotation on your User class to make sure duplicate accounts aren't created? (yes/no) [yes]:
>
Do you want to send an email to verify the user's email address after registration? (yes/no) [yes]:
> no
Do you want to automatically authenticate the user after registration? (yes/no) [yes]:
>
! [NOTE] No Guard authenticators found - so your user won't be automatically authenticated after registering.
What route should the user be redirected to after registration?:
[0 ] _wdt
[1 ] _profiler_home
[2 ] _profiler_search
[3 ] _profiler_search_bar
[4 ] _profiler_phpinfo
[5 ] _profiler_search_results
[6 ] _profiler_open_file
[7 ] _profiler
[8 ] _profiler_router
[9 ] _profiler_exception
[10] _profiler_exception_css
[11] dashboard
[12] app_login
[13] app_logout
[14] _preview_error
> 11
11
updated: src/Entity/User.php
created: src/Form/RegistrationFormType.php
created: src/Controller/RegistrationController.php
created: templates/registration/register.html.twig
Success!
Next:
Make any changes you need to the form, controller & template.
Then open your browser, go to "/register" and enjoy your new form!
请参阅此链接中的源文档: [https://www.binaryboxtuts.com/php-tutorials/how-to-make-a-user-login-and-register-in-symfony-5/][1]
在授权之后去:
app\src\Controller\RegistrationController.php
并添加:
$user->setRoles(['ROLE_MEMBER']);
以上:
$user->setRoles(['ROLE_MEMBER']);
$entityManager->persist($user);
$entityManager->flush();
接下来去:
App\Security\LoginAuthenticator::onAuthenticationSuccess() method.
并更改待办事项:
这里是 om te redirecten afjankelijk van de role 的代码:
//get the user
$user = $token->getUser();
if (in_array("ROLE_INSTRUCTOR", $user->getRoles(), true)) {
return new RedirectResponse($this->urlGenerator->generate('app_instructor'));
}
else if (in_array("ROLE_MEMBER", $user->getRoles(), true)){
return new RedirectResponse($this->urlGenerator->generate('app_member'));
}
else if (in_array("ROLE_ADMIN", $user->getRoles())){
return new RedirectResponse($this->urlGenerator->generate('app_admin'));
}
// For example:
return new RedirectResponse($this->urlGenerator->generate('app_bezoeker'));
// throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
```
[1]: https://www.binaryboxtuts.com/php-tutorials/how-to-make-a-user-login-and-register-in-symfony-5/
Hier 是显示用户信息的方式:
#[Route('/gast/profile', name: 'gast_profile')]
public function index(UserRepository $userRepository,): Response
{
$title = "Profile";
return $this->render('gast/profile.html.twig', [
'title' => $title,
]);
}
show it in the twig with just:
app.user
app.user.name
etc..
// edit user
#[Route('/gast/profile/{id}/edit', name: 'gast_profile_edit')]
public function register(Request $request, User $user, UserRepository $userRepository, UserPasswordHasherInterface $userPasswordHasher,): Response
{
$form = $this->createForm(RegistrationFormType::class, $user);
// add submit botton custom
$form->add('Wijzigen', SubmitType::class, array(
'label' => 'Wijzigen',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$userRepository->save($user, true);
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
$bookings = $this->getuser()->getBookings();
#[Route('/gast/boekingen/add', name: 'gast_boekings_add')]
public function addGastBookings(UserRepository $userRepository, EntityManagerInterface $entityManager, Request $request, UserInterface $user): Response
{
// get current user
$user = $this->getUser();
$booking = new Booking();
$form = $this->createForm(BookingType::class, $booking);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// setting the currrent user
$booking->setUser($user);
$entityManager->persist($booking);
$entityManager->flush();
return $this->redirectToRoute('gast_boekings');
}
$title = "Add booking";
return $this->renderForm('gast/add.html.twig', [
'title' => $title,
'form' => $form,
]);
}
$builder
->add('date', DateType::class, [
'widget' => 'choice',
])
->add('time', TimeType::class, [
'input' => 'datetime',
'widget' => 'choice',
])
// User is setted from the controller: $booking->setUser($user);
->add('donkey_adventure', EntityType::class, [
// looks for choices from this entity
'class' => DonkeyAdventure::class,
'choice_label' => 'name',
])
->add('Add', SubmitType::class, [
'attr' => ['class' => 'save btn-primary'],
])
;
}
$builder
->add('date', DateType::class, [
'widget' => 'choice',
])
->add('time', TimeType::class, [
'input' => 'datetime',
'widget' => 'choice',
])
// User is setted from the controller: $booking->setUser($user);
->add('donkey_adventure', EntityType::class, [
// looks for choices from this entity
'class' => DonkeyAdventure::class,
'choice_label' => 'name',
])
->add('Add', SubmitType::class, [
'attr' => ['class' => 'save btn-primary'],
])
;
}
//delete booking
#[Route('/gast/boekingen/{id}/delete', name: 'gast_boekings_delete')]
public function deleteGastBookings(UserRepository $userRepository, Booking $booking, Request $request, EntityManagerInterface $entityManager): Response
{
$entityManager->remove($booking);
$entityManager->flush();
$this->addFlash(
'success',
'De boeking is verwijderd!'
);
return $this->redirectToRoute('gast_boekings');
}
<div class="row my-4">
<div class="col-md-8 mx-auto">
<div class="card">
<div class="card-header">
Update Room
</div>
<div class="card-body">
{{form(form)}}
</div>
</div>
</div>
</div>
<div class="container">
<div class="row my-5">
<div class="col-md-10 mx-auto">
{% for message in app.flashes('success') %}
<div class="alert alert-success">
{{ message }}
</div>
{% endfor %}
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<span>List of rooms</span>
<a href="{{path('room_create')}}" class="btn btn-sm btn-primary">
Add
</a>
</div>
<div class="card-body">
<table class="table table-borderd table-hover">
<thead>
<tr>
<th>ID</th>
<th>TITLE</th>
<th>DESCRIPTION</th>
<th>IMAGE</th>
<th>PRICE</th>
<th>NUMBER</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
{% for room in rooms %}
<tr>
<td>{{loop.index}}</td>
<td>{{room.title}}</td>
<td>{{room.description}}</td>
<td>
{% if room.image %}
<img src="{{asset('uploads/'~room.image)}}" alt="{{room.title}}" width="60" height="60" class="fluid my-2 rounded">
{% else %}
<img src="{{asset('uploads/default.jpg')}}" alt="{{room.title}}" width="60" height="60" class="fluid my-2 rounded">
{% endif %}
</td>
<td>{{room.price}}</td>
<td>{{room.number}}</td>
<td class="d-flex justify-content-around ">
<a href="{{path('room_show', {id: room.id})}}" class="btn btn-sm btn-dark">Show <i class="fa-solid fa-eye"></i></a>
<a href="{{path('room_edit', {id: room.id})}}" class="btn btn-sm btn-warning">Edit <i class="fa-solid fa-pen-to-square"></i></a>
<form id="{{room.id}}" action="{{path('room_delete', {id: room.id})}}" method="POST"></form>
<button onclick="deleteItem('{{room.id}}')" class="btn btn-sm btn-danger">Delete <i class="fa-solid fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
composer require symfony/form
php bin/console make:form
and then give the e.g BookingType
give class Booking
https://symfony.com/doc/current/reference/forms/types.html
$bookings = $this->getuser()->getBookings();
<td>{{booking.date|date("d-m-y")}}</td>
<td>{{booking.time|date('H:i:s')}}</td>