The user should be able to change his password when he is logged in. But always get i the same error. "Route [password.update] not defined."
I find the route are not in my rout list.
The routes are set in web.php and named in the controller. Where is the mistake?
Routes
//Change Password Routes
Route::get('/setting', 'Auth\UpdatePasswordController#index')->name('password.form');
Route::post('/setting', 'Auth\UpdatePasswordController#updatePassword')->name('password.update');
Controller
class UpdatePasswordController extends Controller
{
/*
* Ensure the user is signed in to access this page
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the form to change the user password.
*/
public function index(){
return view('/setting');
}
/**
* Update the password for the user.
*
* #param Request $request
* #return Response
*/
public function updatePassword(Request $request)
{
$this->validate($request, [
'old' => 'required',
'password' => 'required|min:6|confirmed',
]);
$user = User::find(Auth::id());
$hashedPassword = $user->password;
if (Hash::check($request->old, $hashedPassword)) {
//Change the password
$user->fill([
'password' => Hash::make($request->password)
])->save();
$request->session()->flash('success', 'Your password has been changed.');
return back();
}
$request->session()->flash('failure', 'Your password has not been changed.');
return back();
}
}
view
<form action="{{ route('password.update') }}" method="post" role="form" class="normagin sky-form">
{{csrf_field()}}
Related
I'm working in laravel 6 and vueJs; I want to validate the form request using the custom laravel form request. But it does not trigger any validation error instead gives this error message (500 (Internal Server Error)).
this my code. if anyone could help me would be greatly appreciated.
signup.vue
<template>
<v-container>
<v-form #submit.prevent="signup" class="signup-form">
<v-text-field
label="Name"
v-model="form.name"
type="text"
required
></v-text-field>
<v-text-field
label="E-mail"
v-model="form.email"
type="email"
required
></v-text-field>
<v-text-field
label="Password"
v-model="form.password"
type="password"
required
></v-text-field>
<v-text-field
label="Password_confirmation"
v-model="form.Password_confirmation"
type="password"
required
></v-text-field>
<v-btn type="submit" color="green">signup</v-btn>
<router-link to="/login">
<v-btn color="blue">Login</v-btn>
</router-link>
</v-form>
</v-container>
</template>
<script>
export default {
data() {
return {
form: {
name: null,
email: null,
password: null,
password_confirmation: null
}
}
},
errors: {},
methods: {
signup() {
axios.post('/api/auth/signup', this.form)
.then(res => this.responseAfterLogin(res))
.catch(error => console.log(error.response.data))
}
},
}
</script>
<style>
.signup-form {
margin-top: -120px;
margin-bottom: 15px;
}
</style>
Auth controller:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\SignupRequest;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('JWT', ['except' => ['login', 'signup']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Signup part added manually
*/
public function signup(Request $request)
{
$data = $request->validate([
'name' => 'required',
'email' => 'required|string',
'password' => 'required|string',
]);
User::create($request->all()); // the problem is not bcrypting the password section
// login the registered user
return $this->login($request);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'username' => auth()->user()->name,
]);
}
}
SignupRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SignupRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required',
'password' => 'required|confirmed',
];
}
}
You must define SignupRequest class on your controller for work defined rules. Example usage for signup function,
public function signup(SignupRequest $request)
{
User::create($request->all()); // the problem is not bcrypting the password section
// login the registered user
return $this->login($request);
}
Also you should define $token variable on login function.
Finally, you can find error details on under storage/logs/ folder files.
I hope this help you.
I'm having this method in my controller
public function update(UserUpdateRequest $request)
{
$request->user()->update([
'name' => $request->username,
]);
Mail::to($request->user())->send(
new UserUpdated( $request->user() )
);
return redirect()->route('account.index');
}
So when the user updates the username an email is send
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('emails.user.updated');
}
And this is the email template
Hi {{ $user->username }},
We would like to inform you that your username has been updated successfully.
If this action wasn't done by you, you need to contact with our support.
But this is throwing an exception in the queues
ErrorException: Undefined variable: user in /storage/framework/views/
Any ideas what I'm doing wrong?
Try passing it to the view via with method and make user variable protected:
protected $user;
public function build()
{
return $this->view('emails.user.updated')->with(['username' => $this->user->username]);
}
And then you can access it like {{ $username }} in your view.
Try this and then access the $user in your view
public function update(UserUpdateRequest $request)
{
$request->user()->update([
'name' => $request->username,
]);
$user = $request->user();
Mail::to($request->user())
->send(new UserUpdated($user));
return redirect()->route('account.index');
}
You can't send $request directly to you email template may this is the reason why you are not able to access the $user
when i have tried to submit the login form it goes to the logout route with MethodNotAllowedHttpException error and no message
// this is my route
Route::get('/',function(){return view('users.home');});
Route::get('register', 'RegisterController#showRegistrationForm')->name('showRegister');
Route::post('register', 'RegisterController#register')->name('Register');
Route::get('login', 'LoginController#showLoginForm')->name('showLogin');
Route::post('login', 'LoginController#login')->name('login');
and this is my login and logout controller
public function login(loginRequest $request )
{
if ( Auth()->attempt(['email' => $request->Username, 'password' => $request->Password], $request->remember) ) {
return redirect()->intended( url('dashboard') );
}// Authentication failed, redirect back to the login form
return redirect($this->redirect);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
Auth::guard()->logout();
$request->session()->flush();
return redirect()->guest(route('showLogin'));
}
redirect in login controller is wrong
public function login(loginRequest $request )
{
if ( Auth()->attempt(['email' => $request->Username, 'password' => $request-
>Password], $request->remember) ) {
//return redirect()->intended( url('dashboard') );
// the correct answer is
return redirect('/dashboard');
}
return redirect($this->redirect);
Instead of redirect($this->redirect) use Redirect::back()
return Redirect::back()->withErrors(['msg', 'The Message']);
and in your login controller function
public function login(loginRequest $request )
{
if ( Auth()->attempt(['email' => $request->Username, 'password' => $request->Password], $request->remember) ) {
return redirect('/dashboard');
}// Authentication failed, redirect back to the login form
return Redirect::back()->withErrors(['msg', 'The Message']);
}
and inside your view call this
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
I changed the login function a bit, that the user can only log in with his username and his email if his email address was confirmed by a sent email.
what do I want to do
If the email address has not yet been confirmed, I would like to redirect the user to a page to confirm his email address. If the table "users, active" has a 1, the address has been confirmed.
Currently I have problems logging in with the username. Does anyone recognize a mistake?
How can I implement that? Does anyone have a similar code?
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
$field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
? $this->username()
: 'username';
return [
$field => $request->get($this->username()),
'password' => $request->password,
];
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => [
'required', 'string',
Rule::exists('users')->where(function ($query){
$query->where('active', true);
})
],
'password' => 'required|string',
], $this->validationError());
}
New loginController
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/iboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'userLogout']]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
$field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
? $this->username()
: 'username';
return [
$field => $request->get($this->username()),
'password' => $request->password,
];
}
public function login(Request $request)
{
$this->validateLogin($request);
if (Auth::once($this->credentials($request))) { //use auth once so that it will not create auth session
$user = Auth::user();
if($user->active){
Auth::login($user); //now create auth session, check
return redirect('/iboard'); //redirect to dashboard url
}else{
return redirect('email_confirm')->with('fail', 'Please confirm your email'); //redirect to email confirm page
}
}
return redirect()->back()->with('fail', "Invalid username or password");
}
public function userLogout()
{
Auth::guard('')->logout();
return view('/exit');
}
}
You can try the below code for your login, assuming you have validateLogin and credentials functions in the same controller because the below login action used both of these function. Check details here
public function login(Request $request)
{
$this->validateLogin($request);
if (Auth::once($this->credentials($request))) { //use auth once so that it will not create auth session
$user = Auth::user();
if($user->active == 1){
Auth::login($user); //now create auth session
return redirect('dashboard'); //redirect to dashboard url
}else{
return redirect('email_confirm')->with('error', 'Please confirm your email'); //redirect to email confirm page
}
}
return redirect()->back()->with('error', "Invalid username or password");
}
I'm making a site with laravel that has a CRUD functie for Users and posts. That part is completed.
After that I made a register function, that also worked.
But when I tried to make a Login page some is wrong.
As soon as I select the, "login"-button a error page shows up with the error:
Class 'Auth' not found
My UserController:
<?php
class UserController extends BaseController {
protected $layout = "layouts.main";
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// get all the users
$users = User::all();
// load the view and pass the users
return View::make('users.index') ->with('users', $users);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
// load the create form (app/views/users/create.blade.php)
return View::make('users.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if($validator->fails()) {
return Redirect::to('users/create')
->withErrors($validator)
->withInput(Input::except('password'));
}else{
//store
$user = new User;
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Successfully created User!');
return Redirect::to('users');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
// get the User
$user = User::find($id);
// show the view and pass the user to it
return View::make('users.show') ->with('user', $user);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
// get the user
$user = User::find($id);
// show the edit form and pass the User
return View::make('users.edit') -> with('user', $user);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:8'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if($validator->fails()) {
return Redirect::to('users/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
}else{
//store
$user = User::find($id);
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Successfully updated User!');
return Redirect::to('users');
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
// delete
$user = User::find($id);
$user->delete();
// redirect
Session::flash('message', 'Successfully deleted the User!');
return Redirect::to('users');
}
//dit is toegevoegd
public function getRegister() {
$this->layout = View::make('login.register');
}
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('login/login')->with('message', 'Thanks for registering!');
} else {
// validation has failed, display error messages
return Redirect::to('login/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getDashboard')));
}
public function getLogin() {
$this->layout = View::make('login.login');
}
public function postSignin() {
$user = array('email'=>Input::get('email'), 'password'=>Input::get('password'));
if (Auth::attempt($user)) {
return Redirect::to('login/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('login/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
public function getDashboard() {
$this->layout = View::make('login.dashboard');
}
}
My Login.blade.php:
#include('header')
<h1>Login page</h1>
{{ Form::open(array('url'=>'login/signin', 'class'=>'form-signin')) }}
<h2 class="form-signin-heading">Please Login</h2>
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address')) }}
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password')) }}
<br><br>
{{ Form::submit('Login', array('class'=>'btn btn-large btn-primary btn- block'))}}
{{ Form::close() }}
#include('footer')
And my routes:
<?php
Route::get('home', function()
{
return View::make('home');
});
Route::get('/', function()
{
return View::make('home');
});
Route::resource('users', 'UserController');
Route::resource('posts', 'PostController');
Route::controller('login', 'UserController');
Anybody who can help me?
You need to add use Auth;
or use \Auth::
To use the Auth facade, you have to import it into your namespace.
A better option is to use the helper function instead:
if (auth()->attempt($user)) {
//
}
isset(auth()->user()->id)
to check is user logged in or not.