Creating 'Reactivation' Option in Laravel - php

I have a problem that I wanted to create a reactivate option for users, but after trying several times, it is not working and I am confused.
here is the middleware (original version):
public function handle($request, Closure $next)
{
if (!Auth::check()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/');
}
}
else
{
$user = Auth::user();
if (!$user->activated) {
$activation = action('Auth\AuthController#getActivationMail', ['username' => $user->username]);
Auth::logout();
return redirect()->guest('auth')
->withErrors(array('message' => 'Please activate your account. Re-send your activation by clicking <a href=' . $activation . '>here</a>.'));
}
else if (!$user->enabled) {
Auth::logout();
return redirect('/auth')->withErrors(array('message' => 'Your account has been deactivated. Please email ... for any inquiries.'))->withInput();
// I tried to add the same method as the above if statement but not working here
}
$user->runDailyNotifications();
}
return $next($request);
}
I wanted to update my database using this way:
$user = Auth::user();
$user->enabled = 1;
$user->save();
which should be working fine.
I am new to Laravel. At first, I added these code in the middleware (which is a mistake).
After trying a bit I know it is impossible for it to work (when users click login twice they will log in after deactivating their account). Now I'm just wondering how could I achieve that since I kept getting error messages from everywhere. Thank you for the help!

I have done email confirmation and resend confirmation in one of my older projects. I've done the email confirmation validation in the post login check in the LoginController. Let me post you some snippets which might help you.
// Overwrite the authenticated method in LoginController
protected function authenticated(Request $request, $user)
{
if ($user->isBanned()) {
$this->logout($request);
flashError('Your account has been banned.');
return back();
}
if (!$user->isEmailConfirmed()) {
$this->logout($request);
flashWarning('Email confirmation pending. Click here to resend confirmation email.');
return back();
}
return redirect()->route($this->redirectRoute);
}
public function resendConfirmationEmail(Request $request, User $user)
{
//resend confirmation email
}
public function confirmEmail(Request $request, $token)
{
// Validate the token and update the user email confirmation status
}
Model
public function isBanned()
{
return (bool) $this->banned;
}
public function isEmailConfirmed()
{
return (bool) $this->confirmed;
}
Route
Route::get('confirm/resend/{user}', 'Auth\RegisterController#resendConfirmationEmail')->name('confirm.resend');
Route::get('confirm/email/{token}', 'Auth\RegisterController#confirmEmail')->name('confirm.email');

Related

how redirect user after email verification in laravel 8 and nuxtjs

how redirect user after email verification in laravel 8 and nuxtjs ??
email verification code
public function verify(Request $request)
{
auth()->loginUsingId($request->route('id'));
if ($request->route('id') != $request->user()->getKey()) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return response(['message'=>'Already verified']);
// return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return response(['message'=>'verified']);
}
how redirect user to localhost:3000 ?
Do like this in your notification file (e. Notifications/VerifyEmailNotification.php) :
public function toMail($notifiable)
{
$spa_url = env('SPA_URL') . '/email/verify/';
$id = $notifiable->getKey();
$hash = sha1($notifiable->getEmailForVerification());
$spa_url .= "{$id}/{$hash}";
$url = UrlSigner::sign($spa_url, Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)));
return (new MailMessage)
->line('Please click the button below to verify your email address.')
->action('Verify Email Address', url($url))
->line('This link expires in 1 hour and can only be used once. You can always request another link to be sent if this one has been used or is expired.');
}

Route does not redirect Laravel

I am trying to verify a new user using an email.
app/Http/Controllers/Auth/RegisterController.php
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails())
{
$this->throwValidationException($request, $validator);
}
DB::beginTransaction();
try
{
$user = $this->create($request->all());
$email = new EmailVerification(new User(['email_token' => $user->email_token]));
Mail::to($user->email)->send($email);
DB::commit();
$this->guard()->login($user);
return redirect($this->redirectPath());
}
catch(Exception $e)
{
DB::rollback();
return back();
}
}
public function verify($token)
{
User::where('email_token',$token)->firstOrFail()->verified();
return redirect('/login');
}
routes/web.php
Route::get('register/verify/{token}', 'Auth\RegisterController#verify');
The issue I am having is that the path never gets triggered, even though the email has the correct link. If I remove $this->guard()->login($user); it does activate it, but it doesn't log in and I need it, so the user redirects to a specific page and stays there until the account is being verified.
Any idea what might be the issue?

Laravel 5 custom login

