How to create a laravel 5.5 custom auth? - laravel

I created a custom Auth controller in Laravel 5.5 with the action "store" inside it, then I authenticated it using the $auth->attempt() method that returns true. So far so good, the problem starts when I try to use the "auth" middleware for my panel routes, the authentication middleware always redirects to the login action.
Routes:
Route::group(['middleware' => ['auth', 'web']], function () {
Route::get('/painel/', ['as' => 'painel.dashboard', 'uses' => 'DashboardController#index']);
});
Route::get('/login', ['middleware' => 'web', 'as' => 'login', 'uses' => 'AuthController#index']);
Route::group(['middleware' => ['web']], function () {
Route::get('/painel/auth', ['as' => 'painel.auth.index', 'uses' => 'AuthController#index']);
Route::post('/painel/auth/store', ['as' => 'painel.auth.store', 'uses' => 'AuthController#store']);
});
Controller:
namespace App\Applications\Painel\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Auth\AuthManager as Auth;
class AuthController extends BaseController
{
/**
* #var Guard
*/
private $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function index()
{
return view('painel::auth.index');
}
public function store(Request $request)
{
$data = $request->only(['email', 'password']);
// This condition always return true, but after Laravel return to action index...
if ($this->auth->attempt($data)) {
return redirect()->route('painel.dashboard');
}
return redirect()->back();
}
}
auth.index:
<!doctype html>
<html lang="pt_BR">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Admin</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="row">
<div class="col-sm-12 col-md-12">
<h2 class="text-center">Admin</h2>
<hr>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-2 col-md-offset-5 col-sm-offset-4">
<form action="{{ route('painel.auth.store') }}" method="post" id="login-form">
{!! csrf_field() !!}
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Senha</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Senha">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg btn-block" name="submit" id="submit">Entrar</button>
</div>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

The attempt method needs the $request as parameter or you'll need to include the remember token in $data. The guard is missing the remember token, I think.

Related

Laravel: Login system problem for learning

I'm trying to make a login for learning, so I followed a video from youtube with the same coding. It should be able to check the format of the inputted data, check whether user already login or not, check whether user accessing the next page wihthout login, but in the end, it will always only showed email and password required errors even if I already inputted the right input. Please help. Here are my codes.
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/main', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/successlogin', 'MainController#successlogin');
Route::get('main/logout', 'MainController#logout');
login.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<!--CSS-->
<link rel="stylesheet" href="{{ asset('css/styles.css') }}" type="text/css">
<link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' />
<script type="text/javascript" src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
</head>
<body>
<div class="login-page-frame">
<div class="header-login-page-frame">
<h3>Login</h3>
</div>
<div class="inner-login-form-frame">
#if(isset(Auth::user()->email))
<script>window.location="/main/successlogin";</script>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert"></button>
<strong>{{$message}}</strong>
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('/main/checklogin') }}" class="login-form">
{{ csrf_field() }}
<input type="email" placeholder="email" name="login-email" class="form-control">
<br>
<input type="password" placeholder="pass" name="login-password" class="form-control">
<br>
<input type="submit" name="login" class="btn-login" value="login">
</form>
</div>
</div>
</body>
</html>
halamanUtama.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Halaman Utama</title>
</head>
<body>
<div class="container box">
<h3 align="center">Selamat Datang</h3>
<br />
#if(isset(Auth::user()->email))
<div class="alert alert-danger success-block">
<strong>Welcome {{ Auth::user()->email }}</strong>
<br />
Logout
</div>
else
<script>window.location="/main";</script>
#endif
</div>
</body>
</html>
MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use Input;
class MainController extends Controller
{
//
function index(){
return view('login');
}
function checklogin(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data=array(
'email' => $request->get('login-email'),
'password' => $request->get('login-password')
);
if(Auth::attempt($user_data)){
return redirect('main/successlogin');
}else{
return back()->with('error', 'Wrong Login Details');
}
}
function successlogin(){
return view('halamanUtama');
}
function logout(){
Auth::logout();
return redirect('main');
}
}
I won't comment on whether any of your other code works, but the cause of your validation errors is that the name of your form inputs does not match the name of the fields you are trying to validate.
In your form, your inputs are called login-email and login-password. However, in your controller, you are validating that a field called email and a field called password are provided (because they are required).
So either change your form names to email and password or change your validation fields to login-email and login-password.

