Laravel sanctum check if user is authenticated - php

How to check if the user is authenticated when using Laravel sanctum?
Example :
Controller :
public function testAuth(Request $request)
{
if ($request->user()) {
return "auth";
} else {
return "guest";
}
}
api.php
Route::get('testauth', [MyTestController::class, 'testAuth']);
this route always returns guest even if I pass token in headers.
when I add sanctum middleware, route return auth
api.php
Route::get('testauth', [MyTestController::class, 'testAuth'])->middleware('auth:sanctum');
but I don't want that , I want to check if the user is authenticated in the controller without using middleware

Try this following code will help you.....You can use user('sanctum') instead of user()
public function testAuth(Request $request)
{
if ($request->user('sanctum')) {
return "auth";
} else {
return "guest";
}
}

first attach auth middleware with sanctum guard like this to route
Route::get('/somepage', 'SomeController#MyMethod')->middleware('auth:sanctum');
Then inside route closure/controller action access it with
auth()->user()
as usual
authorization http header must hold your bearer token

return auth('sanctum')->check() ? "Auth" : "Guest";

Related

Redirect to other route when session has expired in Laravel 5.8

I´m trying to return another route because in my case login it´s a modal page, and when the session has expired, return to this route but it does not exist. I don´t know how I would do this.
I can see this in web: if(Auth::check()){ return route('/')} but i don´t know where i´m putting this code.
Also i can see this: in 'App\Exception\Handler' put this:
if ($exception instanceof AuthenticationException) {
return redirect('/');
}
How I would can to do this?
Thanks for helping me
You can create a route to check sessions, every minute it will check session exists or not.
You can use like this:
Blade part:
#if (Auth::user())
<script>
$(function() {
setInterval(function checkSession() {
$.get('/is-logged-in', function(data) {
// if session was expired
if (!data.isLoggedIn) {
// redirect to login page
// or, may be better, just reload page
location.reload();
}
});
}, 60000); // You can change it
});
</script>
#endif
Route:
Route::get('is-logged-in', 'Auth\AuthController#checkSession');
Controller:
public function checkSession()
{
return Response::json(['isLoggedIn' => Auth::check()]);
}
Laravel probably already has what you need. Take a look at the App\Http\Middleware\Authenticate class. This is a middleware that will redirect user to 'login' named route (by default), if the session has expired.
By default none of the routes you put in routes/web.php are protected by this middleware, but you can change this.
Method 1: Add a auth middleware in your controller's constructor:
public function __construct()
{
$this->middleware('auth');
}
Method 2: Add a auth middleware for one of your routes:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Method 3: Adding all protected routes into group:
Route::group(['middleware' => ['auth']], function () {
// All your protected routes go here
});
Then you can easily change the URL which will be used for redirecting users with expired session (not authenticated). Just edit the App\Http\Middleware\Authenticate::redirectTo() method and return your URL, for example:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('yourLoginRouteName');
}
}

How to redirect to a previous URL in Laravel 5.6 and intended

In my Laravel application I have a middleware for specific routes, in this middleware I validate to redirect to a url.
public function handle($request, Closure $next)
{
$isValidated= ....
if ($isValidated) {
session()->put('url.intended', URL::full());
return redirect()->route('routeone')
}
return $next($request);
}
in the store method of that table when you register I do a redirect in the following way, but it turns out that when I do it, it redirects me to domain/img/favicon.png and I did not do the previous route
public function store(Request $request)
{
....
return redirect()->intended(session('url.intended') ?? '/admin');
}
What is the problem here or how could I address this detail to redirect to the url before the middleware redirects. ?
Try to use this code :
$referrer = $this->request->headers->get('referer');
$url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession();
or directly :
$url = request()->headers->get('referer');
and
session()->put('url.intended', $url);
Could you not just do this
return back();
From the docs https://laravel.com/docs/5.7/redirects#creating-redirects

Profile Settings middleware

I have a user profile page and user profile/settings page
the problem is I made a middleware for settings page to prevent any auth user from entering other users settings page or update them Unless the ID OR SLUG IS MATCHED to the auth user but I'm using Vue whenever I use the API routes to fetch or update the data it says unauthorized 401 or 500.
middleware :
public function handle($request, Closure $next)
{
if ($request->slug != auth()->user()->slug) {
return redirect()->to('/');
}
return $next($request);
}
API route :
Route::get('/profile/{slug}','ProfilePrivateController#show')->middleware('editProfile');;
VueJs :
update(){
axios.put(`/api/profile/${this.id}`,{
email : this.email,
username : this.name,
password : this.password,
education_level : this.education_level,
fb_url : this.fb_url,
twitter_url : this.twitter_url,
field : this.field
})
.then(res=>console.log(res))
}
Controller :
public function show($slug)
{
$user = User::findBySlugOrFail($slug);
return response()->json($user);
}
public function update(Request $request, $slug)
{
$user = User::findBySlug($slug);
$user->update([
'email'=>$request->email,
'education_level'=>$request->education_level,
'field'=>$request->field,
'school'=>$request->school,
'fb_url'=>$request->fb_url,
'twitter_url'=>$request->twitter_url,
]);
if($request->has('password')){
$user->save([
'password'=>$request->password
]);
}
return response()->json('user updated',200);
}
I Want to let the user update his settings and secure the API at the same time.
I'm really lost at this point Any help is appreciated!
You have a GET request for the API route, but using a PUT request in Vue.
Updating Route::get to Route::put should solve the problem.
Also, since its an AJAX request, you should be returning a JSON response so it can easily be consumed. You can return something similar to:
return response()->json(['error' => 'unauthorized'], 401);

Redirect back to page I entered from after logging in

public function login()
{
$login = EmployeeLogin::whereEmail(request()->email_id)->first();
if ($login) {
if($login->active == 1){
if (Auth::guard('employer')->attempt(['email' => request()->email_id, 'password' => request()->pwd]))
{
Auth::guard('employer')->user();
return redirect()->intended('/');
}
else{
return redirect()->route('employer.auth')->with('message','Incorrect Email id or Password');
}}}}
How to redirect back to page I entered from after logging in?
We have already tried using
redirect()->back()
return Redirect::route('dashboard'); and
with return Redirect::intended('dashboard');
I'm using laravel 5.4.
Use intended() method
return redirect()->intended('/');
From docs
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
Use Redirect::to()
use Illuminate\Support\Facades\Redirect;
return Redirect::to('dashboard');
And in routes.php
Route::get('/dashboard', 'Controller#method')->name('dashboard');

How can I return to a specified URL after login in Laravel?

I'm using Laravel 5.3 and want to return the user to a user-specified URL after login.
I am using a lot of JavaScript and want to return to a specific URL, that isn't the URL the user is trying to access, after they have logged in. The URL is different depending on user action.
For example:
/login?r=/come/here/after/login
I can pass this URL to the login screen, but I can't find a way to pass it through to the auth controller for redirection after login is successful.
In your case I would create a custom auth middleware just for the custom redirected routes:
class PostLoginRedirect
{
public function handle($request, Closure $next, $guard = null)
{
$response = $next($request);
if (\Auth::id() && isset($request->r)) {
// Return the new route redirect.
return redirect($request->r);
}
// Return the custom one in case r? don't exists.
return $response;
}
}
Declare your new middleware on app/Http/Kernel.php
protected $routeMiddleware = [
'login-redirect' => \YourNamespace\PostLoginRedirect::class
];
And add to your routes:
$this->post('login', ['middleware' => 'login-redirect', 'uses' => 'Auth\AuthController#login']);
Maybe you need to do a minor change but must work :)

Categories