Laravel Authentication - php

$this->beforeFilter(function()
{
Config::set('auth.model', 'User');
if ((Auth::guest())) {
//dd(Auth::guest());
$msg3 = "Please Login First";
// dd("ok");
return Redirect::to(Request::root().'/auth')->with("error_message", $msg3);
}
});
I am using a Auth::guest() function for stopping unauthorized access but when I hit URL unauthorized access works fine but login fails... without this portion of code login using Auth::attempt() works fine... what can be the problem??
Edit
//AuthController for login
<?php
// uncomment this to use namespaced controller
//namespace Modules\admin\Controllers;
class AuthController extends \BaseController
{
public function __construct()
{
$this->beforeFilter(function()
{
Config::set('auth.model', 'User');
});
}
public function getIndex()
{
return \View::make("login");
}
public function postLogin()
{
$msg7 = "Invalid email address or password";
// $results['userData'] = user::get();
// dd($results);
//$password=Input::get('password');
//$password=Hash::make('secret');
$userData = array(
'email' => Input::get('email'),
'password'=> Input::get('password')
);
$email=Input::get('email');
// $password=Input::get('password');
// dd($password);
//dd($userData);
$rules = array(
'email' => 'required|email',
'password' => 'required|min:5'
);
$remember=Input::get('remember');
$remember_me=false;
if (!empty($remember)) {
$remember_me=true;
}
$validator = Validator::make(Input::get(), $rules);
if($validator->fails()){
// redirect to the login page with validation errors
return Redirect::to(Request::root().'/auth')->withErrors($validator)->withInput();
}
else{
//dd(Auth::attempt($userData));
// check authentication
if(Auth::attempt($userData,$remember_me)){
// dd(Auth::attempt($userData)); // redirect to the dashboard page
//dd($userData);
return Redirect::to(Request::root().'/home');
}else{
//dd($userData);
//DB::table('user')->insert($userData);
//dd("test");
// redirect to the login page with error message
return Redirect::to(Request::root().'/auth')->with("error_message", $msg7);
}
}
}
// logout function
public function getLogout()
{
// delete all data from sesstion
Auth::logout();
Session::flush();
// redirect to login page
return Redirect::to(Request::root().'/auth');
}
}
// DashboardController where unauthorized access is blocked
<?php
class DashboardController extends BaseController{
public function __construct()
{
$this->beforeFilter(function()
{
Config::set('auth.model', 'User');
if ((Auth::guest())) {
//dd(Auth::guest());
$msg3 = "Please Login First";
// dd("ok");
return Redirect::to(Request::root().'/auth')->with("error_message", $msg3);
}
});
}
public function getIndex()
{
//dd(Auth::check());
return View::make('home');
}
}

The problem is that you should exclude your action when you send your login form data. If in your controller you have method postLogin to handle POST data from login form, you should use:
$this->beforeFilter(function() {
// here goes code of your filter
}, array('except' => 'postLogin'));
Reference

Related

Cannot show callback validation message in a model

I'm using codeigniter 3 to build a simple login form but my callback validation message didn't work. Here is my code:
LoginForm_model.php
class LoginForm_model extends CI_Model
{
private $username;
private $password;
protected $validationRules = [
'username' => 'required|callback_username_exist',
'password' => 'required',
];
public function username_exist($str)
{
$this->load->model('Reseller_model', 'reseller');
$reseller = $this->reseller->findOne(['username' => $this->input->post('LoginForm')['username']]);
if (!empty($reseller)) {
return true;
}
$this->form_validation->set_message('username_exist', 'Username tidak ditemukan');
return false;
}
public function validate() {
$modelName = explode("_", get_class($this));
foreach($this->validationRules as $field => $validationRule) {
$this->form_validation->set_rules($modelName[0].'['.$field.']', $this->getLabels($field), $validationRule);
}
return $this->form_validation->run();
}
}
I use that model in my controller for validating login form input
Welcome.php
class Welcome extends CI_Controller {
public function index()
{
$this->load->model("Loginform_model", "loginform");
if (NULL !== $this->input->post('LoginForm')) {
if ($this->loginform->validate()) {
echo "All Set!";
}
}
$this->load->view('login');
}
}
The callback validation seems to work, but the message is like this:
Unable to access an error message corresponding to your field name Username.(username_exist)
The callback validation works if I put username_exist function in my controller. Can't we do it in a model? I want to make the controller as clean as possible. Please help.