How to use CSRF token in codeigniter with Ajax Post data in database with giving 403 Error..?

* While posting data in database in codeigniter first time my data is post to database , but when second time i am try to post data in database then it give me 403 ERROR .First Time code is work ,when second time i am post it give me 403 error data is not post or save in my database. *
View Page Code :
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h2>Register</h2>
<!-- <form id="saveEmpForm"> -->
<?php
$attributes = array('id' => 'saveEmpForm');
echo form_open('register/insert', $attributes);
?>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
</div>
<button type="submit" class="btn btn-primary" id="btn_add">Submit</button>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
<script type="text/javascript">
var csrf_token = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<script type="text/javascript">
$('#saveEmpForm').submit('click',function(){
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>register/insert",
dataType : "JSON",
data : {name:name, email:email, password:password, csrf_test_name: csrf_token},
success: function(response){
$('#name').val("");
$('#email').val("");
$('#password').val("");
alert('Success');
}
});
return false;
});
</script>
</body>
</html>
Controller code:
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('register_model');
}
public function index()
{
$this->load->view('register_view');
}
public function insert(){
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result=$this->register_model->insert_data($data);
echo json_encode($data);
}
}
Model Code :
class Register_model extends CI_Model{
public function insert_data($data)
{
$this->db->insert('emp',$data);
return $this->db->insert_id();
}
}
?>```

The email field is required but no input email in view Laravel

I keep getting this error message:
The email field is required.
But I don't have any input type with a name of email in my view:
Login
<link rel="shortcut icon" href="{{ asset('img/logo.png') }}" type="image/x-icon">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}">
<link rel="stylesheet" href="{{ asset('css/feather.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
<link rel="stylesheet" href="{{ asset('css/jquery.mCustomScrollbar.css') }}">
</head>
<body>
<section class="login-block">
<div class="container">
<div class="row">
<div class="col-md-12">
<form action="/login" method="post" class="md-float-material form-material">
#csrf
<div class="auth-box card">
<div class="card-block">
<div class="row m-b-20">
<div class="col-md-12">
<h3 class="text-center">Members Management System</h3>
</div>
</div>
#if ($errors)
<div class="alert alert-danger background-danger">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="icofont icofont-close-line-circled text-white"></i>
</button>
#foreach ($errors->all() as $error)
- {{ $error }}
<br>
#endforeach
</div>
#endif
<div class="form-group form-primary">
<input type="text" name="employee_id" class="form-control" required=""
placeholder="Employee ID">
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="password" name="password" class="form-control" required=""
placeholder="Password">
<span class="form-bar"></span>
</div>
<div class="row m-t-30">
<div class="col-md-12">
<button type="submit"
class="btn btn-primary btn-md btn-block waves-effect waves-light text-center m-b-20">
SIGN IN
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/jquery-ui.min.js') }}"></script>
<script src="{{ asset('js/script.js') }}"></script>
</body>
</html>
I don't understand why the $errors is notifying me of error regarding email. Any suggestions? I didn't modify any default AUTH settings from Laravel. It may seem that the error is coming from other source?
EDIT:
Thanks for suggesting to override the username() in my LoginController by:
public function username()
{
return 'employee_id';
}
Is this the most conventional and preferred way to do this? Thank you for the assist.
AuthenticatesUsers is responsible for validating the data after the user submitted the form. If you take a look at this file, you will see this method:
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
More specifically, as you can see, this method is in charge for calling the validator on the fields name "password" and by the method username(). If you only wanted to custom the username field, you could overwrite the username() method in LoginController class:
public function username()
{
return 'employee_id';
}
But since you want to custom both the username field name and the password field name, I suggest that you overwrite the validateLogin() method in the LoginController class:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'employee_id' => 'required|string',
'user_password' => 'required|string',
]);
}
Hope that helps.
You can refer employee_id, as username, on login.
Now, open LoginController, and add the username() method.
public function username() {
return "username";
}
Now, you can login without e-mail address.

Validation not working in laravel 5.5

I installed a new Laravel 5.5 app and created a form in test.blade.php view:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action={{ route('contact') }}>
{{ csrf_field() }}
<input type="text" name="title">
<input type="text" name="body">
<input type="submit" value="click">
</form>
</body>
</html>
and created my PageController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Pagecontroller extends Controller
{
public function index(Request $request){
$this->validate($request,[
'title' => 'required',
'body' => 'required',
]);
return View('View');
}
}
and in the web.php add my routes:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/test',function(){
return View('test');
});
Route::post('/contact',['uses'=>'PageController#index','as'=>'contact']);
My problem is when I submit the form with or without data nothing happen and the page just reload and when I remove the validation code:
$this->validate($request,[
'title' => 'required',
'body' => 'required',
]);
it return the requests I can't understand what is the problem because I tested it before and it was working in Laravel 5.4. Can any one help me?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Pagecontroller extends Controller
{
public function index(Request $request){
$request->validate([
'title' => 'required',
'body' => 'required',
]);
return View('View');
}
}
And your view code should be:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="POST" action={{ route('contact') }}>
{{ csrf_field() }}
<input type="text" name="title">
<input type="text" name="body">
<input type="submit" value="click">
</form>
</body>
</html>

How to create a user login in Laravel 5.2?

I am using laravel 5.2. I want to create a user login.
I will give my model, view and controller files. I want to create a user login page.
I used below given view, model, controller but I get the error:
Sorry, the page you are looking for could not be found.
NotFoundHttpException in RouteCollection.php line 161:
Please help me to create a user login page in laravel 5.2.
model file
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserLogin extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
use Authenticatable, CanResetPassword;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [ 'username','password'];
}
view file
<!DOCTYPE html>
<html lang="en">
<head>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<title>#section('title') Cable #show</title>
#section('meta_keywords')
<meta name="keywords" content="MCC Hostel"/>
#show #section('meta_author')
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="cleartype" content="on" />
#show #section('meta_description')
<meta name="description" content="MCC Hostel"/>
#show
{!! Assets::css() !!}
#yield('styles')
</head>
<body id="login-page">
<div class="container">
<div class="content">
<div id="home" class="content has-bg home">
<div class="container home-content">
#include('utils.errors.list')
<div class="logo-img-login text-center"> <big>Cable</big></div>
<form class="form col-sm-6 col-sm-offset-3 col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4" role="form" method="POST" action="{{ URL::to('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label">Email</label>
<input type="text" class="form-control" name="username" value="{{ old('email') }}">
</div>
<div class="form-group">
<label class="control-label">Password</label>
<input type="password" class="form-control" name="password">
</div>
<div class="form-group">
<div class="">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="">
<button type="submit" class="btn btn-primary" style="margin-right: 15px;">
Login
</button>
<a class="hide" href="{{
URL::to('/password/email') }}">Forgot Your Password?</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{!! Assets::js() !!}
#yield('scripts')
</body>
</html>
controller file
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserLoginController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
protected $redirectPath = 'admin/dashboard';
protected $username = 'username';
protected function validator(array $data) {
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
$data = User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
Mail::send('emails.welcome', ['name' => $data['name']], function ($m) use ($data) {
$m->to($data['email'], $data['name'])->subject('Thank you for registering!')->from('admin#alumni.mescampusschool.edu.in', 'Admin MES school campus');
});
Session::flash('flash_notification', array('level' => 'success', 'message' => 'Your account has been regsitered please check your mail'));
return $data;
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request) {
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->confirmed) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'You must confirm your payment first to login '
]);
}
}
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
}
You receive a NotFoundHttpException. This means that you probably forgot to define a matching route.
Go into your app/http/routes.php file and define your routes there - e.g. :
Route::get('/login', 'Authcontroller#login'); // if you have this function in your controller
or like
Route::get('/login', function() {
return view('auth.login'); // if you have your login view placed in the auth folder of your view resources
});
The MOST EASY way to get a working login system in laravel is to use the command
php artisan make:auth
But BE AWARE of the following: This might overwrite existing files (if you have an existing Authcontroller for example or an app layout in views/layouts/app.blade.php ).
Usually this should be the first command you run after setting up a new laravel application if you want the default login behavhiour.
Dont forget to call php artisan migrate and ofcrouse define your .env variables correctly to ensure a working database connection.

Resources