I get this error when i try to access the post signin route. I'm new to laravel and i can't seem to figure out how to solve this error. Please help.
My Routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', [
'uses'=>'\ocsaf\Http\Controllers\HomeController#index',
'as'=>'home',
]);
/*
*Authentication
*/
Route::get('/signup', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#getSignUp',
'as'=>'auth.signup',
'middleware' => ['guest'],
]);
Route::post('/signup', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#postSignUp',
'middleware' => ['guest'],
]);
Route::get('/signin', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#getSignIn',
'as'=>'auth.signin',
'middleware' => ['guest'],
]);
Route::post('/signup', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#postSignIn',
'middleware' => ['guest'],
]);
Route::get('/signout', [
'uses'=>'\ocsaf\Http\Controllers\AuthController#getSignOut',
'as'=>'auth.signout',
]);
/*
*search
*/
Route::get('/search', [
'uses'=>'\ocsaf\Http\Controllers\SearchController#getResults',
'as'=>'search.results',
]);
/*
*Profile
*/
Route::get('/user/{username}', [
'uses'=>'\ocsaf\Http\Controllers\ProfileController#getProfile',
'as'=>'profile.index',
]);
Route::get('/profile/edit', [
'uses'=>'\ocsaf\Http\Controllers\ProfileController#getEdit',
'as'=>'profile.edit',
'middleware'=>['auth'],
]);
Route::post('/profile/edit', [
'uses'=>'\ocsaf\Http\Controllers\ProfileController#postEdit',
'as'=>'profile.edit',
'middleware'=>['auth'],
]);
Route::post('/profile/edit', [
'uses'=>'\ocsaf\Http\Controllers\StatusController#postStatus',
'as'=>'status.post',
'middleware'=>['auth'],
]);
});
AuthController.php
namespace ocsaf\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use ocsaf\Models\User;
class AuthController extends Controller
{
public function getSignUp()
{
return view('auth.signup');
}
public function postSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|max:255',
'password' => 'required|min:6',
]);
User::create([
'email' => $request-> input('email'),
'username' => $request-> input('username'),
'password' => bcrypt($request -> input('password')),
]);
return redirect()
->route('home')
->with('info', 'You have signed up, Please sign in!');
}
public function getSignIn()
{
return view('auth.signin');
}
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 those details ');
}
return redirect() ->route('home')->with('info', 'You are now signed in');
}
}
my signin.blade.php form statement
<form class="form-vertical" role = "form"
method = "post" action = "{{ route('auth.signin'); }}">
Your form method is post but for the route auth.signin the HTTP verb is get.
Related
am trying to do simple function, signup function. Am new in laravel so really does not know why this is not working...
Am getting 419 Page Expired in insomnia.
So this is my method code:
public function signup(Request $request)
{
$data = $request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'required',
];
$registeredUser = User::create($data);
return response()->json($registeredUser);
}
Route:
Route::prefix('api/v1')->group(function () {
Route::group(['namespace' => 'App\Http\Controllers'], function () {
/** signup */
Route::post('/signup', 'AuthController#signup');
});
});
So whats wrong with this code? why am getting 419?
I've created an api an it works however there is a weird behavior it doesnt allow me to send data in the body of the request.
Here's my code:
api.php
Route::controller(AuthController::class)->group(function () {
Route::post('login', 'login');
Route::post('register', 'register');
Route::post('logout', 'logout');
Route::post('refresh', 'refresh');
Route::get('me', 'me');
});
AuthController.php
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login','register']]);
}
public function register(Request $request){
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = Auth::login($user);
return response()->json([
'status' => 'success',
'message' => 'User created successfully',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
}
if i send data like this
localhost:8000/api/register?name=odlir4&email=odlirgz4#gmail.com&password=password
it works fine but if i send it like this
this doesn't work, anyone knows why this is happening? i think it should work or am i wrong?
Thank you!
in the route register you define the POST method
api.php
Route::post('register', 'register');
in postman you send data using GET method because it passes parameter
localhost:8000/api/register?name=odlir4&email=odlirgz4#gmail.com&password=password
it should be like this in Tab Body
https://www.postman.com/postman/workspace/published-postman-templates/request/631643-083e46e7-53ea-87b1-8104-f8917ce58a17
You need to get form-data in your controller using below method
public function register(){
$datarequest = $this->input->post();
// other code
}
OR if you want to send request in json
public function register(){
$datarequest = json_decode(file_get_contents('php://input'),true);
// other code
}
I am currently learning Laravel and using Sanctum to perform authentication.
I have a route working /register and /login and I am trying to create /me endpoint that's protected using auth:sanctum which as a test just returns the authenticated user.
In my api.php I have the following:
Route::post('/auth/register', [UserController::class, "register"]);
Route::post('/auth/login', [UserController::class, "login"]);
Route::middleware('auth:sanctum')->get('/me', function(){
return auth()->user();
});
In my UserController class I have the following:
class UserController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function register(Request $request)
{
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password'])
]);
return response([
'success' => $user->createToken('API Token')->plainTextToken
]);
}
public function login(Request $request)
{
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr))
{
return response('Credentials not found', 401);
}
return response([
'token' => auth()->user()->createToken('API Token')->plainTextToken
]);
}
public function logout()
{
auth()->user()->tokens()->delete();
return [
'message' => 'Tokens Revoked'
];
}
}
The /login and /register routes work fine, however, when I attempt to use the /logout or /me route which is using auth:sanctum middleware, I get the following error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.
Everything I've Google'd seem to show that I've implemented it correctly, so I'm not sure what I'm missing.
I managed to figure out the problem with some help from #LessMore.
I think most of the problem the auth.php being wrong. Under config/auth.php, under the api section change the driver from token to session, so it should be as follows:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
'hash' => false,
],
],
The other thing was I was forgetting to add the Authorization header with the bearer token that is returned on the login and to put Accept application/json header.
Trying to get Laravel multiple authentication to work using Doctrine instead of Eloquent. I've tried multiple things but keep getting stuck. I currently have two guards defined, two models, two login controllers, etc. If I enable either one or the other, they work. If I try both at the same time, only the default guard seems to work. When I try to access the other guard, I get redirected to the wrong login page.
If I go to /login - works as expected
If I go to /home (without being logged in) - redirected to /login as expected
If I go to /register- works as expected
If I go to /admin/login - works as expected
If I go to /admin/register - works as expected
If I go to /admin (without being logged in) - fail - should get redirected to /admin/login but instead getting redirected to /login
I'm sure I'm missing something simple. Everything works individually. It's just getting the /admin route to use the right middleware...I think...maybe?
My routes file:
Auth::routes();
// staff authentication routes
Route::group( [ 'middleware' => [ 'web' ] ], function() {
Route::get( 'admin/login', 'Auth\StaffLoginController#showLoginForm' );
Route::post( 'admin/login', [ 'as' => 'staff.login', 'uses' => 'Auth\StaffLoginController#login' ] );
Route::get( 'admin/register', 'Auth\StaffRegisterController#showRegistrationForm' );
Route::post( 'admin/register', [ 'as' => 'staff.register', 'uses' => 'Auth\StaffRegisterController#register' ] );
Route::group( [ 'middleware' => [ 'staff' ] ], function() {
Route::get( '/admin', 'AdminController#index' )->name( 'admin' );
});
});
Route::get('/home', 'HomeController#index')->name('home');
I've tried various route definitions but this is the latest iteration. None of the previous iterations worked either.
My auth file:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'staff' => [
'driver' => 'session',
'provider' => 'adminusers',
]
],
'providers' => [
'users' => [
'driver' => 'doctrine',
'model' => App\Users\Customer::class,
],
'adminusers' => [
'driver' => 'doctrine',
'model' => App\Users\Staff::class,
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'adminusers' => [
'provider' => 'adminusers',
'table' => 'password_resets',
'expire' => 30,
],
],
My LoginController (basically same as out of the box):
class LoginController extends Controller {
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct() {
$this->middleware('guest')->except('logout');
}
}
My StaffLoginController:
<?php
class StaffLoginController extends Controller {
use AuthenticatesUsers;
protected $redirectTo = '/admin';
protected $guard = 'staff';
public function __construct() {
$this->middleware( 'guest' )->except( 'logout' );
}
public function showLoginForm() {
return view( 'auth.staff.login' );
}
public function login( Request $request ) {
$this->validate( $request, [
'email' => 'required|email',
'password' => 'required',
]);
if( auth()->guard( 'staff' )->attempt( [
'email' => $request->input( 'email' ),
'password' => $request->input( 'password' ),
])) {
return view( 'staff' );
} else {
return view( 'auth.staff.login' )->withErrors( [ 'email' => 'Authentication failed' ] );
}
}
protected function guard() {
return \Auth::guard( 'staff' );
}
}
My AdminController:
class AdminController extends Controller {
public function __construct() {
$this->middleware( 'auth:staff' );
}
public function index() {
return view( 'staff' );
}
}
My RedirectIfStaffUnauthenticated middleware (which is registered in Http\Kernel.php routeMiddleware as 'staff' => \SNJ\Http\Middleware\RedirectIfStaffUnauthenticated::class, ):
class RedirectIfStaffUnauthenticated {
public function handle( $request, Closure $next, $guard = 'staff' ) {
if ( !Auth::guard( $guard )->check() ) {
return view( 'auth.staff.login' );
}
return $next( $request );
}
}
UPDATE:
Changed routes in web.php to be as thus (removed the middleware from the admin/login and admin/register routes:
Auth::routes();
// staff authentication routes
Route::get( 'admin/login', 'Auth\StaffLoginController#showLoginForm' );
Route::post( 'admin/login', [ 'as' => 'staff.login', 'uses' => 'Auth\StaffLoginController#login' ] );
Route::get( 'admin/register', 'Auth\StaffRegisterController#showRegistrationForm' );
Route::post( 'admin/register', [ 'as' => 'staff.register', 'uses' => 'Auth\StaffRegisterController#register' ] );
Route::group( [ 'middleware' => [ 'staff' ] ], function() {
Route::get( '/admin', 'AdminController#index' )->name( 'admin' );
});
Route::get('/home', 'HomeController#index')->name('home');
No change. Still doesn't work.
Tried changing routes thusly (put all admin routes into 'staff' middleware:
Auth::routes();
// staff authentication routes
Route::group( [ 'middleware' => [ 'staff' ] ], function() {
Route::get( 'admin/login', 'Auth\StaffLoginController#showLoginForm' );
Route::post( 'admin/login', [ 'as' => 'staff.login', 'uses' => 'Auth\StaffLoginController#login' ] );
Route::get( 'admin/register', 'Auth\StaffRegisterController#showRegistrationForm' );
Route::post( 'admin/register', [ 'as' => 'staff.register', 'uses' => 'Auth\StaffRegisterController#register' ] );
Route::get( '/admin', 'AdminController#index' )->name( 'admin' );
});
Route::get('/home', 'HomeController#index')->name('home');
Same same. Still doesn't work.
Change your StaffLoginController to this,
<?php
class StaffLoginController extends Controller {
use AuthenticatesUsers;
public function showLoginForm() {
return view( 'auth.staff.login' );
}
public function login( Request $request ) {
$this->validate( $request, [
'email' => 'required|email',
'password' => 'required',
]);
if( auth()->guard( 'staff' )->attempt( [
'email' => $request->input( 'email' ),
'password' => $request->input( 'password' ),
])) {
return view( 'staff' );
} else {
return view( 'auth.staff.login' )->withErrors( [ 'email' => 'Authentication failed' ] );
}
}
}
remove constructor from AdminController, we are later going to call this middleware on routes.
class AdminController extends Controller {
public function index() {
return view( 'staff' );
}
}
You don't need to pass the guard value to auth middleware since you already defined as second middleware for authenticating admin routes.
update your staff middleware like this.
class RedirectIfStaffUnauthenticated {
public function handle( $request, Closure $next, $guard = null ) {
if ( Auth::guard( $guard )->check() ) {
if(! $guard == 'staff')
{
return redirect()->route( 'staff.login.form' );
}
}else return redirect()->route( 'staff.login.form' );
return $next( $request );
}
}
Now update your routes.
Route::get( 'admin/login', 'Auth\StaffLoginController#showLoginForm' );
Route::post( 'admin/login', [ 'as' => 'staff.login.submit', 'uses' => 'Auth\StaffLoginController#login' ] );
Route::get( 'admin/register', 'Auth\StaffRegisterController#showRegistrationForm' );
Route::post( 'admin/register', [ 'as' => 'staff.register.submit', 'uses' => 'Auth\StaffRegisterController#register' ] );
Route::group( [ 'middleware' => [ 'staff' ] ], function() {
Route::get( '/admin', 'AdminController#index' )->name( 'admin' );
});
Also add the following lines to your unauthenticated function in Handler.php file in app\Exceptions
$guard = array_get($exception->guards(), 0);
switch ($guard) {
case 'staff':
$login = 'admin/login';
break;
case 'users':
$login = 'login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route('login'));
Please check your app/Kernel.php, you can see that guest is an alias for app/Http/Middleware/RedirectIfAuthenticated.php middleware.
You don't need to call constructors on both web.php file and on the controllers constructor.
Here the RedirectIfStaffUnauthenticated middleware checks the root /admin is authenticated and it has a guard value of staff, if not it will redirect to the /admin/login route.
Please read laravel doc for clarification
Hope this helps.
I am somewhat new to Laravel.
I have created a form, submitted it for authorisation but then I am told (by Firefox) the routing will never complete. I know the login has worked as I intercepted it.
Here is my routes.php:
Route::get('/',function()
{
return view('welcome');
})->name('home');
Route::get('/welcome', function () {
return view('welcome');
});
Route::post('/signin',
[
'uses' =>'UserController#postSignIn',
'as' => 'SignIn'
]);
Route::get('/dashboard',
[
'uses' => 'UserController#getDashboard',
'as' => 'DashBoard',
'middleware' => 'auth'
]);
Route::get('/logout',
[
'uses' => 'UserController#getLogout',
'as' => 'Logout'
]);
and here is the UserController:
class UserController extends Controller
{
public function postSignIn(Request $request)
{
$this->validate($request,
[
'email' => 'required | email',
'password' => 'required'
]);
if (Auth::attempt([ 'email' => $request['email'], 'password' =>$request['password'] ]) )
{
//exit("authorised");
$message = "you are now logged in";
return redirect()->route('DashBoard')->with(['successmessage' =>$message]);
}
else
{
$message = "username\password combination not correct";
//exit('not - email = '.$request['email'].' password = '. $request['password']);
return redirect()->back()->with(['errormessage' => $message] );
}
}
public function getLogout()
{
Auth::logout();
return redirect()->route('home');
}
public function getDashboard()
{
return redirect()->route('DashBoard');
}
}
As can be seen by what is commented out the authorisation is OK
But I get this from Firefox
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Just use to() in your return as
return redirect()->to('DashBoard')->with(['successmessage' =>$message]);
add this to your route
Route::get('/signin',
[
'uses' =>'UserController#postSignIn',
'as' => 'SignIn'
]);