In my laravel project I am checking for status and verified_email after login.but shows the error for username password not match only do not checking the error code which is going after login and loading the page continuously.
sessioncontroller
<?php
namespace App\Http\Controllers;
use Request;
use Response;
//----models--------
use App\Site;
use App\Jobs;
use Auth;
use DB;
use Validator;
use Redirect;
use Illuminate\Support\MessageBag;
class SessionController extends Controller {
public function index(){
return Redirect::to('login');
}
public function store()
{
$input = Request::only('username', 'email', 'password');
$credentials = [
'username' => Request::get('username'),
'password' => Request::get('password')
];
if (!Auth::attempt($credentials))
{
return Redirect::back()->with('alert-danger', 'Username or password do not match.');
}
else
{
if (Auth::user()->verified_email != 1) {
Auth::logout();
return Redirect::back()->with('alert-danger', 'Please verify your email.');
}
if (Auth::user()->status != 'A') {
Auth::logout();
return Redirect::back()->with('alert-danger', 'Your Account is disabled.Please contact your Administrator.');
}
$credentials_last_login = [
'last_login_at' => '',
'username' => array_get('username', $input, ' '),
'password' => array_get('password', $input, ' ')
];
if (Auth::attempt($credentials_last_login))
{
return redirect('/change_password');
}
else
{
return redirect('/properties');
}
}
}
}
It gives an error alert when username password not match but do not when verified_email is not 1 and when status is not Active instead of showing the error just load it.
Your password is being stored as a hash but I think your calling it plain - try:
'password' => Hash::make($request->password)
Related
I'm doing a login and registration screen, the registration screen is perfect, but the login screen is giving me a headache to authenticate.
the registration is done, but as soon as I log in it gives this error...
"Undefined property: Illuminate\Support\Facades\Request::$email"
I don't know what else to do to make it work.
CONTROLLER:
<?php
namespace App\Http\Controllers;
use App\Models\Usuario;
use Illuminate\Support\Facades\Auth;
use Request;
class Usuarios extends Controller
{
public function cadastrar()
{
$usuario = new Usuario(Request::all());
$usuario->save();
return redirect('/')->with('mensagem_sucesso', 'Cadastro efetuado com sucesso!');
}
public function index()
{
return view('layout/cadastrousuario');
}
public function indexlogin()
{
return view('layout/login');
}
public function logar(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request-> password])) {
dd('voce esta logado');
} else {
dd('voce nao esta logado');
}
}
}
MODEL:
<?php
namespace App\Models;
use App\Models\Model\Request;
use DB;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
class Usuario extends Authenticatable
{
protected $table = 'usuario';
public $timestamps = false;
protected $fillable =
array(
"codigo",
"nome",
"email",
"apelido",
"senha",
"bloqueado",
"saldo",
"saldo_atual",
"admin"
);
use HasFactory;
}
ROUTE:
<?php
use App\Http\Controllers\Lancamentos;
use App\Http\Controllers\LancamentosSimplificado;
use App\Http\Controllers\Usuarios;
use Illuminate\Support\Facades\Route;
// Route = (rota)::get ou post = (method) ( '/home' = (link) , [Lancamentos = (controller) :: class, 'logar' = ( function) ;
Route::get('/', [Lancamentos::class, 'index']);
Route::get('/salvar', [Lancamentos::class, 'salvar']);
Route::get('/maisdetalhes/{codigo}', [Lancamentos::class, 'maisdetalhes']);
Route::get('/criarchat', [Lancamentos::class, 'criarchat']);
Route::post('/cadastrar', [Lancamentos::class, 'cadastrar']);
Route::post('/cadastrar-simplificado', [LancamentosSimplificado::class, 'cadastrar']);
Route::get('/criarchat', [LancamentosSimplificado::class, 'listar']);
Route::get('/chat/{codigo}', [Lancamentos::class, 'chat']);
Route::get('/chatcriado/{codigo}', [LancamentosSimplificado::class, 'chatcriado']);
Route::get('/cadastrar-usuario', [Usuarios::class, 'index']);
Route::post('/cadastrar-usuario', [Usuarios::class, 'cadastrar']);
Route::get('/login', [Usuarios::class, 'indexlogin']);
Route::post('/login', [Usuarios::class, 'logar']);
page image as soon as I click login
to start you have to make validations in the register function to be sure that the email address arrives well and is registered. i would start by modifying this function
public function cadastrar(Request $r)
{
$r->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'min:6',
'password_confirmation' => 'required_with:password|same:password|min:6',
'custom_field' => 'custom validation'
]);
$input = $r->all();
$input['password'] = Hash::make($r->password);
$utilisateur = Model::create($input); //the Model == Usuario;
return redirect('/')->with([
'message' => "Cadastro efetuado com sucesso!",
'alert-type' => 'success',
]);
}
this is just a code snippet, I don't pretend to say that it's exactly what you need.the next way is the login function
if (Auth::attempt(['email' => $r->email, 'password' => $r->password])) {
// The user is active, not suspended, and exists.
$user = Auth::user();
if($user->fcm_token != Null){
$token = $user->createToken('AUTH')->accessToken;
$user->remember_token = $token;
$user->device_token = $user->fcm_token;
$user->save();
$response = [
"data"=> [
'user'=> $user,
'token'=> $token,
],
'message_fr' => 'Utilisateur connecté avec succès',
'message_en' => 'User logged successfully',
];
return response()->json($response, 200);
}else{
$response = [
'message_fr' => 'Vous êtes peut-être un robot',
'message_en' => 'You may be a robot',
];
return response()->json($response, 422);
}
} else {
$response = [
'message_fr' => 'Veuillez vérifier vos informations de connexion',
'message_en' => 'Please check your login information',
];
return response()->json($response, 422);
}
since you put a validation on the register, you are sure that the email is not only present, but also conforms to the nomenclature of an email
these two methods presented are examples taken from my source code of an available project, Good luck to you
You are using the wrong Request class. Request (Illuminate\Support\Facades\Request) that is aliased in config/app.php is the Facade, static proxy, for the bound Request class instance, Illuminate\Http\Request. If you want an instance of a Request you need to be using Illuminate\Http\Request.
use Illuminate\Http\Request;
Now via dependency injection you will have an instance of the Request class (which has magic methods to access inputs via dynamic properties). If you keep what you have then you would not be asking for an instance via dependency injection and would have to use the Facade as a Facade:
public function logar()
{
...
$something = Request::input(...); // static call to Facade
...
}
I'm trying to login a user through laravel socialite. Everything is working fine but the user is not getting logged in!
I'm getting response from facebook, saving the response in the database and trying to login after that.
here is the code:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Two\InvalidStateException;
use Auth;
use Socialite;
use App\User;
use DB;
use Log;
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
$findUser = User::where('email', $social->email)->first();
if ($findUser) {
// dd($findUser); **************** This returns information of the user who is trying to login through facebook
// dd(Auth::login($findUser, true)); ***************** This line returns null
if (Auth::login($findUser, true)) {
// dd(Auth::loginUsingId($findUser->id, true));
redirect()->route('dashboard');
} else {
return 'Error'; //**************** This get echoed on the screen
}
} else {
$user = new User();
$user->name = $social->name;
$user->email = $social->email;
$user->avatar = $social->avatar;
$user->provider = $provider;
$user->id = $social->id;
$user->password = bcrypt('password');
$user->save();
}
if (Auth::login($user)) {
return redirect()->intended('/home');
} else {
return 'Error';
}
}
Neither register, nor login is working.
The login() method doesn't return anything so if (Auth::login($findUser, true)) will never pass.
Also, it might be worth using the firstOrCreate() to make your method smaller:
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
User::unguard();
$user = User::firstOrCreate([
'email' => $social->email,
], [
'id' => $social->id,
'name' => $social->name,
'avatar' => $social->avatar,
'provider' => $provider,
'password' => bcrypt('password'),
]);
auth()->login($user, true);
return redirect()->intended('/home');
}
If you want to check if the User is signed in then you can use the auth()->id() method to retrieve the current authenticated user's id and then compare that to the $user->id:
if (auth()->id() !== $user->id) {
return 'Error';
}
Obviously, if you prefer to use the Auth facade instead of the auth() helper function then you can use Auth::id() instead of auth()->id()
This is my login controller function
use ThrottlesLogins;
protected $maxLoginAttempts = 3;
protected $lockoutTime = 300;
public function login(Request $request)
{
if ($this->hasTooManyLoginAttempts($request))
{
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$validator = Validator::make(Input::all() , ['credential' => 'required|min:2|max:255', 'password' => 'required|string|min:8', ]);
$cred = $request->credential;
$pw = $request->password;
$remember = (Input::has('remember')) ? true : false;
if (filter_var($cred, FILTER_VALIDATE_EMAIL))
{
if (Auth::guard('customers')->attempt(['email' => $cred, 'password' => $pw, 'verified' => 1], $remember))
{
return redirect()->route('front');
}
else
{
return redirect()->route('customer-login-page')->with('error', 'Your credentials do not match');
}
}
else
{
if (Auth::guard('customers')->attempt(['contact' => $cred, 'password' => $pw], $remember))
{
return redirect()->intended(route('front'));
}
else
{
return redirect()->route('customer-login-page')->with('error', 'Your credentials do not match');
}
}
}
protected function hasTooManyLoginAttempts(Request $request)
{
return $this->limiter()->tooManyAttempts(
$this->throttleKey($request), $this->maxLoginAttempts, $this->lockoutTime
);
}
It's not working. I've tried failed login attempts more that 3 times and still not getting throttled. AND
Even when I post the correct credentials, the login and redirect works but when I check the request I get a
302 FOUND error
in the network tab
You need to let the trait know that you are performing a login attempt by calling $this->incrementLoginAttempts($request) (see code). You can place this call right after your existing throttle check:
if ($this->hasTooManyLoginAttempts($request))
{
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->incrementLoginAttempts($request);
// other code
Try
use Illuminate\Foundation\Auth\ThrottlesLogins;
Instated of
use ThrottlesLogins;
Now I've followed the Laravel documentation on how to allow usernames during authentication, but it takes away the ability to use the email. I want to allow users to use their username or email to login. How do I go about this?
I've added this code to the LoginController as per Laravel's Documentation and it only allows username for login. I want it to accept username or email for login.
public function username () {
return 'username';
}
I think a simpler way is to just override the username method in LoginController:
public function username()
{
$login = request()->input('login');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$field => $login]);
return $field;
}
Follow instructions from this link: https://laravel.com/docs/5.4/authentication#authenticating-users
Then you can check for the user input like this
$username = $request->username; //the input field has name='username' in form
if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
//user sent their email
Auth::attempt(['email' => $username, 'password' => $password]);
} else {
//they sent their username instead
Auth::attempt(['username' => $username, 'password' => $password]);
}
//was any of those correct ?
if ( Auth::check() ) {
//send them where they are going
return redirect()->intended('dashboard');
}
//Nope, something wrong during authentication
return redirect()->back()->withErrors([
'credentials' => 'Please, check your credentials'
]);
This is just a sample. THere are countless various approaches you can take to accomplish the same.
Open your LoginController.php file.
Add this reference
use Illuminate\Http\Request;
And override the credentials method
protected function credentials(Request $request)
{
$field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
? 'email'
: 'username';
return [
$field => $request->get($this->username()),
'password' => $request->password,
];
}
Successfully tested in Laravel 5.7.11
You need to override protected function attemptLogin(Request $request) method from \Illuminate\Foundation\Auth\AuthenticatesUsers Trait in your LoginController
i.e. in my LoginController class
protected function attemptLogin(Request $request) {
$identity = $request->get("usernameOrEmail");
$password = $request->get("password");
return \Auth::attempt([
filter_var($identity, FILTER_VALIDATE_EMAIL) ? 'email' : 'username' => $identity,
'password' => $password
]);
}
Your LoginController class should use Trait \Illuminate\Foundation\Auth\AuthenticatesUsers in order to override attemptLogin method i.e.
class LoginController extends Controller {
use \Illuminate\Foundation\Auth\AuthenticatesUsers;
.......
.......
}
I think its even more simple, just override the method from AuthenticatesUsers traits, credentials method in your LoginController. Here I have implemented to login with either email or phone. You can change it to fit your needs.
LoginController.php
protected function credentials(Request $request)
{
if(is_numeric($request->get('email'))){
return ['phone'=>$request->get('email'),'password'=>$request->get('password')];
}
return $request->only($this->username(), 'password');
}
This is the way I do it:
// get value of input from form (email or username in the same input)
$email_or_username = $request->input('email_or_username');
// check if $email_or_username is an email
if(filter_var($email_or_username, FILTER_VALIDATE_EMAIL)) { // user sent his email
// check if user email exists in database
$user_email = User::where('email', '=', $request->input('email_or_username'))->first();
if ($user_email) { // email exists in database
if (Auth::attempt(['email' => $email_or_username, 'password' => $request->input('password')])) {
// success
} else {
// error password
}
} else {
// error: user not found
}
} else { // user sent his username
// check if username exists in database
$username = User::where('name', '=', $request->input('email_or_username'))->first();
if ($username) { // username exists in database
if (Auth::attempt(['name' => $email_or_username, 'password' => $request->input('password')])) {
// success
} else {
// error password
}
} else {
// error: user not found
}
}
I believe there is a shorter way to do that, but for me this works and is easy to understand.
public function username()
{
//return ‘identity’;
$login = request()->input('identity');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone';
request()->merge([$field => $login]);
return $field;
}
protected function validateLogin(Request $request)
{
$messages = [
'identity.required' => 'Email or username cannot be empty',
'email.exists' => 'Email or username already registered',
'phone.exists' => 'Phone No is already registered',
'password.required' => 'Password cannot be empty',
];
$request->validate([
'identity' => 'required|string',
'password' => 'required|string',
'email' => 'string|exists:users',
'phone' => 'numeric|exists:users',
], $messages);
}
https://dev.to/pramanadiputra/laravel-how-to-let-user-login-with-email-or-username-j2h
This solution of "Rabah G" works for me in Laravel 5.2. I modified a litle but is the same
$loginType = request()->input('useroremail');
$this->username = filter_var($loginType, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$this->username => $loginType]);
return property_exists($this, 'username') ? $this->username : 'email';
Thanks, this is the solution I got thanks to yours.
protected function credentials(Request $request) {
$login = request()->input('email');
// Check whether username or email is being used
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'user_name';
return [
$field => $request->get('email'),
'password' => $request->password,
'verified' => 1
];
}
i want to add password update option for logged user therefore i used following code
controller auth\authController.php
public function updatePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('change-password', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::route('change-password', $user->id)->withErrors('Your old password does not match');
} else {
$user->password = Input::get('password');
$user->save();
return Redirect::route('change-password', $user->id)->with("message", "Password have been changed");
}
}
}
Routes
Route::post('change-password', 'Auth\AuthController#updatePassword');
Route::get('change-password', 'Auth\AuthController#updatePassword');
im getting following error
FatalErrorException in AuthController.php line 123:
Class 'App\Http\Controllers\Auth\Auth' not found
for this line "$user = Auth::user();"
Your question has hidden answer..I have similar problem like #faz..I have done the trick with his question's code actually
The correct way to achieve this -
protected function postChangePassword(ChangePasswordFormRequest $request){
$user = Auth::user();
$current_password = Input::get('current_password');
$password = bcrypt(Input::get('password'));
$user_count = DB::table('users')->where('id','=',$this->user_id)->count();
if (Hash::check($current_password, $user->password) && $user_count == 1) {
$user->password = $password;
try {
$user->save();
$flag = TRUE;
}
catch(\Exception $e){
$flag = FALSE;
}
if($flag){
return redirect('/u/0/change/password')->with('success',"Password changed successfully.");
}
else{
return redirect('/u/0/change/password')->with("danger","Unable to process request this time. Try again later");
}
}
else{
return redirect('/u/0/change/password')->with("warning","Your current password do not match our record");
}
}
Please note for Hash and Auth, we need to include class at the top and user_id I have get through constructor $this->user_id = Auth::user()->id;. I think I have helped people.
You didn't import Auth class.
add this at the top of the file. after the namespace.
use Illuminate\Support\Facades\Auth;
Its namespace issue, Try :
//if this method is not protected by a middleware for only authenticated users
//verify that user is currently logged in:
if(!$user = \Auth::user()) abort(503); //or return redirect()->route('login')
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
Or Add the namespace at the top of your AuthController
use Auth;
class AuthController{
....
}
As i can understand your issue you just use auth namespace of laravel, just write this line at top of your controller file
use Auth;
will solve your problem.