hi im trying to make a good user auth form but i ve have had some problems , so first i tried this :
Route::get('login', function()
{
/* Get the login form data using the 'Input' class */
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
/* Try to authenticate the credentials */
if(Auth::attempt($userdata))
{
// we are now logged in, go to admin
return Redirect::to('home');
}
else
{
return Redirect::to('login');
}
});
and this is the form blade page :
{{ Form::open(array('url' => 'login', 'class' => 'form-horizontal')) }}
<div class="control-group">
<label class="control-label" for="username"></label>
<div class="controls">
<input id="username" name="username" type="text" placeholder="" class="input-xlarge" required="">
</div>
</div>
<!-- Password input-->
<div class="control-group">
<label class="control-label" for="password"></label>
<div class="controls">
<input id="password" name="password" type="password" placeholder="" class="input-xlarge" required="">
</div>
</div>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="submit"></label>
<div class="controls">
<button id="submit" name="submit" class="btn btn-inverse"></button>
</div>
</div>
</fieldset>
and it gave me the redirect loop error
and then i tried this :
Route::get('login', function()
{
/* Get the login form data using the 'Input' class */
$user = new User;
$log = array(
$user -> username = Input::get('username'),
$user -> password = Input::get('password')
);
/* Try to authenticate the credentials */
if(Auth::attempt($log))
{
// we are now logged in, go to admin
return Redirect::to('home');
}
else
{
return Redirect::to('login');
}
});
and it gives me :
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `users` where `0` is null and `1` is null limit 1)
does anyone knows whats the problem?
first code should have worked perfectly but why redirect error?
Firstfully, change your route names, to:
Route::get('login', function(){}); And Route::get('sign-in', function(){});
Get auth page:
Route::get('login', function()
{
return View::make('your-auth-view');
}
And your sign-in handler should looks like:
Route::get('sign-in', function(){
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::attempt($userdata))
{
// we are now logged in, go to admin
return Redirect::to('home');
}
else
{
return Redirect::to('login');
}
});
And form will change to:
{{ Form::open(array('url' => 'sign-in', 'class' => 'form-horizontal')) }}
P.S. You have a redirect loop, because, you have a two the same routes, and when you submit the form you redirect to login page again and again
If you are using Laravel 4.2 and still have issues after adding
{{ Form::token() }} or
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
Then you can try changing the filter.php file in app directory by adding
Request::getMethod() !== 'GET' on your filter.
Route::filter('csrf', function()
{
if (Request::getMethod() !== 'GET' && Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
This has been useful to me too.
Related
I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.
I have a problem with the login when I try to log in it says the page has expired due to inactivity.I am using middleware to check role based on user login and it seems it's not working. When ever try to login the page has expired message popups.
Route:
Route::get('/', function () {
return view('login');
});
Route::get('/dashboard/{user_id}', ['as' => 'dashboard', function ($user_id) {
return view('theme.index')->with(['id'=>$user_id]);
}]);
Route::post('login', 'AuthController#postSignIn')->name('login');
AuthController:
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user=DB::table('users')->where([['username', '=', $request['username']],['status','=','0']])->first();
$user_id=$user->user_id;
return redirect()->route('dashboard',$user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Middleware:
public function handle($request, Closure $next)
{
if ($request->user() === null) {
// return response("Insufficient permissions", 401);
return response(view('error'),401);
}
$actions = $request->route()->getAction();
$roles = isset($actions['roles']) ? $actions['roles'] : null;
if ($request->user()->hasAnyRole($roles) || !$roles) {
return $next($request);
}
// return response("Insufficient permissions", 401);
return response(view('error'),401);
}
}
Index:
<form class="form-horizontal" action="{{ route('login') }}" method="post">
{{ csrf_token() }}
<div class="form-group m-b-20 row">
<div class="col-12">
<label for="emailaddress">Username</label>
<input class="form-control" type="text" id="username" required="" placeholder="Enter Username">
</div>
</div>
<div class="form-group row m-b-20">
<div class="col-12">
<label for="password">Password</label>
<input class="form-control" type="password" required="" id="password" placeholder="Enter your password">
</div>
</div>
<div class="form-group row text-center m-t-10">
<div class="col-12">
<button class="btn btn-md btn-block btn-primary waves-effect waves-light" type="submit">Login</button>
</div>
</div>
</form>
You can change the session lifetime in Laravel config inside config/session.php by modifying following value
lifetime
also you will need to run
php artisan config:cache
for Laravel to pick new configurations.
I had figured it out i did it from scratch it was the problem of Auth function
The import Auth before that i did run two commands to clear my cache
php artisan cache:clear
php artisan config:cache
and import Auth
Thank you for the help guys appreciate it
add your route in $except array of VerifyCsrfToken.php middleware like this $except = [ "/login" ]; .
open VerifyCsrfToken.php middleware and put in except your url like :
protected $except = [
'http://localhost:8000/login'
];
and can see laravel docs for more information about csrf
https://laravel.com/docs/5.6/csrf#csrf-excluding-uris
I have login form with two text fields email, password.when I tried to login with credentails it's working fine but when clear cache and then tried to login it gives the 'MethodNotAllowedHttp' exception.I am not getting the issue why it's showing this error. My code is as follows:
Route::post('users/login/5', 'administrator\usersController#login')->name('sl');
usersController.php
namespace App\Http\Controllers\administrator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Validator;
use Session;
class FreeusersController extends Controller {
function login(Request $request) {
$type = $request->segment(3);
//print_r($request);
echo "type=".$type;
echo $request->input('email');
echo $request->input('password');
die("sss");
if ($request->isMethod('post') && !empty($type)) {
$this->validate($request, [
'email' => 'required|min:5,max:50',
'password' => 'required|min:5,max:50'
]);
switch ($type) {
case 5:
$condArr = ['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => '5', 'role' => 'father'];
break;
case 4:
$condArr = ['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => '4', 'status' => true];
break;
}
if (Auth::attempt($condArr)) {
return redirect('administrator/dashboard');
} else {
return redirect(url()->previous())->withErrors(['password' => 'Invalid credentials'])->withInput();
}
} else {
return redirect("/");
}
}
}
<form action="/users/login/5" id="login-form" method="post" class="smart-form client-form">
{{ csrf_field() }}
<fieldset>
<section>
<label class="label">Email</label>
<label class="input"> <i class="icon-append fa fa-user"></i>
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}">
</section>
<section>
<label class="label">Password</label>
<label class="input"> <i class="icon-append fa fa-lock"></i>
<input id="password" type="password" class="form-control" name="password">
</section>
</fieldset>
<footer>
<button type="submit" class="btn btn-primary">
LogIn
</button>
</footer>
</form>
You have to clear routes:
php artisan route:cache
Then it will remember that login action is post.
I think you are getting this error because you when you are calling this url there is another url with something like users/{id} which means anything after users/. May be you are using resource route. So, when you call url users/login/5 its taking login/5 as $id of that users/{id} url.
But that url is for GET method. You are calling this with post method, as a result you are getting this error.
Solution
You can try calling your url using route method like:
action="{{route('sl', ['id'=>5])}}"
If it doesn't work then you can change your route to something else. For example:
Route::post('user/login/5', 'administrator\usersController#login')->name('sl');
Here you can use user instead of users because you already have a url with a users. Don't forget to change your action too.
First look at your routes with php artisan route:list.
Then are you sure of your request verb ? Look in your navigator console to look at your requests.
I have a number of php files in my project:
admin.blade.php: this files contains the admin form.
When called it show the following error:
MethodNotAllowedHttpException in RouteCollection.php line 201
<h2>Please Log In To Manage</h2>
<form id="form1" name="form1" method="post" action="<?=URL::to('/admin')?>">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
User Name:<br />
<input name="username" type="text" id="username" size="40" />
<br /><br />
Password:<br />
<input name="password" type="password" id="password" size="40" />
<br />
<br />
<br />
<input type="submit" name="button" id="button" value="Log In" />
</form>
In route.php, this call is made:
Route::get('/admin',array('uses'=>'student#admin'));
This is the function in student.php
public function admin()
{
return View::make('student.admin');
$validator = Validator::make($data = Input::all() , User::rules());
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
else
{
$check = 0;
$check = DB::table('admin')->get();
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(['username' => $username, 'password' => $password]))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput()->withErrors('That username/password combo does not exist.');
}
}
I don't know much about creating an admin area, I am just trying to create it.
This is how I do it.
Routes.php
Route::get('/admin', 'UsersController#getAdminLogin');
Route::get('/admin/dashboard', 'UsersController#dashboard');
Route::post('/admin', 'UsersController#postAdminLogin');
admin_login.blade.php
{!! Form::open(['url' => '/admin']) !!}
<div class="form-group">
{!! Form::label('email', 'Email Id:') !!}
{!! Form::text('email', null, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
</div>
{!! Form::close() !!}
dashboard.blade.php
<h4 class="text-center">
Welcome {{ Auth::user()->full_name }}
</h4>
UsersController.php
/**
* Display the admin login form if not logged in,
* else redirect him/her to the admin dashboard.
*
*/
public function getAdminLogin()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return redirect('/admin/dashboard');
}
return view('admin_login');
}
/**
* Process the login form submitted, check for the
* admin credentials in the users table. If match found,
* redirect him/her to the admin dashboard, else, display
* the error message.
*
*/
public function postAdminLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email,role,admin',
'password' => 'required'
]);
$credentials = $request->only( 'email', 'password' );
if(Auth::attempt($credentials))
{
return redirect('/admin/dashboard');
}
else
{
// Your logic of invalid credentials.
return 'Invalid Credentials';
}
}
/**
* Display the dashboard to the admin if logged in, else,
* redirect him/her to the admin login form.
*
*/
public function dashboard()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return view('admin.dashboard');
}
return redirect('/admin');
}
Your Code:
In routes.php, you have only 1 route, i.e.,
Route::get('/admin',array('uses'=>'student#admin'));
And there is no declaration of post method, hence, the MethodNotAllowedHttpException
Also, in your controller, you are returning the view first and then processing the form which is not going to work at all. You first need to process the form and then return the view.
public function admin(){
// Won't work as you are already returning the view
// before processing the admin form.
return \View::make(students.admin);
// ...
}
As #Sulthan has suggested, you should use Form Facade. You can check out this video on Laracasts about what Form Facade is and how you should use it.
You're using post method in the form but you're having get method in the routes.
So, Change the method to post in your routes
Note :
I recommend you to make use of the default form opening of Laravel like the below given which is always the best practise
{!! Form::open(array('url' => 'foo/bar')) !!}
{!! Form::close() !!}
Tips :
Read more on here and try to debug such things by comparing the methods and routes.
Form facade is not included in laravel 5 by default. You shall install it by
composer require "illuminate/html":"5.0.*"
and updating in the app.php.
I have written a blog which gives a breif about this installation.
In Routes web.php
Your code is
Route::get('/admin',array('uses'=>'student#admin'));
which is wrong.
Actually submitting data in POST method its array of data so you need to route through post instead of get.
so correct code is
Route::post('/admin',array('uses'=>'student#admin'));
Follow this tutorial form Laracast it might helpful,
https://laracasts.com/series/laravel-from-scratch-2017/episodes/16
In routes.php, replace Route::get by Route::post.
You have no post route for your form data posting , use route match function for both http verb (get & post). use this
Route::match(['get', 'post'], '/admin', 'student#admin');
Also you need to change your admin method,
public function admin(Request $request){
if($request->isMethod('get')){
return \View::make('student.admin');
} else {
// your validation logic
}
}
I have 3 user types :
Admin
Distributor
Internal
I have a problem sign in as user type. ( Internal )
I can sign in when my user type is Admin.
I can sign in when my user type is Distributor.
BUT I can’t sign in when my user type is internal. Wired ????
I look through every single line of my code in my sign-in functions in my AccountController.php.
I didn’t notice any bug there. If you guys notice any bugs there -- please kindly let me know.
That will be a huge help for me.
Here is my Sign-In Functions
GET
public function getSignIn(){
return View::make('account.signin');
}
POST
public function postSignIn() {
$validator = Validator::make( Input::only('username','password'),
array(
'username' =>'required',
'password' =>'required'
)
);
if ($validator->fails()) {
return Redirect::route('account-sign-in-post')
->with('error','Username/Password Wrong or account has not been activated !')
->withErrors($validator);
}
// Remember Me
$remember = (Input::has('remember')) ? true : false ;
$auth = Auth::attempt(array(
'username' => strtolower(Input::get('username')),
'password' => Input::get('password'),
'active' => 1),
$remember);
// Keep track on log-in information of the user.
if(Auth::check()){
$user = Auth::user();
$user->last_logged_in = Input::get('created_at');
$user->logged_in_count = $user->logged_in_count + 1 ;
$user->is_online = '1';
$user->save();
}
if($auth) {
return Redirect::to('/')
->with('success','You have been successfully logged in.')
;
}
else {
return Redirect::route('account-sign-in')
->with('error','Username/Password Wrong or account has not been activated !')
->withInput(Input::except('password'))
->withErrors($validator);
}
}
VIEW
#extends ('layouts.form')
#section('content')
<style type="text/css">
.signin{
text-align: center;
}
#forgetpassword{
/*color:#5cb85c;*/
color:silver;
}
</style>
<form class="form-horizontal" role="form" action=" {{ URL::route('account-sign-in-post')}}" method="post" >
#if ($errors->has('username')){{ $errors->first('username')}} #endif
<div class="form-group">
<label for=""> Email </label>
<input placeholder="Email" type="text" class="form-control" required name="username" {{ ( Input::old('username')) ? 'value="'.e(Input::old('username')).'"' : '' }}>
</div><br>
#if ($errors->has('password')){{ $errors->first('password')}} #endif
<div class="form-group">
<label for=""> Password </label>
<input placeholder="Password" type="password" class="form-control" required name="password">
</div><br>
<br>
<button type="submit" class="btn btn-success btn-sm btn-block ">Sign In </button>
{{ Form::token() }}
</form><br>
<div class="col-lg-12 text-center">
<a id="forgetpassword" href="{{ URL::route('account-forgot-password') }}"> Forget Password </a> <br>
</div>
#stop
I am sure that I typed in the right username and password because I double check with my database.
It keep redirecting me back to my sign-in page.
with('error','Username/Password Wrong or account has not been activated !')
Can someone please tell me, if I did anything that I’m not suppose to ?
In your situation, you should check your auth variable in your Sign_In Function.
According to your code,
$auth = Auth::attempt(array(
'username' => strtolower(Input::get('username')),
'password' => Input::get('password'),
'active' => 1),
$remember);
Keep in mind that, these are things need to make sure
username must match the database
password must match the database
user active must be 1
If any of these fail, therefore, it STOP you from signing in.
Since, you're so sure about username and password, what about user active ?
Did you check to if it's 1 ?
If Not
on your set-password function or anywhere, where you normally set your user active.
just do this :
$user->active = '1';
$user->save();
Let me know if this work!!