How to make custom auth in laravel 5.3 - php

I'm facing problem in my Laravel 5.3 custom auth want to use my own functions or pages when I check Auth::check() it returns false.
Here is User controller:
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Session;
use validatior;
use Auth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$user = new User();
$user->email = $request->get("email");
$user->password = bcrypt($request->get['password']);
$user->save();
}
return redirect('signupPage');
}
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect('users/profile');
}
dd(Auth::check());
exit;
}
}
After sign in I want to redirect at profile page but my condition is not working. My routes are:
Route::group(['prefix' => 'users'], function(){
Route::group(['middleware' => 'guest'], function(){
Route::get('/signupPage','UserController#getSignUp');
Route::post('/register',array ('as'=>'signup', 'uses' =>'UserController#postSignUp', ));
Route::get('signInPage', array('as' => 'signInPage', 'uses' => 'UserController#getSignIn'));
Route::post('/postLogin', array('as' => 'postLogin', 'uses' => 'UserController#postSignIn'));
});
Route::group(['middleware' => 'auth'], function(){
Route::get('/profile', array('as' => 'profile', 'uses' => 'UserController#getProfile'));
Route::get('/logout', array('as'=>'logout', 'uses'=> 'UserController#logout'));
});
});

Here are some Modifications of your code
public function postSignUp(Request $request)
{
$email = $request->input('email');
$pass = $request->input('password');
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$pas = bcrypt($pass);
$user = new User();
$user->email = $email;
$user->password = $pas;
$user->save();
}
return redirect('users/signInPage');
}
Do use bcrypt while registering your User as this function is by default used by Auth Attempt function
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$email= $request->input['email'];
$password= $request->input['password'];
if (Auth::attempt(['email'=>$email,'password'=>$password']))
{
return redirect('users/profile');
}
return redirect('users/signInPage')->withErrors(['failure' => 'The credentials you entered did not match our records. Try again!',]);
}
finally this will give you too many redirects error as you using default middlewares, because your logic is now differ from the default one that's why you have to write your custom middleware, for this run this command
php artisan make:middleware CutomAuth
this will create your custom middleware now write code in it by your logic and after registering in app/Http/Kernel.php as \n
'customauth' => \Illuminate\Auth\Middleware\CutomAuth::class, you are good to go

Related

Laravel Route Redirection Problems

I'm having problem redirecting my admin page to a Route::resource(); so that I could display my CRUD from the BookController
What am I doing wrong?
This is my AdminLoginController:
public function __construct(){
$this->middleware('guest:admin');
}
public function showLoginForm(){
return view('auth.admin-login');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password],$request->remember)){
return redirect()->intended(route('books.index'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
BookController
public function index()
{
$books = Book::orderBy('id','desc')->paginate(3);
return view('books.index')->withBooks($books);
}
web.php
Route::prefix('admin')->group(function(){
Route::get('/login','Auth\AdminLoginController#showLoginForm')>name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')>name('admin.login.submit');
Route::get('/books/','BookController#index');
});
I think you should update your books route:
Route::get('/books/','BookController#index')->name('books.index');
OR
Route::group(['prefix' => 'admin'], function () {
Route::resource('/books','BookController#index');
});
and check your route name in php artisan route:list
update your code like:
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password],$request->remember)){
return redirect()->intended(route('admin.books.index'));
}
Hope this work for you!

how to auto login after successfully registered in laravel 5.4.12?

i want to make an auto login after successful registration and redirect to Edit Profile page.. I tried the following code but not working as i want
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/edit_profile';
public function __construct()
{
$this->middleware('guest');
}
public function createUser(Request $request)
{
$this->validate($request , [
'firstName' => 'required',
'lastName' => 'required',
'displayName' => 'required',
'email' => 'required |email',
'password' =>'required ',
'gender' =>'required',
'day' =>'required|max:2',
'month' =>'required|max:2',
'year' =>'required|max:4',
]);
$email=$request->input('email');
$password=$request->input('paasword');
$dob=$request->input('day').'-'.$request->input('month').'-'.$request->input('year');
$request->request->add(['dob'=>$dob]);
$request->request->add(['password'=>bcrypt($request->input('password'))]);
$data = User::create($request->except(['_token', 'submit', 'day','month','year', 'confirm_password' ,'dayInWeek']));
Auth::login($data);
}
}
Routes
Route::get('/', 'PageController#login');
Route::get('/home', 'HomeController#index');
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('main', 'PageController#main');
Route::get('browse', 'PageController#browse');
Route::get('pickngo', 'PageController#pickngo');
Route::get('edit_profile', 'PageController#profile');
}
Use Laravel loginUsingId($id) function by passing the user id.
$data = User::create($request->except(['_token', 'submit', 'day','month','year', 'confirm_password' ,'dayInWeek']));
Auth::loginUsingId($data->id);
just modify your auth login just like
if(Auth::login($data)) {
return redirect('/edit_profile');
}
else
{
return redirect()->back();
}
Scren from documentation.
You just need to add after login redirectTo property or method inside your LoginController.
P.S.it will work if you're using laravel's make:auth.

