Laravel Passport returned all users - laravel

I created a user auth system based on Passport in my app and now I have some troubles. When I send a token, my details() method returned all app users instead of specific one. I paste my code to show exactly what is going on.
Login method:
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('myapp')->accessToken;
$user->api_token = $success['token'];
$user->save();
return response()->json(['user' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
It return something like that:
{
"user": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImFjMzEwM2UyMzIwNGIxMjg3M2E3ZWMyZmUyNGJkNDEzMTQyN2I1ZWUzMWRjOGFhZjRhMzcyMDQzM2ZmNGJiZGJjZGU3ZjQ1ZjZkNzZmMGRkIn0.eyJhdWQiOiIxIiwianRpIjoiYWMzMTAzZTIzMjA0YjEyODczYTdlYzJmZTI0YmQ0MTMxNDI3YjVlZTMxZGM4YWFmNGEzNzIwNDMzZmY0YmJkYmNkZTdmNDVmNmQ3NmYwZGQiLCJpYXQiOjE1NTIxMzIyODMsIm5iZiI6MTU1MjEzMjI4MywiZXhwIjoxNTgzNzU0NjgzLCJzdWIiOiIxOCIsInNjb3BlcyI6W119.LmwTCSlRTrZ9pq01JK6tfsx5yjjA9qfidTws-0_vVc-UsFKQOJSk-K1uAYMR5gd0SQzC8VyG8bIJLVdPZbm5ggXkk-itN1bHEdZPFT7zdx7rOTFVF1ri9-chZIDL6nElosk3SOw_1QwuwOxiMHBB7ss9ItPHrtwkNEMxpeh16henknIZVYct0Vn1grztdnh7EJCM9SkKjIxqF0yozuw-wsN-UmsLvNoFZkOFWuNCPC9Mawx_ip2VBD26mwcxzTgD1XFwRloTCtDOAZfQ4DfgS_YuuXEPn8pfrkp92C1lxGXp09Wu0ZdzFaIf8LWEQXCgwlqvsVuFSnKt3lGyEPuHuJc_DjZZTcWgjslVQr7RhEqWQmRK2xlJpiAcZyWoI1vhfYLmullr1vf7nGCoRsp3UDZB64J2oPVjomcClEfseAKQbIq_9roKxIGjTeYdaF2vwHCosaxzrak7AqBHkze-z5cL8ix9G6rWBeg4sDUPhiLDgrgHK4ywxBqHMyto-Ywak56pzq1767r4reunDyNYDhLwSt0IiK1Hmx7ZQ9j6_EWy3NLf1oy7eGc33bj7eQNusbEa0TfcXujNK299RAEnTFLEc4kuS_otHzGrwSvOx2zYPsZkctZYn19YoyKaeP7hM1ek0zfIlGXsxQI84osPl91U7PHqAufIK6YJeizcik0"
}
}
When I have my token for specific user I send that token to details().
Details method:
public function details(Request $request)
{
$userData = $request->user()->with('kids')->with('hobbies')->with('conversations')->get();
return response()->json(['user' => $userData], $this->successStatus);
}
Here is my api.php route file:
Route::group(['middleware' => 'auth:api'], function(){
Route::get('details', 'UserController#details');
});
Route::post('login', 'UserController#login');
Route::post('register', 'UserController#register');
I don't know why my details method return all app users. Do you have any advice how I can fix that? I really appreciate any help with that trouble.

Related

Why login redirect is not working in Laravel

I am trying to login though API. My code is like below.
public function store(LoginRequest $request)
{
$response = Http::post('http://moretext/login', [
'email' => $request->email,
'password' => $request->password,
]);
$session_token = str_replace("Bearer ", "", $response->json()['access_token']); // I am getting Token here
if ($session_token) {
Session::put('SesTok', $session_token);
return redirect('/dashboard'); //This redirect is not working.
} else {
return redirect('/login')->withErrors('Login is not successful.');
}
}
I have below the code in route.php file.
Route::get('/dashboard', function () {
return view('dashboard');
});
there's no redirect throw apis
api except response json
if you want to redirect don't call as api
do in web routes and it will work fine

How can I delete the token when the user log out?

I made a UserController which generats an accessToken when a user registered succesfully on a page.
class UserController extends Controller
{
/**
* Login Method: in here we call Auth::attempt with the credentials the user supplied.
* If authentication is successful, we create access tokens and return them to the user.
* This access token is what the user would always send along with all API calls to have access to the APIs.
* Register Method: like the login method, we validated the user information,
* created an account for the user and generated an access token for the user.
*/
public function login()
{
$credentials = [
'email' => request('email'),
'password' => request('password')
];
if (Auth::attempt($credentials)) {
$success['token'] = Auth::user()->createToken('MyApp')->accessToken;
return response()->json(['success' => $success]);
}
$status = 401;
$response = ['error' => 'Unauthorized'];
return response()->json($response, $status);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success' => $success]);
}
public function getDetails()
{
return response()->json(['success' => Auth::user()]);
}
}
My problem is that I want to remove the token when the user logs out but I dont know how to remove the access token from the user.
logout function in my UserController
public function logout()
{
Auth::user()->tokens->each(function($token, $key) {
$token->delete();
});
return response()->json([
'message' => 'Logged out successfully!',
'status_code' => 200
], 200);
}
When I test it with postman with the GET route: http://127.0.0.1:8000/api/logout. Am I missing something?
UPDATE
Here s my api.php file:
Route::resource('categories', 'App\Http\Controllers\CategoryController');
Route::post('register', 'App\Http\Controllers\UserController#register');
Route::post('login', 'App\Http\Controllers\UserController#login');
/**
* We can group the routes we need auth for
* under common middleware. It secures our routes
*/
Route::group(['middleware' => 'auth:api'], function(){
Route::get('logout', 'App\Http\Controllers\UserController#logout');
});
I am testing it in postman using the route: http://127.0.0.1:8000/api/logout and passing the Bearer token, which I get from the login request, as a value.
It should be POST Request instead of GET request, because your deleting/making change to the database.
The route should look like this:
Route::POST('logout', 'App\Http\Controllers\UserController#logout')->middleware('auth:api');
And the logout method in in UserController should be.
public function logout()
{
auth()->user()->tokens->each(function ($token, $key) {
$token->delete();
});
return response()->json([
'message' => 'Logged out successfully!',
'status_code' => 200
], 200);
}
In your logout function, it should expire the token, not delete it
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([], Response::HTTP_NO_CONTENT);
}
OR if you wanna expire all his tokens:
use Illuminate\Support\Facades\Auth;
public function logout(Request $request)
{
$userTokens = Auth::user()->tokens();
foreach($userTokens as $token)
{
$token->revoke();
}
}

