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'
]);
Related
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
}
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 building a login page for the user in which one can sign up by filling the sign up form or can login with facebook.
Login with facebook is working fine and is routing to the user's profile page whereas when one logins after registering on the site ,error occurs stating that "route[myplace] not defined which is working in case of login with facebook.
My routes.php file:
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/signup' , [
'uses' => 'UserController#postSignUp' ,
'as' => 'signup'
]);
Route::post('/signin' , [
'uses' => 'UserController#postSignIn' ,
'as' => 'signin'
]);
Route::get('/myplace' , [
'uses' => 'UserController#getmyplace' ,
'as' => 'myplace' ,
'middleware' => 'auth:web'
])->name('myplace');
Route::get('/verify' , [
'uses' => 'UserController#getverify' ,
'as' => 'verify'
]);
Route::get('login', 'Auth\AuthController#redirectToFacebook');
Route::get('login/callback', 'Auth\AuthController#getFacebookCallback');
my postSignIn function in UserController.php:
public function postSignIn(Request $request)
{
$this->validate($request,[
'email'=> 'required' ,
'password' => 'required'
]);
if(Auth::attempt(['email'=>$request['email'], 'password' => $request['password']]))
{
return redirect()->route('myplace');
}
return redirect()->back();
}
Actually,I was using same route for different controllers.So ,i just copied my myplace function from UserController.php to AuthController.php and it worked.
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.
When I submit my user credentials instead of lining in form tries to register me as new user.
here is my controller:
public function postCreate() {
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes()) {
$user = new User;
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::route('home')->with('message', 'Thanks for registering');
} else {
return Redirect::route('register')->withErrors($validation)->withInput();
}
}
public function getLogin() {
return View::make('users.login')->with('title', 'Project - Login');
}
public function postLogin()
{
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
$validator = Validator::make($user, User::$rules);
if ($validator->passes()) {
if (Auth::attempt($user)) {
return Redirect::to('home');
}
else
{
return Redirect::to('login')->withErrors($validator)->withInput();
}
}
return Redirect::to('login')->withErrors($validator)->withInput();
}
and route :
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#showIndex'));
Route::get('register', array('as' => 'register', 'uses' => 'UsersController#getNew'));
Route::get('login', array('as' => 'login', 'uses' => 'UsersController#getLogin'));
Route::post('register', array('before' => 'csrf', 'uses' => 'UsersController#postCreate'));
Route::post('login', array('before' => 'csrf', 'uses' => 'UsersController#postLogin'));
Error when I attempt login :
The username has already been taken.
The password confirmation does not match.
I have used this code before and it worked, but what is the problem now, I don't know.
You don't need to confirm password for the login $rules array.
$rules = array(
'username' => 'required|email|exists:users',
'password' => 'required',
);
This should work for the postLogin validation rules.