Laravel 5.2 - Validation errors are not getting displayed [duplicate]

This question already has answers here:
Validation error in Laravel - $errors array does not get populated after the validation failure
(3 answers)
Closed 6 years ago.
I'm trying to validate a login/signup system in Laravel 5.2.
I'm using welcome.blade.php as the index page which contains two forms for both signup and signin
This is how my UserController.php is set up:
namespace authme\Http\Controllers;
use Illuminate\Http\Request;
use authme\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function getDashboard()
{
return view('dashboard');
}
public function doSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users',
'first_name' => 'required|max:120',
'password' => 'required|min:6'
]);
$email = $request['email'];
$password = bcrypt($request['password']);
$first_name = $request['first_name'];
$last_name = $request['last_name'];
$location = $request['location'];
$phone = $request['phone'];
$user = new User();
$user->email = $email;
$user->password = $password;
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->location = $location;
$user->phone = $phone;
$user->save();
Auth::login($user);
return redirect()->route('dashboard');
}
public function doSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
To show the errors during signup/login, in my view file (welcome.blade.php), I've included:
#if(count($errors) > 0)
<div class="row">
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
and the routes are set up like this:
Route::group(['middleware' => ['web']], function() {
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController#doSignUp',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'UserController#doSignIn',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard'
]);
});
The forms are working fine when entering correct details. However when I enter incorrect data:
When I try to submit the blank form, it just redirects back to the original page, but no errors are shown
When I try to enter an email that is already in use, it again redirects back to the original page, but no errors are displayed
However, I couldn't find any possible syntax error in my code. Is there any logical errors?
PS:
I've not edited or modified App\Exceptions\Handler
None of the answers to questions asked both here and here solves my problem
If you're using Laravel version higher or equal to 5.2.25 you no longer need to put your routes in the web middleware. It is now automatically applied.
Putting your routes in the web middleware in the routes.php actually causes the problem.
Explained here.
You can also use following codes to show the errors for sign in with invalid credential.
public function doSignIn(Request $request)
{
$rules = array(
'email' => 'required',
'password' => 'required'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()){
return redirect('welcome')
->withErrors($validator)
->withInput();
}else{
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
}
}
It seems to me your validation error messages are not getting saved to the session. Have a look at this.
https://github.com/laravel/framework/issues/12022

laravel 5.2 - Auth::user()->username is empty

If I use Auth::user()->username in a Blade file laravel returns me an empty String but Auth::user()->email is filled. I use my own AuthController and my Login,Register and Logout work perfectly but I can't get the username.
Routes.php
<?php
Route::group(['middleware' => ['web']] , function () {
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::group(['middleware' => ['web','guest']], function () {
Route::auth();
#Sign up Routes
Route::get('/signup', function () {
return view('auth.signup');
})->name('auth.signup');
Route::post('/signup', 'AuthController#signup');
#Sign in Routes
Route::get('/signin', function () {
return view('auth.signin');
})->name('auth.signin');
Route::post('/signin', 'AuthController#signin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::auth();
#Sign out Routes
Route::get('/signout', 'AuthController#signout')->name('auth.signout');
});
And my custom Auth Controller is:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request) {
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|min:2|max:20',
'password' => 'required|min:6'
]);
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
]);
return redirect()->route('home');
}
public function signin(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('flash-message','We can not sign you in with this data!');
}
return redirect()->route('home');
}
public function signout() {
Auth::logout();
return redirect()->route('home');
}
}
Maybe someone can help me
.
Note:
I added the username into User.php under the filled array.
Most likely you are missing username in $fillable of your User model.
The create method only accept fields coming from $fillable.
Please edit your User model like this:
protected $fillable = [
'email', 'username', 'password',
];
Only $fillable fields insert by Create method.

Login trouble in Laravel 4.2

I tried to create a login, after I tried successfully identified,
return "Success Login";
but when I replace with
return Redirect::to('dashboard');
always returned to Login page
can you help me ? what's wrong with my code...
here is my code :
route.php
Route::get('login',array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'AuthController#postLogin'))->before('csrf');
Route::group(array('before' => 'auth'), function(){
Route::get('dashboard', array('as' => 'panel', 'uses' => 'DashboardController#view_dashboard'));
});
AuthController.php
class AuthController extends Controller {
public function getLogin(){
return View::make('users.login');
}
public function postLogin(){
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('login')->withErrors($validator);
}
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
), false);
if(!$auth){
return Redirect::route('login')->withErrors(array(
'Maaf anda bukan sebagai admin..'
));
}
//return "Success";
return Redirect::to('dashboard');
}
}
DashboardController.php
class DashboardController extends Controller {
public function view_dashboard(){
return View::make('dashboard.view_home_admin');
}
}
view_home_admin.blade.php
<h1>Welcome <small>{{ ucwords(Auth::user()->username) }}</small></h1>

Categories