laravel 4.2 user roles with auth and Entrust - laravel

I look for to make two interface
Administrator (Administrator role)
Subscriber (subscriber role)
I used for now auth and entrust (Github Link) of Laravel 4
A recording User
in my SubscriptionContoller.php I make this :
public function doRegister(){
$password=Input::get('password');
$data = array(
'email' => Input::get('email'),
'password' => Hash::make($password)
);
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$messages = array(
'required' => 'The :attribute field is required.',
);
$validator = Validator::make($data, $rules, $messages);
if ($validator->fails()) {
Session::flash('message', 'This email is already registered, please choose another one.');
return Redirect::to('subscription/register')
->withErrors($validator);
} else {
$user = new User;
$role = Role::where('name','=','agency')->first();
$user->email = Input::get('email');
$user->password = Hash::make($password);
$user->save();
$user->roles()->attach($role);
Session::flash('message', 'Successfully created account! Please login to submit your ad.');
return Redirect::to('subscription/dashbord');
}
}
How should i write the routes.php and filters.php ??

Just put this line on top of your routes.php
Entrust::routeNeedsRole( 'subscription*', 'agency' );
More Details:
This will only allow users with agency role to be able to access subscription/* urls. If user didn't have that role, then by default an App::abort(403); will be executed, which will look for 403.blade.php in your views/public/ folder.
If you want to do something specific if user didn't match the role, you can pass the third parameter as follow:
Entrust::routeNeedsRole( 'subscription*', 'agency', Redirect::to('/not-authorized'));

Related

How to log in a user with custom guard in Laravel within a controller

I have a custom guard set up for 'customer' which has a LoginController that works absolutely fine. The login controller is as follows:
public function login(Request $request)
{
// Validate form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if(Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))
{
return redirect()->intended(route('customer.dashboard'));
}
// if unsuccessful
return redirect()->back()->withInput($request->only('email','remember'))
}
Now, within my workflow in another route where I check out customers; I have another controller where I create a new customer. I then attempt to log them in since I have all their details, this doesn't seem to work, does anyone have any idea on what I am doing wrong?
public function registerCustomer($data)
{
$pw = Hash::make($data->pw->main);
$customer = new Customer;
$customer->firstname = $data->customer->name;
$customer->lastname = $data->customer->lastname;
$customer->mobile = $data->customer->mobile;
$customer->email = $data->customer->email;
$customer->password = $pw;
$customer->save();
//I HAVE TRIED THIS
// if(Auth::guard('customer')->attempt(['email' => $data->customer->email, 'password' => $pw]))
// {
// dd('logged in');
// }
//AND NOW THIS...
$logged = Auth::guard('customer')->attempt([ 'email' =>$data->customer->email, 'password' => $pw ]);
dd($logged);
}
In registerCustomer function, $pw is an encrypted password. You could not use it for Auth::guard('customer'). You have to replace $pw by $data->pw->main.
$logged = Auth::guard('customer')->attempt([ 'email' =>$data->customer->email, 'password' => $data->pw->main ]);
dd($logged);

How to send password set(reset link) laravel 7

I was trying to send a password reset link to my newly created user and had a hard time trying to find a solution. In case someone has the same issue here is what worked for me in Laravel 7.
Or is there a better way to handle all: add entry in password_resets table and send the notification?
Mail sending properly but i want to send password reset mail to user .Below is the my add controller
public function contactSave(Request $request)
{
$password = Hash::make($request->name);
$validate = $request->validate([
'name' => 'required|regex:/^[\pL\s\-]+$/u',
'email' => 'email',
'phone' => 'digits:10',
'address' => 'required',
'country' => 'required',
'state' => 'required',
// 'comment' => 'required',
'organization' => 'required',
'captcha' => 'required|captcha'
],
[
'captcha.captcha' => 'Incorrect Captcha'
]
);
$user= new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $password;
$user->save();
$CustomerContact= new CustomerContact;
// $CustomerContact->name = $request->name;
// $CustomerContact->email = $request->email;
$CustomerContact->phone = $request->phone;
$CustomerContact->address = $request->address;
$CustomerContact->user_id = $user->id;
$CustomerContact->country_id = $request->country;
$CustomerContact->state_id = $request->state;
$CustomerContact->comment = $request->comment;
$CustomerContact->organization = $request->organization;
$CustomerContact->captcha = $request->captcha;
$CustomerContact->save();
$details = [
'title' => 'Hi '.$request->name.'',
'body' => 'Your account has been created successfully. Request you set your password with this link ???'
];
\Mail::to($request->email)->send(new \App\Mail\ContactMail($details));
return redirect('contacts')->with('success', 'User created successfully.');
}
Anyone here to help me. After saving data in user and employee . I want send email with password reset link to that user id email($request->email).
GIve me simplest solution with kittle explation how to do this
if i correctly understood your problem you can create a route for example: password/reset/user-code
and send it in your email to every user.
you should create a random-code for every user when its created and put it in that link and send in your email.
when user click on that link it will come to your controller and you check that random-code in your database and find your user! and when you have your user you can show them your view for resetting password and save new password
that what i did for password reset before
IF you want to send some data (link or token or everything else) to your mail use this:
Mail::to($request->email)->send(new ContactMail($your_token,$link,$user));
and in your ContactMail class:
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $your_token;
public $link;
public $user;
public function __construct($your_token,$link,$user)
{
$this->your_token= $your_token;
$this->link= $link;
$this->user= $user;
}
public function build()
{
return $this->view('email')
->with('your_token',$this->your_token)
->with('link',$this->link)
->with('user',$this->user
}
}

How to use the reset password mailable given by auth command

I would like to use the reset password mail but in another controller, for I do not know how to code the link in the button for mailtrap or email. So if there is a way of calling the same reset mail password, It would save me some lines. Or if someone could show me how to code that link in another mail function I am okay
Here is the controller I would like to use
public function create()
{
$roles = Role::all();
$addresses = Address::all();
$user = new User();
return view('admin.create', compact('roles', 'addresses', 'user'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'address_id' => 'required',
'name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'role_id' => 'required',
'description' =>['max:255'],
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$newuser = User::create([
'address_id' =>$request->address_id,
'name'=> $request->name,
'email' => $request->email,
'password' => Hash::make($quickpass),
'role_id' => $request->role_id,
'description'=> $request->description,
]);
Mail::to($newuser->email)
->send(new NewUserPassReset());
return view('admin.index')->with('message','The user has been created and a password reset email has been sent to them.');
}
The NewUserPassReset is the mailable I created on my own which has only the message but does not have the link
Right now, I am using mailtrap and above is my admin controller and he is the one who supposed to create user for me
I will kindly appreciate any help
Check out Illuminate\Auth\Notifications\ResetPassword.php.
It has the url that you're looking for:
url(config('app.url').route('password.reset', ['token' => $token, 'email' => $email]))
As you see, you'll need an email and a token to generate the reset password link.
Assuming you know the email, you can obtain the token with the Illuminate\Support\Facades\Password facade:
$token = \Password::createToken($user)
Hope this helps.

Can't update user information in Laravel

On my current project (a school management system) I want to give admins the ability to register users. Admins can create courses and subjects for example, which I've managed to do using resource controllers. However, I thought I could do the same for users, since the process appears the same to me. That is: I can show, edit, create, update and delete users.
However, I've run into several problems so far. Right now I can create users, but not update them.
Here's my code:
web.php
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('/admin', 'HomeController#admin');
Route::post('register', 'UserController#store');
Route::resources([
'admin/cursos' => 'CursoController',
'admin/turmas' => 'TurmaController',
'admin/semestres' => 'SemestreController',
'admin/materias' => 'MateriaController',
'admin/usuarios' => 'UserController',
]);
});
UserController.php
public function update(Request $request, $id)
{
$rules = array(
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'role' => 'required|string',
'password' => 'required|string|min:6|confirmed',
);
$validator = validator::make(Input::all(), $rules);
if ($validator->fails()) {
// return dd();
return Redirect::to('/admin/usuarios/' . $id . '/edit')
->withErrors($validator);
} else {
// store
$user = User::find($id);
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->role = Input::get('role');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Sucesso!');
return Redirect::to('/admin/usuarios');
}
}
Validation fails every time I try to update user information. What exactly is going on here? I'm relatively new to Laravel, so I'm a bit lost now.
If the request is failing when a user is trying to update their information without changing the email address, you need additional logic to ignore the id for user associated with the email.
Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.
To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
Applied to your set of validation rules it would look like:
$rules = array(
'name' => 'required|string|max:255',
'email' => [
'required',
'string',
'email,
'max:255',
Rule::unique('users')->ignore(auth()->id())
],
'role' => 'required|string',
'password' => 'required|string|min:6|confirmed',
);
You have to except the User ID ($id) in email validation, since u use "unique" rule.
you can check the guide in here
https://laravel.com/docs/5.6/validation#rule-unique

Laravel Email Confirmation On Registration

I need to send an email after a new user is created.
But I don't know how to return to the home page without getting an error.
This is what I am doing right now.
User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
if (Auth::attempt(['email' => $data['email'], 'password' => bcrypt($data['password']) ])) {
// Authentication passed...
return redirect('/');
}
I keep getting this as my error message.
SErrorException in SessionGuard.php line 439:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /Applications/XAMPP/xamppfiles/htdocs/sniddl/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 63 and defined
Edit:
changed the title to reflect the answer.
Here is a modified create function with an added email function for your register controller
Make sure Request is included in the pages top with namespaces being used:
use Illuminate\Http\Request;
Change the create function in your controller:
protected function create(Request $data)
{
$user = new User;
$user->name = $data->input('name');
$user->username = $data->input('username');
$user->email = $data->input('email');
$user->password = bcrypt($data->input('password'));
$user->phone = bcrypt($data->input('phone'));
$user->confirmation_code = str_random(60);
$user->save();
if ($user->save()) {
$this->sendEmail($user);
return redirect('VIEWPATH.VIEWFILE')->with('status', 'Successfully created user.');
} else {
return redirect('VIEWPATH.VIEWFILE')->with('status', 'User not created.');
}
}
Create the sendEmail function in the same controller that will use Laravels built in email. Make sure you create and your HTML email:
public function sendEmail(User $user)
{
$data = array(
'name' => $user->name,
'code' => $user->confirmation_code,
);
\Mail::queue('EMAILVIEWPATH.HTMLEMAILVIEWFILE', $data, function($message) use ($user) {
$message->subject( 'Subject line Here' );
$message->to($user->email);
});
}
NOTE:
Your going to need to update the VIEWPATH.VIEWFILE and EMAILVIEWPATH.HTMLEMAILVIEWFILE at a minimium in the examples above.
Check the repos below for CONTROLLER :
https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/Auth/AuthController.php
REGISTER VIEW(blade) EXAMPLE
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/auth/register.blade.php
EMAIL VIEW THAT RECEIVES VARIABLES:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/emails/activateAccount.blade.php
Ok so it turns out, by setting User::create as a variable it allows you to login in the user by returning the variable. Like this.
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
return $user;

Resources