I am trying to reset the password but I am getting the error message "Trying to get property of non-object".
I have also attached the screen shot of my error please have a look at it.
My Controller for resetting the password:
class ResetPasswordController extends Controller
{
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
try {
$password = $this->user->where('id', Auth::user()->id)->value('password');
if(Hash::check($request->input('current_password'),$password)) {
$this->user->where('id', Auth::user()->id)->update(['password' => bcrypt($request->input('new_password'))]);
$token = $request->header('Authorization');
JWT::invalidate($token);
Auth::logout();
return response(['status' => true, 'message' => 'Password changed successfully'], 200);
} else {
return response(['status' => false, 'message' => 'The Current Password is invalid.'], 200);
}
} catch (\Exception $ex) {
return response(['status' => false, 'message' => $ex->getMessage()], 500);
}
}
}
My Routes configuration:
\Illuminate\Support\Facades\Auth::routes();
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm');
Route::post('password/reset', 'Auth\ResetPasswordController#reset')->name('password.request');
My View template:
<form action="{{ route('password.request') }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="login-form-email">Current Password</label>
<input type="password" class="form-control" name="current_password" id="login-form-password" tabindex="2" placeholder="Current Password" tabindex="4">
</div>
<div class="form-group">
<label for="login-form-password">New password</label>
<input type="password" class="form-control" name="new_password" id="login-form-password" tabindex="2" placeholder="New Password" tabindex="4">
</div><!-- /.form-group -->
<div class="form-group">
<label for="login-form-password-retype">Confirm new password</label>
<input type="password" class="form-control" name="new_password_confirmation" id="login-form-password-retype" tabindex="3" placeholder="Confirm password">
</div><!-- /.form-group -->
<div class="form-group">
<input type="submit" class="btn btn-primary pull-right" name="reset-confirm" id="reset-confirm" tabindex="4" value="Reset Password">
</div>
</form>
How can I find a solution based on this code and error message?
User doesn't need to be a member
Your first problem is here:
public function __construct(User $user)
You're injecting a user, without it knowing what user to use, unless this is coming from middleware. So the constructor shouldn't take a user, nor do you need to protected member. If you really want it as a protected member you could do the following:
public function __construct()
{
$this->user = Auth::user();
}
But since you have Auth::user(), you don't need it as a member.
where on a Model is Static
You have
$this->user->where('id', Auth::user()->id)->value('password')
Model's where function is a static function you shouldn't call it on an individual object. Instead you shoud call it using the scoping operator (::). Most versions of PHP should error out at that point. The correct way to get the current user's password hash from the database is:
$hash = Auth::user()->password;
If you had an id, you could:
$hash = User::where('id','=',$userId)->get()->password;
If you kept the user as a member (against the recommendation) but did it as in the above section of this answer, you could:
$hash = $this->user->password
Why?
Lastly, the Auth module from Laravel in modern versions already takes care of this for you in app\Http\Controllers\Auth. Why are reinventing the wheel?
Related
I have a problem with the login when I try to log in it says the page has expired due to inactivity.I am using middleware to check role based on user login and it seems it's not working. When ever try to login the page has expired message popups.
Route:
Route::get('/', function () {
return view('login');
});
Route::get('/dashboard/{user_id}', ['as' => 'dashboard', function ($user_id) {
return view('theme.index')->with(['id'=>$user_id]);
}]);
Route::post('login', 'AuthController#postSignIn')->name('login');
AuthController:
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user=DB::table('users')->where([['username', '=', $request['username']],['status','=','0']])->first();
$user_id=$user->user_id;
return redirect()->route('dashboard',$user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Middleware:
public function handle($request, Closure $next)
{
if ($request->user() === null) {
// return response("Insufficient permissions", 401);
return response(view('error'),401);
}
$actions = $request->route()->getAction();
$roles = isset($actions['roles']) ? $actions['roles'] : null;
if ($request->user()->hasAnyRole($roles) || !$roles) {
return $next($request);
}
// return response("Insufficient permissions", 401);
return response(view('error'),401);
}
}
Index:
<form class="form-horizontal" action="{{ route('login') }}" method="post">
{{ csrf_token() }}
<div class="form-group m-b-20 row">
<div class="col-12">
<label for="emailaddress">Username</label>
<input class="form-control" type="text" id="username" required="" placeholder="Enter Username">
</div>
</div>
<div class="form-group row m-b-20">
<div class="col-12">
<label for="password">Password</label>
<input class="form-control" type="password" required="" id="password" placeholder="Enter your password">
</div>
</div>
<div class="form-group row text-center m-t-10">
<div class="col-12">
<button class="btn btn-md btn-block btn-primary waves-effect waves-light" type="submit">Login</button>
</div>
</div>
</form>
You can change the session lifetime in Laravel config inside config/session.php by modifying following value
lifetime
also you will need to run
php artisan config:cache
for Laravel to pick new configurations.
I had figured it out i did it from scratch it was the problem of Auth function
The import Auth before that i did run two commands to clear my cache
php artisan cache:clear
php artisan config:cache
and import Auth
Thank you for the help guys appreciate it
add your route in $except array of VerifyCsrfToken.php middleware like this $except = [ "/login" ]; .
open VerifyCsrfToken.php middleware and put in except your url like :
protected $except = [
'http://localhost:8000/login'
];
and can see laravel docs for more information about csrf
https://laravel.com/docs/5.6/csrf#csrf-excluding-uris
I have small issue with authentication when user try to login but the username and password not matched in table how can return to login page with error massage
login.blade.php
<form class="login-box animated fadeInUp" action="valdateData" method="POST" >
{{csrf_field()}}
<div class="box-header">
<h2>Log In</h2>
</div>
<label for="username">Username</label>
<br/>
<input type="text" id="username" name="username">
<br/>
<label for="password">Password</label>
<br/>
<input type="password" id="password" name="password">
<br/>
<button type="submit">Sign In</button>
<br/>
<p class="small">Forgot your password?</p>
</form>
web.php
Route::post('/testgetvalue','OrdersController#GetValues');
Route::get('/ES','OrdersController#PrepareIndex');
Route::get('/loginForm','LoginController#ShowLoginPage');
Route::post('/valdateData','LoginController#checkValidate');
Route::post('login/{id}','LoginController#ShowErrorMassege');
LoginController.php
public function ShowLoginPage()
{
return view('/loginForm');
}
public function checkValidate(Request $request)
{
$username=$request->input('username');
$password=$request->input('password');
$isVald=true;
$checkValdate = \DB::table('authentications')
->where(['username'=>$username,'password'=>$password])
->get();
if(count($checkValdate) > 0)
{
$isVald=true;
session()->set('UserValidate','true');
session()->set('username',$username);
//$value=session()->get('test');
// echo "session "+$value;
return redirect('/es');
} else {
return redirect('/login/'.$isVald);
}
}
in this part
return redirect('/login/'.$isVald);
how can return to login page with error message
thanks
$validator = Validator::make($request->all(), [
'username'=>'required|min:3|max:30',
'password'=>'digits_between:1,5000',
]);
if ($validator->fails())
{
return redirect()->back()->with('error', sprintf('Server failed provided data validation.Please try again and follow the validation rules as instructed.'));
}
Here is a example of how you can do it, depends on your validatin rules. You can also define partials with a costum message foreach error, you should also use "use Illuminate\Support\Facades\Validator;" in your controller
I have followed a tutorial to add authentication to my application. I have a login route which has the method post and the form is also submitting as a post method. But whenever I click on the login button. Laravel throws an error of MethodNotAllowed. I assume that it is getting the method as a get request but the route is a post. Error is in thecompiled.php.
Route
Route::any('signup',['as' => 'signup' , 'uses' => 'Auth\AuthController#getRegister']);
Route::any('loginForm',['as' => 'loginForm' , 'uses' => 'Auth\AuthController#showLoginForm']);
Route::post('login',['as' => 'login' , 'uses' => 'Auth\AuthController#login']);
Route::any('postRegister',['as' => 'postRegister' , 'uses' =>'Auth\AuthController#postRegister']);
View
<form id="login" method="post" action="{{ route('login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input type="email" placeholder="User Email" id="email" name="email" class="form-control" value="{{old('email')}}"/>
</div>
<div class="form-group">
<input type="password" placeholder="Your Password" id="password" name="password" class="form-control" {{--value="{{old('email')}}"/--}}>
</div>
<div class="row">
<div class="mj_checkbox">
<input type="checkbox" value="1" id="check2" name="checkbox">
<label for="check2"></label>
</div>
<span> remember me</span>
</div>
</div>
<div class="form-group pull-right">
<span>forget password ?</span>
</div>
</div>
</div>
</div>
<input type="submit">
</div>
</form>
{authentication code is here}
<?php namespace App\Http\Controllers\Auth;
//use \App\Http\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use App\Http\Models\Company;
use Hash;
class AuthController extends Controller {
/**
* the model instance
public function __construct(Guard $auth, \App\User $user)
{
$this->user = $user;
$this->auth = $auth;
$this->middleware('guest', ['except' => ['getLogout']]);
}
public function getRegister()
{
return view('public-pages.Home.signup');
public function postRegister(Request $request)
{
$company = new Company;
$company-> companyName = $request -> companyName;
$company-> email = $request -> email;
$company-> password = Hash::make($request-> password);
$company-> address = $request -> address;
$company-> employeeName = $request -> employeeName;
$company-> phone_no = $request -> phone_no;
$company-> country = $request -> country;
$company-> city = $request -> city;
$company -> save();
return redirect('loginForm');
}
public function showLoginForm()
{
return view('public-pages.Home.login');
}
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect('Private-pages.Company.cmp-home');
} else {
return redirect('/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
public function getLogout()
{
$this->auth->logout();
return redirect('/');
}
}
I have some problem with Auth::attempt. When i write good Login with bad password attempt login into website anyway with wrong user. Why it dont work ?
Method:
public function postLogin(LoginRequest $request) {
if (Auth::attempt(["name" => $request["name"], "password" => $request["password"]])) {
return Redirect::route("home");
} else {
return Redirect::route("home");
}
}
LoginRequest
class LoginRequest extends Request {
public function rules() {
return [
"name" => "required|exists:users",
"password" => "required",
];
}
public function messages(){
return [
"name.required" => "Login is empty.",
"password.required" => "Password is empty.",
"name.exists" => "User not found.",
];
}
}
I know i redirect to same view, but view have 2 options for auth and !auth, but I see auth page when I login with good login and bad password, other options works. What did I wrong ?
Regards
edit:
view
<form action={{ route("login") }} method="post">
<input class="form-control" type="text" name="name" /><br />
<input class="form-control" type="password" name="password" /><br />
<input class="form-control" type="hidden" name="_token" value="{{ csrf_token() }}" /><br />
Remember me! <input class="form-control" type="checkbox" name="remember_me" value=""/><br />
<input class="btn btn-primary" type="submit" value="Zaloguj" />
</form>
the password column is named "password" ? and is hashed?
you can see the doc for more information.
https://laravel.com/docs/5.2/authentication#authenticating-users
I've made a login function in which I render a template after checking the login and password. This's the form that i've made inside a template.
<form action="{{ path("login") }}" method="post" id="formulaire_connexion">
<label class="control-label">Email
<input type="text" name="email" id="email" placeholder="your#email.com" onclick="this.select()"/>
</label>
<label class="control-label">Password</br>
<input type="password" name="password" id="password" placeholder="*********" onclick="this.select()"/>
</label>
<input type="checkbox" id="remember_me" name="remember_me"><label for="remember_me">Remember me </label></br>
<button type="submit" id="connexion" name="connexion">Connexion</button>
</form>
And this's the logging check method :
public function loginAction(Request $request)
{
$mail = $request->get('email');
$pass = $request->get('password');
$oauth = new OAuth($mail, $pass);
$baseUrl = "http://api.localhost/v1/";
$connexion = "{$baseUrl}login/".$mail."/".$pass;
$oauth->fetch($connexion, $_REQUEST, OAUTH_HTTP_METHOD_GET);
$reponseInformations = json_decode($oauth->getLastResponse(), true);
if (!$reponseInformations) {
$data['erreur'] = "Bad credentials";
return $this->render('EspacePointDeVenteBundle:Authentication:authentication.html.twig', array(
'erreur' => $data,
));
}else{
return $this->render('EspacePointDeVenteBundle:Home:index.html.twig', array(
'reseau' => $reseau,
'identifiant' => $key,
'key' => $identifiant,
));
}
}
After a wrong login connexion I render the same login template, but the routing is changed to /login instead of havig /index per example. What I need to know how to keep the same routing even if we called a foreign method.