I have write a custom login functionality in an old fashioned way.
1.If the email or password is incorrect it will shows the correct error message (ie invalid email,invalid password,account blocked)
2.If login is ok set a session user with corresponding row from the user table.
3.redirect to different url's according to usertype
Here is the implementation
public function login(Request $request)
{
$matches=['email'=>$request->email];
$users =User::where($matches)->first();
if($users == FALSE)
{
$request->session()->flash(
'errors',
'Invalid Email');
return redirect('adminlogin');
}
else if($users->account_status==0)
{
$request->session()->flash(
'errors',
'Account is blocked please contact admin');
return redirect('adminlogin');
}
else if (!Hash::check($request->password,$users->user_password))
{
$request->session()->flash('errors', 'Invalid Password');
return redirect('adminlogin');
}
else
{
$request->session()->put('user',$users);
if($users->user_type == 1)
{
$url = 'index';
}
else if($users->user_type == 3)
{
$url = 'index/package-home';
}
else
{
return view('errors.404');
}
return redirect($url);
}
}
Also in every page i've checked the user authentication with session value,if user session is not set it will redirect to login screen.
public function index(Request $request,$page='admin-home',$id=null)
{
if(!$request->session()->has('user'))
{
$request->session()->flash('errors', 'Session is expired');
return redirect('adminlogin');
}
//load dashboard
}
So my question is my method is correct for a custom authentication or do i need to anything else??
Note:
I don't like to use laravel default auth system,because it dosen't provide a way for custom error message or redirect to differnt url's based on usertype (ie admin,super admin etc)

Laravel - How to logout and display logout page when user manually enter unauthorized URL

I am beginner of laravel. I am using Role and permission concept for multiple user. If user manually enter URL which is not allow to that user then I want to logout that user.
I have successfully logout the user but display logout page in content area part not single page of login.
Please help me .
Thanks in advance ....
image snapshot
enter image description here
This is my ACL Code -
public function handle($request, Closure $next, $permission = null)
{
if ($request->getSession()->has('user')) {
$userObj = new \App\User;
if ($userObj->canAccess($request->getSession()->get('user')[0]['userPerm'], $permission)) {
return $next($request);
}
else{
redirect('logout')->withErrors(array('mst_error' => 'Unauthorized Access!'))->send();exit;
}
}
return $request->isXmlHttpRequest() ?
response(json_encode(array('session_logout' => true)), 401) :
redirect('login')->withErrors(array('mst_error' => 'You don\'t have any active session. Please login again'));
}
I have resolved :)
This is my handle function
public function handle($request, Closure $next, $permission = null)
{
if ($request->getSession()->has('user')) {
$userObj = new \App\User;
if ($userObj->canAccess($request->getSession()->get('user')[0]['userPerm'], $permission)) {
return $next($request);
}
else{
return response()->json(array('mst_error'=>'Unauthorized Access.'),401);
}
}
return $request->isXmlHttpRequest() ?
response(json_encode(array('session_logout' => true)), 401) :
redirect('login')->withErrors(array('mst_error' => 'You don\'t have any active session. Please login again'));
}
This is my Ajax Request -
$.ajax({
url:url,
data:data,
statusCode: {
401: function(res){
location.href = "unauthorized";
}
}
}).done(function(result){console.log(result);
$('#section-content').html(result);
});
This is my unauthorized function in Auth Controller
protected function unauthorized_logout (Request $request) {
if ($request->getSession()->has('user')) {
$request->getSession()->flush();
}
Session::flash('error','Unauthorized Access!');
return redirect('/');
}

Set the active status of a user in the credentials and still return an activation message in Laravel 5.1

I wanted to find out how I would do as requested in the subject line, as the code below works fine but the user is logged in before checking the $user->Activated status. Here is some code to illustrate:
AuthController
public function authenticated(Request $request, User $user)
{
if ($user->Activated) {
return redirect()->intended($this->redirectPath());
} else {
Auth::logout();
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'activated' => 'You need to activate your account to login'
]);
}
}
Preferably I would like to do the following:
AuthController
public function getCredentials(Request $request)
{
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'Activated', '1');
}
But then the only message that gets returned is "These credentials do not match our records.", instead of "You need to activate your account to login". Also how would I update a LoginStatusId once the user is logged in, currently I do it like this:
AuthController
public function authenticated(Request $request, User $user)
{
if ($user->Activated) {
$user->LoginStatusId = 1;
$user->save();
return redirect()->intended($this->redirectPath());
} else {
Auth::logout();
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'activated' => 'You need to activate your account to login'
]);
}
}
Is there a better place to set the $user->LoginStatusId once they login, or is this the best place to put it?
Open this file vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
Add this block of code inside postLogin
// If activated is equal to 1, user allowed to login or throw an credential mismatch error
$userData = User::select('activated')->where('email', $request['email'])->first();
if ($userData->activated == 1) {
$request['activated'] = $activated;
}
$credentials = $this->getCredentials($request); //add these code before this line
And add 'activated' to getCredentials method. It will look like this:
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password', 'activated');
}
You can check user login status anywhere just using this Auth::user(). No need to store login status by yourself. As example in any controller you can write this:
if(Auth::user()){
// do this;
}else{
// do that;
}

Categories