in My web application i have simple custom login and logout routes which logout route doesn't work correctly and after when i want to switch to this route, that redirect to home route as /:
Route:
Route::namespace('Auth')->prefix('page')->group(function () {
Route::get('login', 'LoginController#show')->name('login');
Route::post('login', 'LoginController#login');
// logout route when i use conteoller doesn't work
Route::get('logout', 'LoginController#logoutUser')->name('logout');
});
Layout:
<a href="{{ route('logout') }}" class="nav-link">
<i class="icon-switch2"></i>
<span>LOGOUT</span>
</a>
LoginController:
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if (auth()->validate($request->only('password'))) {
$user = User::whereUsername($request->username)->first();
if ($user->active == 0) {
$checkActivationCode = $user->activationCode()->where('expire', '>=', Carbon::now())->latest()->first();
if ($checkActivationCode != null) {
if ($checkActivationCode->expire > Carbon::now()) {
$this->incrementLoginAttempts($request);
Session::flash('message', 'Please active your account');
return back();
}
}
}
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function logoutUser(Request $request)
{
dd($request->all());
//auth()->logout();
//$this->logout($request);
}
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
$socialUser = Socialite::driver('google')->stateless()->user();
$user = User::whereEmail($socialUser->getEmail())->first();
//dd($socialUser->getAvatar());
if (!$user) {
$data = [
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
'avatar' => str_replace('sz=50', 'sz=150', $socialUser->getAvatar()),
'mobileNumber' => '',
'loginType'=>'google',
'password' => bcrypt($socialUser->getId()),
];
//dd($data);
$user = User::create($data);
}
if ($user->active == 0) {
$user->update([
'active' => 1
]);
}
auth()->loginUsingId($user->id);
return redirect('/system/UserLoginWithGoogle');
}
public function show()
{
return view('auth.login');
}
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
'g-recaptcha-response', 'recaptcha'
]);
}
}
I think you have error in your contructor. There is "->except('login')", but I think it's not related to route name, but to a method, so it needs to be "->except('logoutUser')". Let me know if it works.
Related
in this simple code i created function to created users into database, after created them i can't verify username and password there and i get false
public function store(RequestUsers $request)
{
$user = User::create(array_merge($request->all(), ['username'=>'testtest', 'password' => bcrypt('testtest')]));
if ($user->id) {
dd(auth()->validate(['username'=>'testtest','password'=>$user->password]));
} else {
}
}
what's problem of my code which i can't verify created user?
full my login controller:
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if (auth()->validate($request->only('username','password'))) {
$user = User::whereUsername($request->username)->first();
if ($user->lock) {
$request->session()->flash('error',__('message.your_account_locked'));
return view('layouts.backend.pages.auth.account.locked_account');
}elseif (!$user->active) {
$checkActivationCode = $user->activationCode()->where('expire', '>=', Carbon::now())->latest()->first();
if ($checkActivationCode != null) {
if ($checkActivationCode->expire > Carbon::now()) {
$this->incrementLoginAttempts($request);
$request->session()->flash('error',__('message.please_active_your_account'));
return view('layouts.backend.pages.auth.account.active_account');
}
}else{
return redirect()->to('/page/userAccountActivation/create');
}
}
}
if ($this->attemptLogin($request)) {
//dd('aaaaaa');
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
$socialUser = Socialite::driver('google')->stateless()->user();
$user = User::whereEmail($socialUser->getEmail())->first();
//dd($socialUser->getAvatar());
if (!$user) {
$data = [
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
'avatar' => str_replace('sz=50', 'sz=150', $socialUser->getAvatar()),
'mobileNumber' => '',
'loginType'=>'google',
'password' => bcrypt($socialUser->getId()),
];
//dd($data);
$user = User::create($data);
}
if ($user->active == 0) {
$user->update([
'active' => 1
]);
}
auth()->loginUsingId($user->id);
return redirect('/system/UserLoginWithGoogle');
}
public function show()
{
return view('auth.login');
}
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required|string',
'password' => 'required|string',
'g-recaptcha-response', 'recaptcha'
]);
}
}
dd(auth()->validate(['username'=>'testtest','password'=>$user->password]));
Validate method expects the array to hold plain text value for the password. $user->password would be the hashed value, and it will always return false for that reason.
Changing that to:
dd(auth()->validate(['username'=>'testtest','password'=>'testtest']));
should yield the desired output.
I want to create a forgot password functionality of admin panel but, now I am using the custom admin login functionality in my AdminController. how can I create a forgot password functionality with a token for the admin panel ?
MY AdminController Code Here ...
login Method
public function login(Request $request)
{
if($request->isMethod('post')) {
$data = $request->input();
$adminCount = Admin::where([
'username' => $data['username']
'password'=> md5($data['password']),
'status'=> 1
])->count();
if($adminCount > 0){
//echo "Success"; die;
Session::put('adminSession', $data['username']);
return redirect('/admin/dashboard');
}else{
//echo "failed"; die;
return redirect('/admin')->with('flash_message_error','Invalid Username or Password');
}
}
return view('admin.admin_login');
}
Reset Method
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
You should try this:
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
I'm using laravel 5.1 and the modular package.
In my controller I use the following login method:
public function postLogin(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('admin/dashboard');
}
return redirect('/login')->withErrors([
'email' => 'These credentials do not match our records.']);
}
My route:
Route::group(array('module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'), function() {
Route::get('admin/dashboard', [
'middleware' => 'auth',
'uses' => 'AdminController#index'
]);
}}
My controller:
public function index()
{
return view("Admin::index");
}
My Middleware/Authenticate:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
return $next($request);
}
This works and redirects me to the index view after login.
When the user is not logged in, it is still possible to access the index view by accessing the url: localhost/admin/dashboard.
How can I redirect the user to a custom page which shows an error to the user that it is not possible to access the url localhost/admin/dashboard when he is not logged in?
Any ideas? Thank you
The issue is with your route the middleware should be at the top level as soon as you hit the controller it should redirect if not authenticated
Route::group(['middleware'=>'auth','module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'], function()
{
Route::get('admin/dashboard', ['uses' => 'AdminController#index']);
});
secondly if you want to redirect user to a custom page you can do this
public function redirectUnAuthenticateUser()
{
\Session::flash('login_error', 'Kindly login before you can access this page');
//create a view that user would be redirected to
return view('session.unauthenticated') ;
}
and the change your auth function to below
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('you-custom-rout-name-matching-above-function');
}
}
return $next($request);
}
and on your view you can get the value of the flash message
I'm working on a login form which uses ajax and I can't setup login throttling.
ThrottlesLogins trait redirects somewhere but I don't need that. How can I return number of seconds when user fails password n times?
Controller:
<?php
namespace App\Http\Controllers\Login;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class LoginController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public function index()
{
if (Auth::check()) return redirect(url('/dashboard'));
else return view('admin.login');
}
public function login(Request $request) {
$this->validate($request, [
'username' => 'required', 'password' => 'required',
]);
$credentials = $request->only('username', 'password');
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
if (Auth::attempt($credentials, $request->has('remember')))
{
return $this->handleUserWasAuthenticated($request, $throttles);
//return response()->json(['code' => 1, 'redirect' => url('/dashboard')]);
}
//else return response()->json(['code' => 0]);
if ($throttles) {
$this->incrementLoginAttempts($request);
}
}
}
routes.php
/* Login */
Route::group(array('prefix' => 'login', 'namespace' => 'Login', 'middleware' => 'guest'), function() {
Route::get('/', 'LoginController#index');
Route::post('/', 'LoginController#login');
});
You can change:
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
into
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
if ($request->ajax()) {
return response()->json(['lockout_time' => $this->lockoutTime()]);
}
else {
return $this->sendLockoutResponse($request);
}
}
I have been searching for solutions and changing my code back and forth but nothing worked for me and I honestly have given up hope to fix it by myself.
It stays on the same page and does not Redirect::to('test2'), but stays in the same page and when I remove the else { return Redirect::to('login'), it gives me a blank page.
Any help would be extremely appreciated.
This is my user model file:
protected $fillable=['email', 'password'];
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $primaryKey = 'id';
public static $rules = array(
'email' => 'required|email',
'password' => 'required',
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
This is my routing functions:
Route::get('/login', function(){
return View::make('login');
});
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userData)) {
return Redirect::to('test2');
echo 'SUCCESS!';
} else {
return Redirect::to('login');
}
}
I have been struggling around with the hash at beginning.
1. If the length of your password column isn't 60 then it wouldn't allow you to login.
2. Before logging via Auth::attempt() instead try to fetch the data of the user using his username
and then compare the password using Hash::check()
try something this
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$email=Input::get('email');
$user=User::where('email','=',$email)->first();
$bool=Hash::check('your password for the email',$user->password);
if(bool)
{
if (Auth::attempt(Input::only('email','password')))
{
return Redirect::to('test2');
echo 'SUCCESS!';
}else{
return Redirect::to('login');
}
}else{
return echo 'password didn't matche';
}
}