How to display the role of a user in FOSUserBundle - php

I would like to display the user role in Symfony with the FOSUserBundle.
public function showAction() {
$model = new User();
$role = $model->getRoles();
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->render('#FOSUser/Profile/show.html.twig', array(
'user' => $user,
'role' => $role,
));
}
This my code in my ProfileController put that I can not call in Twig. Here is my Twig file:
<div class="fos_user_user_show">
<p><b>{{ 'Username'|trans }}</b>: {{ user.username }}</p>
<p><b>{{ 'Email'|trans }}</b>: {{ user.email }}</p>
<p><b>{{ 'Role'|trans }}</b>: {{ role.user }}</p>

try only with this:
<p><b>{{ 'Role'|trans }}</b>: {{ role }}</p>

This should also work
<p><b>{{ 'Role'|trans }}</b>: {{ user.roles }}</p>

Related

ReflectionException in Route.php Class App\Http\Controllers\PasswordController does not exist

I am using Laravel 5.2 and trying to make a password change form with its controller. I have added the following routes:
Route::get('changepassword', array('as' => 'reset.password', 'uses' => 'PasswordController#edit'));
Route::post('resetpasswordcomplete', array('as' => 'reset.password.complete', 'uses' => 'PasswordController#update'));
The Http\Controllers\Auth\PasswordController has the following methods:
public function edit() {
return View::make('auth/passwords/change');
}
public function update() {
$hasher = Sentinel::getHasher();
$oldPassword = Input::get('old_password');
$password = Input::get('password');
$passwordConf = Input::get('password_confirmation');
$user = Sentinel::getUser();
if (!$hasher->check($oldPassword, $user->password) || $password != $passwordConf) {
Session::flash('error', 'Check input is correct.');
return View::make('auth/passwords/change');
}
Sentinel::update($user, array('password' => $password));
return Redirect::to('/');
}
The view is as such:
#if (Session::get('error'))
<div class="alert alert-error">
{{ Session::get('error') }}
</div>
#endif
{{ Form::open(array('route' => array('reset.password.complete'))) }}
{{ Form::password('old_password', array('placeholder'=>'current password', 'required'=>'required')) }}
{{ Form::password('password', array('placeholder'=>'new password', 'required'=>'required')) }}
{{ Form::password('password_confirmation', array('placeholder'=>'new password confirmation', 'required'=>'required')) }}
{{ Form::submit('Reset Password', array('class' => 'btn')) }}
{{ Form::close() }}
I get the ReflectionException error because I think the PasswordController is inside of the Auth folder and thus is only accessible to guests who want to reset their forgotten password using the auth scaffold. I would like to know how I could allow a logged in user to access this controller so that they could change their passwords if they wished?
EDIT: I tried doing the following after Alexy's solution:
public function __construct()
{
$this->middleware('guest', ['except' => ['resetpasswordcomplete', 'changepassword']]);
}
It still brings me back to home page.
Change controller path in routes.php to:
Route::get('changepassword', array('as' => 'reset.password', 'uses' => 'Auth\PasswordController#edit'));
Route::post('resetpasswordcomplete', array('as' => 'reset.password.complete', 'uses' => 'Auth\PasswordController#update'));

How TWIG executes if conditionals?

I have a php snippet in Symfony2 where I say:
If the user exists -> return these data sets in an array to the template
else -> return name=> 'user not found'. Below is the only way this can work if I have in my twig only the variable 'first_name' being used.
Clear Problem Explanation:
If the user doesn't exist in the database, I cannot call user.name, user.username, user.password. Even if the if conditional isn't satisfied, twig still tries to evaluate that inside statement.
What I want to say is:
if (user) {
{{ user.name }}<br>
{{ user.username }}<br>
{{ user.password }} <br>
}
else {
User not found
}
However, if the user isn't found, it will still try and execute the DB access from the variable user ... user.name.. etc. How can I fix this?
PHP Snippet
/**
* #Route("/login/{username2}/{password2}")
* #Template()
*/
public function indexAction($username2, $password2)
{
$em = $this->getDoctrine()->getEntityManager();
$respository = $em->getRepository("SchachteUserBundle:user");
$username = $username2;
$password = $password2;
$user = $respository->findOneBy(array("username"=>$username, "password"=>$password));
if ($user) {
return array('exists'=>true, 'first_name' => $user->getName(), 'username' => $user->getUserName(), 'password'=>$user->getPassword());
}
return array('exists'=>false, 'first_name' => 'USER NOT FOUND', 'username' => 'USER NOT FOUND', 'password'=>'USER NOT FOUND');
}
}
TWIG
{% if exists == true %}
Hello {{ first_name }}!
{% else %}
Sorry, that user does not exist!
{% endif %}
Why not simply inject the return of your findOneBy in the template :
$user = $respository->findOneBy(array("username"=>$username, "password"=>$password));
return array('user'=>user);
Then in the template
{% if user %}
{{ user.name }}<br>
{{ user.username }}<br>
{{ user.password }}
{% else %}
User not found
{% endif %}
Moreover if you query the database with a password it means you have stored the clear password. It is very bad practice.