Redirect to view after API login using Passport

I added API authentication to my Laravel app using passport. I followed this tutorial:
https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876
Now how do I redirect to a view after the user is been authenticated? I need this to embed my webapp to another portal using single sign on.
This returns the user values:
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
This tells me the user is unauthorized:
public function details()
{
$user = Auth::user();
return redirect('/home');
}
This is my route:
Route::post('details', 'API\UserController#details')->middleware('auth:api');
This is my login:
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
You can validate user after
Auth::attempt(['email' => request('email'), 'password' => request('password')])
if(Auth::check())
return redirect()->route('<route_name>');

Redirect to profile page after authentication in laravel

When a user logs in I want them to be redirected to their profile page instead of homepage. I have a method in another controller that gets a user profile. Not sure what I need to do since the user profile takes a username variable but when user logs in I'm only asking for email and password.
My route file, but the following method is in a different controller from the authentication controller.
Route::get('/user/{username}', [
'uses' => 'ProfileController#getProfile',
'as' => 'profile.index',
'middleware' => ['auth'],
]);
My following method is in my authentication controller.
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('info' , 'Could not sign you in with that info.');
}
$user= User::where('username', $username)->first();
return redirect()->route('profile.index')
->with('info', 'You are now signed in.')
->with('user', $user);
}
The following is in my profile controller..
public function getProfile($username)
{
$user= User::where('username', $username)->first();
if (!$user){
abort(404);
}
return view('profile.index')
->with('user', $user);
}
To correctly build the route, you need to pass the username here:
$user = User::where('username', $username)->first();
return redirect()->route('profile.index', ['username' => $user->username])
->with('info', 'You are now signed in.')
->with('user', $user);
Get the username from the email provided and pass the $username variable to route:
public function postSignin(Request $request)
{
if (!Auth::attempt($request->only(['email', 'password']),$request->has('remember')))
{
return redirect()->back()->with('info' , 'Could not sign you in with that info.');
}
$username=User::where(['email'=>$request->email])->first()->username;
return redirect()->route('profile.index')->with('username', $username);
}
You can use as like below.
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect('profile.index')->with('info' , 'Could not sign you in with that info.');

Laravel 5.1 Authentication views

I'm using laravel 5.1 and the modular package.
In my controller I use the following login method:
public function postLogin(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('admin/dashboard');
}
return redirect('/login')->withErrors([
'email' => 'These credentials do not match our records.']);
}
My route:
Route::group(array('module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'), function() {
Route::get('admin/dashboard', [
'middleware' => 'auth',
'uses' => 'AdminController#index'
]);
}}
My controller:
public function index()
{
return view("Admin::index");
}
My Middleware/Authenticate:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
return $next($request);
}
This works and redirects me to the index view after login.
When the user is not logged in, it is still possible to access the index view by accessing the url: localhost/admin/dashboard.
How can I redirect the user to a custom page which shows an error to the user that it is not possible to access the url localhost/admin/dashboard when he is not logged in?
Any ideas? Thank you
The issue is with your route the middleware should be at the top level as soon as you hit the controller it should redirect if not authenticated
Route::group(['middleware'=>'auth','module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'], function()
{
Route::get('admin/dashboard', ['uses' => 'AdminController#index']);
});
secondly if you want to redirect user to a custom page you can do this
public function redirectUnAuthenticateUser()
{
\Session::flash('login_error', 'Kindly login before you can access this page');
//create a view that user would be redirected to
return view('session.unauthenticated') ;
}
and the change your auth function to below
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('you-custom-rout-name-matching-above-function');
}
}
return $next($request);
}
and on your view you can get the value of the flash message

Resources