Code for Facebook and Google Login not working on live server

Laravel version : 7.9.2
PHP version: 7.4
I have code for login with Facebook and Google. It's working absolutely fine on localhost but on live server it doesn't work. Surprising thing is It neither returns any error nor throw any exception.
It simply redirect user back to login page and my URL shows the string #=.
This is live link
https://beta.car-chain.net/login
I need suggestion.
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use App\User;
use Exception;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected $providers = [
'github','facebook','google','twitter'
];
public function show()
{
return view('auth.login');
}
public function redirectToProvider($driver)
{
if( ! $this->isProviderAllowed($driver) ) {
return $this->sendFailedResponse("{$driver} is not currently supported");
}
try {
return Socialite::driver($driver)->redirect();
} catch (Exception $e) {
// You should show something simple fail message
return $this->sendFailedResponse($e->getMessage());
}
}
public function handleProviderCallback( $driver )
{
try {
$user = Socialite::driver($driver)->user();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
// check for email in returned user
return empty( $user->email )
? $this->sendFailedResponse("No email id returned from {$driver} provider.")
: $this->loginOrCreateAccount($user, $driver);
}
protected function sendSuccessResponse()
{
return redirect()->intended('home');
}
protected function sendFailedResponse($msg = null)
{
return redirect()->route('social.login')
->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
}
protected function loginOrCreateAccount($providerUser, $driver)
{
// check for already has account
$user = User::where('email', $providerUser->getEmail())->first();
// if user already found
if( $user ) {
// update the avatar and provider that might have changed
$user->update([
'provider' => $driver,
'provider_id' => $providerUser->id,
'access_token' => $providerUser->token
]);
} else {
if($providerUser->getEmail()){ //Check email exists or not. If exists create a new user
$user = User::create([
'name' => $providerUser->getName(),
'email' => $providerUser->getEmail(),
'provider' => $driver,
'provider_id' => $providerUser->getId(),
'access_token' => $providerUser->token,
'password' => '' // user can use reset password to create a password
]);
}else{
//Show message here what you want to show
}
}
// login the user
Auth::login($user, true);
return $this->sendSuccessResponse();
}
private function isProviderAllowed($driver)
{
return in_array($driver, $this->providers) && config()->has("services.{$driver}");
}
}
Route.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('auth/social', 'Auth\LoginController#show')->name('social.login');
Route::get('oauth/{driver}', 'Auth\LoginController#redirectToProvider')->name('social.oauth');
Route::get('oauth/{driver}/callback', 'Auth\LoginController#handleProviderCallback')->name('social.callback');

Laravel Socialite Remember Me