Laravel Registration System not feeding data

I have a login/registration system I am looking to build in Laravel. Currently I am having trouble pulling the information from the form and inputting it into the table. When I submit the form it submits, but the data goes nowhere, I am admittedly new to Laravel.
This is how the form is written:
{{ Form::open() }}
#if (Session::get("error"))
{{ Session::get("error") }}<br />
#endif
{{ Form::label("first_name", "First Name") }}
{{ Form::text("first_name") }}
{{ $errors->first("first_name") }}<br />
{{ Form::label("email", "Email") }}
{{ Form::text('email', Input::old('email')) }}
{{ $errors->first("email") }}<br />
{{ Form::label("password", "Password") }}
{{ Form::password("password") }}
{{ $errors->first("password") }}<br />
{{ Form::label("password_confirmation", "Confirm") }}
{{ Form::password("password_confirmation") }}
{{ $errors->first("password_confirmation") }}<br />
{{ Form::submit("register") }}
{{ Form::close() }}
The user.register (part of a larger controller) which this POSTs to and GETs from is as follows:
public function register()
{
return View::make("user/register");
$validation = Validator::make(Input::all(), User::$rules);
if ($validation->fails())
{
return Redirect::to('register')->withErrors($validation)->withInput();
}
$users = new User;
$users->first_name = Input::get('first_name');
$users->email = Input::get('email');
$users->password = Hash::make(Input::get('password'));
if ($users->save())
{
Auth::loginUsingId($users->id);
return Redirect::to('profile');
}
return Redirect::to('register')-withInput();
}
}
Currently when I submit I get no errors simply a blank redirect to the registration page and nothing ends up in my DB. I am wondering if there is something wrong with my paths? The only other page that is similar to this that I have previously worked on (inputting data to a database) is a page to reset passwords (which works great), but that used a slightly different system through the Auth extension of Laravel.
This I am not familiar with. Can someone point me in the right direction? I have been compiling the knowledge I have gained from guides online but keep ending up in the same place!
Thanks a lot in advance,
Anything else you need (models, routes, etc. I just didn't think they were necessary) lemme know!
Change
return Redirect::to('register')-withInput();
to
return Redirect::to('register')->withInput();
edit:
oh - here is the problem:
public function register()
{
return View::make("user/register");
$validation = Validator::make(Input::all(), User::$rules);
...
remove the "return" function - it should be
public function register()
{
$validation = Validator::make(Input::all(), User::$rules);
...

Laravel 4 - Username not being passed on in URL

I am trying to get into Laravel 4 and am having a problem with editing users I have created. So far I have controllers, views, and routes to show a user and then edit the user by clicking the "Edit" button but when I click the submit button I keep getting a NotFoundHttpException and the "Crash/Error" orange and white Laravel screen. I did, however, notice that the URL changes from showing the username (ex - public/users/av1/edit - with av1 being the username) to only saying {username} (ex -public/users/{username}/edit). I am still new to Laravel but my thought is that I'm not passing the username along properly but I know that it could also be the Controller or route as well. I have tried removing and changing sections of code and have found that if I remove the code from the Controller I still get a URL with {username} but I at least don't get the "Crash/Errors" screen. If anyone could help explain where I am going wrong it would be very much appreciated!
Here is my view:
#extends('layout.main')
#section('content')
{{ Form::model($user, array('route'=>'user-edit-post')) }}
<div>
{{ Form::label('username', 'Username:')}}
{{ Form::text('username') }}
#if($errors->has('username'))
{{ $errors->first('username') }}
#endif
</div>
<div>
{{ Form::label('password', 'Password:')}}
{{ Form::password('password') }}
#if($errors->has('password'))
{{ $errors->first('password') }}
#endif
</div>
<div>
{{ Form::label('password_confirmation', 'Confirm Password:')}}
{{ Form::password('password_confirmation') }}
#if($errors->has('password_confirmation'))
{{ $errors->first('password_confirmation') }}
#endif
</div>
<div>
{{ Form::submit('Edit User') }}
</div>
#stop
My User Controller functions that relates to editing:
public function getEdit($username){
$user = User::where('username', '=', $username);
if($user->count()) {
$user = $user->first();
return View::make('users.edit')
->with('user', $user);
} else {
return App::abort(404);
}
}
public function postEdit($username){
$validator = Validator::make(Input::all(),
array(
'first_name' => 'required|max:20',
'last_name' => 'required|max:20',
'email' => 'required|max:50|email',
'username' => 'required|max:20|min:3',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
)
);
if($validator->fails()){
return Redirect::route('user-edit')
->withErrors($validator);
} else {
/*Edit User*/
$user = User::whereUsername($username)->first();
$password = Input::get('password');
$user->password = Hash::make($password);
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
$user->email = Input::get('email');
$user->username = Input::get('username');
/*password is the field $password is the variable that will be used in the password field*/
if($user->save()){
return Redirect::route('home')
->with('global', 'The password has been changed.');
}
return Redirect::route('home')
->with('global', 'The password could not be changed.');
}
}
And lastly my Routes:
/*Edit users (GET)*/
Route::get('users/{username}/edit', array(
'as' => 'user-edit',
'uses' => 'UserController#getEdit'
));
/*Edit Order (POST)*/
Route::post('/orders/{orders}/edit', array(
'as' => 'order-edit-post',
'uses' => 'OrderController#postEdit'
));
Change
{{ Form::model($user, array('route'=>'user-edit-post')) }}
To
{{ Form::model($user, array('route'=>array('user-edit-post', $user->username))) }}
Your route need additional parameters, so you need supply your parameters with your route name when binding model to form.
Yep, after reading the comment. I found the reason of your trouble here is the redirect in the postEdit function:
Change:
if($validator->fails()){
return Redirect::route('user-edit')
->withErrors($validator);
}
Into
if($validator->fails()){
return Redirect::route('user-edit', $username)
->withErrors($validator);
}
Again, your route need parameters. When the validation fails, you have been redirected to a wrong URL.

Laravel 3 search function controller

I am still new in Laravel. I'm trying to create search box for searching users by their username.
What is the best way to create controller for Laravel search box?
The view that I have look as follows:
{{ Form::search_open('/users/search') }}
{{ Form::search_box('search','admin', array('class' => 'input-medium')) }}
{{ Form::submit('Search'); }}
{{ Form::close() }}
I have the controller as below:
class Users_Controller extends Base_Controller {
public function action_search() {
$userdetail = Input::get("username");
$details = User::where('username', '=', Input::get('username')) - > first();
return Redirect::to_route("users");
}
}
You may try something like this :
Route :
Route::get('/search', array('as' => 'user.search', 'uses' => 'user#search'));
View : (search/index.blade.php)
{{ Form::open(URL::to_route('user.search')) }}
{{ $errors->has('username') ? $errors->first('username','<span class="error">:message</span>') : '' }}
{{ Form::text('username', Input::old('username', $username), array('class' => 'input-medium')) }}
{{ Form::submit('Search'); }}
{{ Form::close() }}
#if ( isset($user) )
#foreach ($user->results as $user)
{{ $user->first_name }}
{{ $user->last_name }}
#endforeach
#endif
Controller : (controllers/user.php)
class User_Controller extends Base_Controller
{
public function action_search()
{
$data['username'] = Input::get('username');
if(Input::get())
{
$rules=array( 'username' => 'required' );
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
return Redirect::back()->with_errors($validation)->with_input();
}
else {
data['user'] = User::where('username', '=', Input::get('username'));
}
}
return View::make('search.index', $data);
}
}
Model : (models/user.php)
class User extends Eloquent
{
// ...
}

Categories