The email verification process not working.
I send email correctly. When I click on link to verify the email, I have been redirected to login page.
It seems the route does not pass auth middleware.
This is how I defined the route:
Route::middleware('auth')->group(function () {
Route::get('email/verify/{id}/{hash}', [App\Http\Controllers\Auth\VerificationController::class, 'verify'])
->name('verification.verify');
});
This is the function in the controller (it's the standard laravel function, I did not edited it):
public function verify(Request $request)
{
if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) {
throw new AuthorizationException;
}
if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
if ($response = $this->verified($request)) {
return $response;
}
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect($this->redirectPath())->with('verified', true);
}
The auth middleware is the default middleware come with laravel.
Related
I am developing a dashboard and I am trying to handle the errors, for this I have this code on handler.php
public function render($request, Throwable $e)
{
if($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
{
if(Auth::user() && (Auth::user()->isStaff() || Auth::user()->isAdmin()))
{
return response()->view('dashboard.404error', [], 404);
}
return response()->view('404error', [], 404);
}
elseif ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
return response()->view('405error', [], 405);
}
// elseif($this->isHttpException($e) && $e->getStatusCode() == '405')
// {
// return response()->view('404error', [], 404);
// }
return parent::render($request, $e);
}
But to check if the user is logged and what type it is, I have to add this middleware on kernel.php:
Middleware:
\Illuminate\Session\Middleware\StartSession::class,
But I dont know why after that my pop ups stop appering when I edit a staff or create one and I dont know why.
Normally on views I return them with something like this:
return redirect()->route('admin.operadoras')
->with('alert-msg', 'Staff edited with success')
->with('alert-type', 'danger');
And what I have on blade view is this:
#if (session('alert-msg'))
#include('partials.message')
#endif
I dont know why that middleware, interfer with this messages.
Given the route:
Route::get('verify/{id}/{hash}', 'Auth\VerificationController#verify');
It uses the Laravel's default verify method from
auth-backend/VerifiesEmails.php
The default verify method looks like bellow:
public function verify(Request $request)
{
if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) {
throw new AuthorizationException;
}
if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return $request->wantsJson()
? new Response('', 204)
: redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
if ($response = $this->verified($request)) {
return $response;
}
return $request->wantsJson()
? new Response('', 204)
: redirect($this->redirectPath())->with('verified', true);
}
I would like to change only the last block of the code in the verify method from
return $request->wantsJson()
? new Response('', 204)
: redirect($this->redirectPath())->with('verified', true);
to
return $request->wantsJson()
? new Response('', 204)
: redirect($this->redirectPath())->with([
'verified' => true,
'userNotification' => [
'message' => 'Wellcome to my website',
'title' => 'Hello World',
],
]);
I know I can override the whole verify method in the VerificationController, which is not ideal to copy and paste the whole block of code for a small change.
My question is How can override only the last block of code as mentioned above?
Right before the final return there is this block:
if ($response = $this->verified($request)) {
return $response;
}
So in your VerificationController you can override just the verified method which is meant for that.
If you look into its source you will see it:
source
So in your local VerificationController add:
protected function verified(Request $request)
{
return $request->wantsJson()
? new Response('', 204)
: redirect($this->redirectPath())->with([
'verified' => true,
'userNotification' => [
'message' => 'Wellcome to my website',
'title' => 'Hello World',
],
]);
}
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?
Hey guys i got some Problems with the Slim Middleware.
I created a Middleware that checks if the user is logged with Facebook and has a specific Email address. So now when i call the url with the PHPStorm RESTful Test tool i should not be able to post data to the server...
But the Redirect does not work so i will be able to send data to the server.
/**
* Admin Middleware
*
* Executed before /admin/ route
*/
$adminPageMiddleware = function ($request, $response, $next) {
FBLoginCtrl::getInstance();
$user = isset($_SESSION['user']) ? $_SESSION['user'] : new User();
if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
$response = $response->withRedirect($this->router->pathFor('login'), 403);
}
$response = $next($request, $response);
return $response;
};
/**
* Milestone POST Method
*
* Create new Milestone
*/
$app->post('/admin/milestone', function (Request $request, Response $response) use ($app) {
$milestones = $request->getParsedBody();
$milestones = isset($milestones[0]) ? $milestones : array($milestones);
foreach ($milestones as $milestone) {
$ms = new Milestone();
$msRepo = new MilestoneRepository($ms);
$msRepo->setJsonData($milestone);
if (!$msRepo->createMilestone()) {
return $response->getBody()->write("Not Okay");
};
}
return $response->getBody()->write("Okay");
})->add($adminPageMiddleware);
So can anyone give me a hint what the problem could be?
I tried to add the same middleware to the get Route ... there it works :/ Strange stuff.
The problem is in your middleware logic.
if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
return $response->withRedirect($this->router->pathFor('login'), 403); //We do not want to continue execution
}
$response = $next($request, $response);
return $response;
So now i ended up with this code:
class AdminRouteMiddleware
{
public function __invoke($request, $response, $next)
{
FBLoginCtrl::getInstance();
$user = isset($_SESSION['user']) ? $_SESSION['user'] : new User();
if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$response = $response->withRedirect('/login', 403);//want to use the route name instead of the url
} else {
$response->getBody()->write('{"error":Access Denied"}');
}
} else {
$response = $next($request, $response);
}
return $response;
}
}
/**
* Milestone POST Method
*
* Create new Milestone
*/
$app->post('/admin/milestone', function (Request $request, Response $response) use ($app) {
$milestones = $request->getParsedBody();
$milestones = isset($milestones[0]) ? $milestones : array($milestones);
foreach ($milestones as $milestone) {
$ms = new Milestone();
$msRepo = new MilestoneRepository($ms);
$msRepo->setJsonData($milestone);
if (!$msRepo->createMilestone()) {
return $response->getBody()->write("Not Okay");
};
}
return $response->getBody()->write("Okay");
})->add(new AdminRouteMiddleware());
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('/');
}