Larvel passport auth_token not saved - laravel

I am working on a Laravel site and I have been the LoginController. Although I obtain the auth_token at login - it doesn't allow me to call the user method - it claims the user is "unauthetnicated"
https://laravel.com/docs/7.x/passport
https://laravel.com/docs/5.8/api-authentication
I followed some documentation claiming that its unauthenticated because I need to group commands in the route?
"This is because we are not authenticated to access that route"
https://www.toptal.com/laravel/passport-tutorial-auth-user-access
but then it throws an error with ['cors', 'json.response']?
my route/api.php looks like this
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => [/*'cors', 'json.response'*/]], function () {
// public routes
// get auth token, POST, /login
Route::post('login', 'LoginController#login');
Route::post('logout', 'LoginController#logout')->middleware('auth:api');
});
Route::middleware('auth:api')->group(function () {
// our routes to be protected will go in here
});
and my logincontroller is like this
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
//
function login(Request $request)
{
$request->validate([
'email' => ['required', 'email'],
'password' => ['required']
]);
$user = User::where('email', $request->email)->first();
//if user not found or the request password and user password does not match
if(!$user || !Hash::check($request->password, $user->password)){
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect']
]);
}
return $user->createToken('Auth Token')->accessToken;
}
function logout(Request $request)
{
$request->user()->tokens()->delete();
}
}

Related

Failed Manually Authenticating Users while login

i'm new in laravel. I'm stuck when creating manual authentication with laravel 9.
when the user is successfully logged in, but cannot access the view page with middleware Auth.
I tried dd(Auth::user()) and the result is null.
where is my mistake?
Controller
`
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
class OtorisasiController extends Controller
{
public function create()
{
return view('otorisasi.login');
}
public function login(Request $request)
{
$validasi = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::attempt($validasi)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->with('infologin', 'Data yang anda masukan salah');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
`
route
// Deafult Page After Login Route::get('/', [TransfersController::class, 'index'])->name('home')->middleware('auth');
how to do so, when login is successful, I can access all middleware auth pages

Laravel API: Illuminate\Contracts\Container\BindingResolutionException: Target class