I am using Socialite for user logins and I would like to set a remember_token to remember the user when they login through Socialite.
Right now I have the following service to create or log the user in:
class SocialAccountService {
public function createOrGetUser(ProviderUser $providerUser) {
$account = SocialAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName()
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
It is called with the following controller:
class AuthController extends Controller {
public function logout() {
Auth::logout();
return redirect('/');
}
public function redirectToGoogle() {
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback(SocialAccountService $service) {
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect('/');
}
}
The issue is that when the user comes back they are not remembered and automatically logged in. How can I do this with Socialite?
According to the documentation, passing true as the second argument of login() will set the remember token.
// Login and "remember" the given user... Auth::login($user, true);
The Auth facade and auth() helper function access the same object.

Routing confusion on two admin in laravel 4

I have following routes:
// For user
Route::controller('/', 'LoginController');
//For admin
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'admin\LoginController#index');
Route::get('/dashboard', 'admin\LoginController#show');
Route::get('/Logout','admin\LoginController#logout');
Route::resource('/setting','admin\SettingController');
});
I have user panel without prefix.
In logincontroller contain authorization codes.
I have found 'Controller method not found.' error when i open admin.but when i comment to user route then admin is working fine but user panel found same error.please help sir..thanks
Yes Here is LoginController of user
<?php
class LoginController extends BaseController {
public function getIndex()
{
if(Auth::check())
{
return Redirect::to('/user/home');
}
return View::make('login.index');
}
public function postIndex()
{
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(['username' => $username, 'password' => $password]))
{
return Redirect::intended('/user/home');
}
return Redirect::back()
->withInput()
->withErrors('Sorry,Username or password is incorrect');
}
public function getLogin()
{
return Redirect::to('/');
}
public function getLogout()
{
Auth::logout();
return Redirect::to('/');
}
}
Admin Login Controller
<?php
namespace admin;
class LoginController extends \BaseController {
public function showLogin() {
return \View::make('admin.login');
}
public function index()
{
return \View::make('admin.index');
}
public function store()
{
$username = \Input::get('username');
$password = md5(\Input::get('password'));
if ($mm=\DB::select('select * from admin where uname = ? and password = ?', array($username, $password)))
{
\Session::put('admin', $mm);
return \Redirect::intended('/admin/dashboard');
}
else
{
\Session::flush('admin');
return \Redirect::back()
->withInput()
->withErrors('Sorry,Unauthorized admin please try again');
}
}
public function postIndex()
{
echo 'Demo of post index';exit;
}
public function show()
{
$tt=\Session::get('admin');
return \View::make('admin.dashboard');
}
public function Logout()
{
\Session::flush('admin');
return \Redirect::to('/admin');
}
}
The problem is that Route::controller('/') is catching all requests that only have one segment. that means /admin as well. It then tries to find a getAdmin() method in the user LoginController which obviously doesn't exist.
You basically have two options here.
1. Change the route order
Routes are searched in the order you register them. If you place the admin group before the other route everything will work as expected:
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'admin\LoginController#index');
Route::get('/dashboard', 'admin\LoginController#show');
Route::get('/Logout','admin\LoginController#logout');
Route::resource('/setting','admin\SettingController');
});
Route::controller('/', 'LoginController');
2. Make explicit routes
Instead of using Route::controller('/') you could specify each route:
Route::get('/', 'LoginController#getIndex');
Route::get('login', 'LoginController#getLogin');
// etc...
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'admin\LoginController#index');
Route::get('/dashboard', 'admin\LoginController#show');
Route::get('/Logout','admin\LoginController#logout');
Route::resource('/setting','admin\SettingController');
});

how to remember a user who is login

I have created a sign in form with a remember me checkbox. I want to know how can i allow user to keep sign in when the browser is closed or sign out person when they close the browser. A sample code would be nice thank you.
here is my code
class HomeController extends BaseController {
public function getIndex()
{
if(Auth::check())
{
return Redirect::to('profile');
}
return View::make('index');
}
public function postRegister()
{
//gets array of the register form input values
$value = Input::all();
// create a new instance of the User model
$user = new User;
$validate = $user->userValidate($value);
//checks if the validation for the field fails
if($validate->fails())
{
/* $message = $validation->messages();
return $message; */
return Redirect::back()->withInput()->withErrors($validate);
}
//adds the users input to speicific field in the users table
$user->user_name = $value['username'];
$user->email = $value['email'];
$user->password = Hash::make($value['password']);
//save the inputs to the users table
$user->save();
return 'information has been stored';
}
public function getRegister()
{
$title = 'Register';
return View::make('register')->with('title',$title);
}
public function getSignIn()
{
$title = 'Signup';
return View::make('signup')->with('title',$title);
}
public function postSignIn()
{
//user's information
$credentials = array('email' => Input::get('email'),'password'=>Input::get('password'));
//logs this user in and checked if they are registered already in
if(Auth::attempt($credentials,false))
{
return Redirect::to('profile');
}
return Redirect::back()->withInput();
}
}
You just have to turn it on in your login method:
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user will now be logged in and remembered
}
else
{
// Raise a login error
}
This "true" parameter is to remember your user.
Here is the Laravel Auth::attempt() method declaration:
public function attempt(array $credentials = array(), $remember = false, $login = true)
{
...
}
You could set a cookie on the users browser (make sure you tell them if you are) to identify them. But beware that this could be modified by a malicious user.
PHP Cookies Documentation

Categories