How to attach variable to reset password link view in laravel? - laravel-5

I am using laravel 5.2 where I need to sent an OTP code to reset password, though email is being sent with built in subject and limited message done by make:auth command but how to customize? I have tried to follow the link unfortunately I am unable to understand how i can use this to solve.
I customized the api like this
public function sendResetLinkEmail(Request $request)
{
$this->validateSendResetLinkEmail($request);
$broker = $this->getBroker();
$email = $request->input('email');
$userid = DB::table('users')->where('email','=',$email)->value('id');
$uniqueotp = "DIYA".uniqid();
$curr_timestamp = strtotime(date("Y-m-d H:i:s"));
$date = strtotime("+7 day", $curr_timestamp);
$expiry_otp = date('Y-m-d H:i:s',$date);
$ip_address = $request->ip();
DB::table('otp_users')->insert([
'user_id' => $userid,
'status' => 0,
'otp_code' => $uniqueotp,
'ipaddress'=>$ip_address,
'expires_at'=>$expiry_otp
]);
$response = Password::broker($broker)->sendResetLink(
$this->getSendResetLinkEmailCredentials($request),
$this->resetEmailBuilder()
);
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->getSendResetLinkEmailSuccessResponse($request,$response);
case Password::INVALID_USER:
default:
return $this->getSendResetLinkEmailFailureResponse($response);
}
}
Any idea how I can achieve?
My required email message like this:
Hello, Tamaghna Banerjee Click here to reset your password:
Your OTP is: B16445512121
Reset Your Password through http://localhost/diya/public/password/reset/83baba9f61fc851b9d80b515415ec86c43b03b56b068e1888256db7a7831ba83?email=tamaghnabanerjee%40live.com

Related

Route for resetting password in Laravel 7

I am using the custom password reset option in Laravel 7. When the user clicks the reset password button (in the inbox of her/his email), the user is redirected to the password reset link. Here is my link
http://localhost/LaraTest/public/reset/5199667639cfc4f5ea624f4c18dbf7e8-vJcnLSH92vAj1IlnV3j7phT8zBtcbX0gSDbjXX37oFsuEM560oAiehZ4oVd0?email=basish%40gmail.com
Here is the code which generates the link
$token1= md5($fp_email);
$token2 = Str::random(60);
$fp_token = $token1."-".$token2;
//some more codes here
$link = 'localhost/LaraTest/public/reset/' . $fp_token . '?email=' . urlencode($fp_email);
//$link is sent to user as email
Route (after some research)
Route::get('reset/{tokenname}{email}','LoginController#resetpassword');
Controller
public function resetpassword(Request $request){
return view('resetpassword');
}
How would I define my route? I am a bit confused as my link contains
both the password reset token and the email id.
How will I retrieve the password reset token and the email id from the link above,after being redirected to the new password form?
Your route should be:
Route::get('reset/{tokenname}','LoginController#resetpassword');
In then the actual handler:
public function resetpassword(Request $request, $token){
$email = $request->email;
return view('resetpassword', compact('token', 'email');
}
Then in your view you can have:
<input type="hidden" name="email" value="{{$email}}" />
<input type="hidden" name="token" value="{{$token}}" />
and your actual password reset handler this would probably be defined in a route like:
Route::post('reset', 'LoginController#doPasswordReset');
and the method body would be (code borrowed in some part from the laravel source):
public function doPasswordReset(Request $request){
$validatedRequest = $request->validate([
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:8',
]);
$email = $request->email;
$token = $request->token;
$broker = app(PasswordBrokerManager::class);
$response = $broker()->reset(
$validatedRequest, function ($user, $password) {
// save new password here
}
);
return $response == Password::PASSWORD_RESET
? // Reset response?
: // Reset failed response?
}
This will ensure Laravel can verify the user by the provided email and password before doing the actual password reset.

Laravel sending e-mails to new registered users

I'm trying to send e-mails to new users. I made changes in my env. file. I am using a gmail.com mail service. I want to send e-mails to users including their name. Ex:
Hi John, your registration is succesful!
Here John part will be user name.
my code is here in RegistrationController:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$to_name = $data['name'];
$to_email= $data['email'];
$body =[];
$mailData=array('body'=>$body);
Mail::send('email.email-register', $mailData, function($message) use ($to_name, $to_email ){
$message->to($to_email, $to_name)->subject('Registration is succesfull!');
$message->from(env('MAIL_USERNAME'));
});
return $user;
}
Also i am using a mail template. I want to send user as variable to the view. How do i do that?
1- You need to run command php artisan make:mail RegisterMail
2- Add Library use App\Mail\RegisterMail;
Mail::to('YourEmail#gmail.com')->send(new RegisterMail($mailData));
3- Create a new Data Member in your App\Mail\RegisterMail.php Class
public $mailData;
public function __construct($mailData)
{
$this->mailData = $mailData;
}
4- Add this in your App\Mail\RegisterMail.php
public function build(){
return $this->from('youremail#gmail.com','your name')->replyTo('youremail#gmail.com')->subject($this->mailData['subject'])->view('email')->with('mailData',$this->mailData);
}

How do I manually send a password reset request in Laravel 5.8

I would like to manually send a password reset request to a specific user (not the one currently logged in) from within a controller. I did some digging around in the Laravel code and I searched many articles but I do not get output.
//...
use Illuminate\Support\Facades\Password;
//...
public function sendResetEmail(Request $request)
{
// I will assueme that you already have $email variable
$response = Password::sendResetLink(['email' => $email], function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
dump('We have e-mailed your password reset link!');
case Password::INVALID_USER:
dump('We can\'t find a user with that e-mail address.');
}
}
You can do it using the Password facade
$email = 'example#domain.com';
$response = \Illuminate\Support\Facades\Password::broker()->sendResetLink($email);
$ok = $response == \Illuminate\Support\Facades\Password::RESET_LINK_SENT;

How To Get Auth ID form user table and grab it for store to other table on database

I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user

Laravel Socialite Google login only with one domain

I have a Google+ login on my app with Laravel Socialite. When the login is done I have a callback to connect the user (I create her in database if necessary).
But I want to restrain the connection to only the company (email like "example#company.com", so only the email with "company.com").
Can I do it with Laravel Socialite ? I can make the verification manually in my callback but if Socialite can do it, it's better.
Thank you
My callback :
public function handleProviderCallback($provider){
$user = Socialite::driver($provider)->user();
if ($user) {
$local_user = User::whereEmail($user->getEmail())->first();
// If we don't have a user create a new user
if (!$local_user) {
$fragment = explode(' ', $user->getName());
$local_user = User::create([
'first_name' => isset($fragment[0]) ? $fragment[0] : '',
'last_name' => isset($fragment[1]) ? $fragment[1] : '',
'email' => $user->getEmail(),
'last_seen' => Carbon::now(),
'password' => ''
]);
$local_user->roles()->attach(Role::whereName('User')->first());
}
auth()->login($local_user);
}
return redirect($this->redirectTo);
}
You have a step by step guide for domain restriction.
In controller you need to specifiy these actions:
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// only allow people with #company.com to login
if(explode("#", $user->email)[1] !== 'company.com'){
return redirect()->to('/');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->to('/home');
}
No, you can’t do it in Socialite itself because Socialite is just a mechanism of retrieving tokens from OAuth-compliant servers.
If you only want to accept users with a particular email suffix, then that’s business logic so something you should handle in your callback:
public function handleProviderCallback()
{
$user = Socialite::driver('google')->user();
if (Str::endsWith($user->getEmail(), '#example.com')) {
// Look up user and authenticate them
}
abort(400, 'User does not belong to organization');
}

Resources