i am working on API. I want to create login api. i have created UsersController in API folder it in controllers. when i run in postman i shows an error
Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController] does not exist. in file F:\University_Data\xamp\htdocs\stylooworld\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 835`
I don't now why its duplicated the routing path Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController]
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
UsersController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\UserController;
class UsersController extends Controller
{
//
public function loginUser(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
echo "<pre>";
print_r($data);
die;
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
// check email is activated or not (Only Work Online Server)
/* $userStatus = User::where('email', $data['email'])->first();
if ($userStatus->status == 0) {
Auth::logout();
$message = "Your account is not activated yet! Please confirm your email to activate!";
Session::flash('error_message', $message);
return redirect()->back();
}*/
//update user cart with user id
if (!empty(Session::get('session_id'))) {
$user_id = Auth::user()->id;
$session_id = Session::get('session_id');
Cart::where('session_id', $session_id)->update(['user_id' => $user_id]);
}
return redirect('/');
} else {
$message = "Invalid Username or Password";
Session::flash('error_message', $message);
return redirect()->back();
}
}
}
}
I don't know why this happen?
Update the routes.
For details please check (ref link) https://laravel.com/docs/8.x/upgrade and https://laravel.com/docs/8.x/releases#routing-namespace-updates
Use like this
api.php
If not working
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
Then Use like this
use App\Http\Controllers\API\UsersController;
Route::post('login', [UsersController::class, 'loginUser']);
import method Request
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
on click (import method) always ready.
are you ok.

laravel showing 1 after i login

When I log in Laravel, first thing that shows is 1 then it redirects me to my intended page. I have checked everywhere, there is no middleware which makes 1 to show up. I don't get what is the problem.
This is my login code:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Session;
class LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function authenticated()
{
return redirect('admin/dashboard');
}
public function showLoginForm()
{
return view('admin.login');
}
protected function validateLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required'
]);
}
public function logout()
{
session::flush();
auth::logout();
return back();
}
}
These are my routes
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
Auth::routes();
// Route::get('/home', 'HomeController#index')->name('home');
Route::post('/login', 'Auth\LoginController#attemptLogin')->name('login');
Route::middleware('auth')->prefix('/admin')->name('admin.')->group(function() {
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
Route::post('/logout', 'Auth\LoginController#logout')->name('logout');
});
There is not much in my routes as I just started to build my site and I am facing this error.

Class App\Http\Controllers\API\UserController does not exist

I am Having the issue of not getting token in postman as well as the following problem
ReflectionException
…\vendor\laravel\framework\src\Illuminate\Container\Container.php790
user controller does not exist
my route file;
Route::post('login', 'API\UserController#login');
Route::post('register', 'API\UserController#register');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController#details');
});
My controller file;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\Request;
class UserController extends Controller {
//
public $successStatus = 200;
/**
* login api
*
* #return \Illuminate\Http\Response
*/
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);
}
}
/**
* Register api
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]); 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], $this-> successStatus);
}
/**
* details api
*
* #return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this-> successStatus);
}
}
How can I Solve this?
If your controller path is /App/Http/Controllers/API, you need to adjust it's namespace :
namespace App\Http\Controllers\API;
If your controller path is /App/Http/Controllers, you need to adjust your routes:
Route::post('login', 'UserController#login');
simply just write folder extension in namespace
for example in your case
namespace App\Http\Controllers\API;
And in route you just write
Route::post('register','api\UserController#register');
It could be because you are not calling the right middleware on the user route that directs to that controller. You would have to create a user middleware.
You can do this by navigating to your App\Http\Middleware and add the user middleware with the name UserMiddleware.php and some code to it.
Firstly, you would need to import the following files;
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
Then you create a class called; class UserMiddleware
Add a handle function to it like so; public function handle($request, Closure $next)
Inside this function include the following code;
if (Auth::user()->usertype == 'user')
{
return $next($request);
}
Next up, head over to you App\Http\Kernel.php and add the following code at the bottom of the protected $routeMiddleware section;
'user' => \App\Http\Middleware\UserMiddleware::class,
Then go over to your route (API) and include this predefined user middleware to your URLs.
Route::group(['middleware' => 'user'], function () {
Route::post('login', 'API\UserController#login');
Route::post('register', 'API\UserController#register');
Route::post('details', 'API\UserController#details');
});
});
For this to work you would need to have a usertype field in your users table that is set to user by default. Your usertype column should look like this;
$table->string('usertype')->nullable()->default('user');
1. Copy the existing functions of your controller and delete it.
2. Recreate your controller but this time specifying the location of were you want to place it, in the Controllers directory. e.g.
php artisan make:controller NameOfYourSubFolder\YourControllersName
3. Paste you functions.
Laravel has web route and API route, with different namespace/path configuration, where the issue such as "Class App\Http\Controllers\API\UserController does not exist" comes from.
Web route:
in controller:
<?php
namespace App\Http\Controllers;
use Auth;
use App\Application;
use Illuminate\Http\Request;
class HomeController extends Controller
{
in web.php route file:
Route::get('/home', 'HomeController#index')->name('home');
API route:
in controller:
the namespace should be App\Http\Controllers\API if you put your API controllers in \API path.
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
in api.php route file, add API\ to the controller path.
Route::get('/carts', 'API\CartController#index');

Can't redirect users to custom URL after succesful login in Laravel

I am trying to redirect the users to a custom URL after a succesful login but it doesn't work. It keeps redirecting users to this dashboard page "/". I already deployed the website to the server so I can't clear the route cache with artisan.
Laravel version is 5.3.29
App\Http\Controllers\Auth\LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/my-profile';
protected $redirectPath = '/my-profile';
protected function redirectTo()
{
return '/my-profile';
}
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
App\Http\Middleware\RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check())
{
return redirect('/my-profile');
}
return $next($request);
}
}
I have read that there might be some problems with Laravel in this post. It says that there might be some problems with this file: /vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUser.php, but this error was fixed in Laravel version 5.3.29, but I can see that it is fixed and 'returnTo' method should work.
/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUser.php
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Support\Facades\Log;
trait RedirectsUsers
{
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
Log::info("RedirectsUsers");
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/homeeeee';
}
}
And my routes file:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Auth::routes();
Route::get('/', 'HomeController#index');
Route::get('/home', 'HomeController#index');
Route::get('/confirm-your-email', 'Auth\ConfirmEmailController#confirm_email');
Route::get('/confirm-email/{register_token}', 'Auth\ConfirmEmailController#index');
Route::get('/my-profile', ['as' => 'my-profile' , 'uses' => 'MyProfileController#show', 'userAlert' => null]);
Route::post('/my-profile/edit-about', 'MyProfileController#editAbout');
Route::post('/my-profile/edit-profile-picture', 'MyProfileController#editProfilePicture');
Route::get('/search/company', 'SearchController#searchCompany');
Route::get('/my-profile/add-job', 'MyProfileController#addJobPage');
Route::get('/my-profile/add-job/{id}', 'MyProfileController#addCompanyJobPage');
Route::post('/my-profile/add-a-job', 'MyProfileController#addJob');
Route::post('/my-profile/delete-job', 'MyProfileController#deleteJob');
Route::get('/users/{id}', ['as' => 'users', 'uses' => 'UserController#show']);
Route::get('/rate/user/{id}', ['as' => 'rate', 'uses' => 'RateController#showUserRate']);
Route::post('/rate/rate-user/{id}', 'RateController#rateUser');
Route::get('/invite-user-rate/{id}', 'RateController#showInviteUserToRateYou');
Route::post('/invite-rate/user/{id}', 'RateController#inviteUserToRateYou');
Route::get('/company/{id}', ['as' => 'company', 'uses' => 'CompanyController#show']);
Route::get('/rate/company/{id}', 'RateController#showCompanyRate');
Route::post('/rate/rate-company/{id}', 'RateController#rateCompany');
Route::get('/search/{page}/results/', 'SearchController#showSearchCompanies');
Route::get('/search/{page}/people/results', 'SearchController#showSearchPeople');
Route::get('/leave-a-rating/', 'SearchController#showLeaveARating');
Route::get('/invite', ['as' => 'invite', 'uses' => 'OtherAuthentificatedController#showInvite']);
Route::post('/email-invite', 'OtherAuthentificatedController#emailInvite');
Route::get('/contact', 'OtherController#showContact');
Route::post('/send-contact-email', 'OtherController#sendContact');
Route::get('/tyfcu', 'OtherController#thankYouForContactingUs');
you can run this command on your server for clear chache
if you want
php artisan cache:clear
and for redirecting you can redirect by this method
return Redirect::route('/my-profile');
think this might be help you

Resources