Creating Password Reset Function without using Laravel make:auth - laravel

I'm dealing with Laravel 5.6. I am using JWT Authentication, and I create my own authentication controller.
This is my recover method at AuthController,
public function recover(Request $request)
{
$user = User::where('email', $request->email)->first();
if (!$user) {
$error_message = "Your email address was not found.";
return response()->json(['success' => false, 'error' => ['email'=> $error_message]], 401);
}
try {
Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject('Your Password Reset Link');
});
} catch (\Exception $e) {
$error_message = $e->getMessage();
return response()->json(['success' => false, 'error' => $error_message], 401);
}
return response()->json([
'success' => true, 'data'=> ['message'=> 'A reset email has been sent! Please check your email.']
]);
}
In postman, if I execute the recover method, I get this message
{
"success": false,
"error": "Route [password.reset] not defined."
}
How can I deal with this. thanks!

You need to give the route a name, in this case password.reset. In your routes.php (or wherever you've defined them) call the name method:
Route::post('/password/reset', 'AuthController#recover')->name('password.reset');

If you haven't run make:auth you don't have the route defined, as the error itself is saying.
Try to define the following route in routes/web.php
Route::post('/pwdreset', 'AuthController#recover')
->name('password.reset');

Related

Throw not found error if user not exist in database Laravel

I'm using Auth::attempt($credentials) to authenticate login data from users.
$credentials = [
'user_name' => $request->user_name,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
return redirect()->route('admin.dashboard');
} else {
return redirect()->back()->with('status', 'Invalid credentials!');
}
If a user types the wrong password or wrong username, I throw an invalid credentials error. But I want if a user does not exist in the database, I can throw an error that the user does not exist.
My Auth::attempt($credentials) returns true or false, so I don't know how to do this. Can you help?
$user = User::where('user_name',$request->user_name)->first();
if($user) {
$credentials = [
'user_name' => $request->user_name,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
return redirect()->route('admin.dashboard');
} else {
return redirect()->back()->with('status', 'Invalid credentials!');
}
} else {
return redirect()->back()->with('status', 'Not found!');
}
It would be an security issue sir as #fubar said, but the simple logic is
Find at users table if email is exists.
if exists then go to auth attempt like the way you implement already.
if not exists throw 404.

The PUT method is not supported for this route. Supported methods: GET, HEAD, POST

I have the following code in my controller:
public function update(Request $request, $id)
{
$cook = cooks::findOrFail($id);
if (!$cook) {
return response()->json([
'success' => false,
'message' => 'Sorry, cook with id ' . $id . ' cannot be found',
], 400);
}
$updated = $cook->fill($request->all())
->save();
if ($updated) {
return response()->json([
'success' => true,
]);
} else {
return response()->json([
'success' => false,
'message' => 'Sorry, cook could not be updated',
], 500);
}
}
And when I use in my postman method PUT I received this message "The PUT method is not supported for this route. Supported methods: GET, HEAD, POST."
in my api.php I have the following line:
Route::resource('cook', 'cookList');
and here is the route that I use in postman:
`http://127.0.0.1:8000/api/cook`
with body id-1 and title-cook
Can someone help me, please?
You are missing a parameter in your route. As you are using http://127.0.0.1:8000/api/cook it's guessing you are trying to go to the index method or store method. So add a id parameter to your route and it should work with PUT method.
http://127.0.0.1:8000/api/cook/1
(Not tested, but should work)
You could try the Form Method Spoofing:
https://laravel.com/docs/5.8/routing#form-method-spoofing

Laravel 5.5 - Handle Error Exception for 'where'

In Laravel 5.5 I am trying to handle an error exception like this...
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
catch(ModelNotFoundException $e) {
return Response::json(array(
'error' => true,
'status_code' => 400,
'response' => 'fruit_id not found',
));
}
But this is giving me a 'Trying to get propert of non-object' error
The same error handling works correctly for findorfail, how should I be doing this for the 'where' statement?
I think you are passing wrong values in your where query in the try block.
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
Is it fruit_id or just id because you are querying it on fruit model itself.
Thanks to some pointers in the comments I changed to
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
catch(\Exception $e) {
return Response::json(array(
'error' => true,
'status_code' => 400,
'response' => 'fruit_id not found',
));
}
All is now working now I am catching the correct exception
Tested on Laravel 5.7
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
catch(\Exception $e) {
abort(404);
}
Even though you got it working, I'd like to make mention of Laravel's Exception Handler.
The report method allows you to catch any exception type and customize how you wish to process and move forward. There is a report helper function as well which is globally accessible.
Furthermore, reportable and renderable exceptions allow you to create and customize your responses.
Try the below code:
if ($user->fruit) {
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
} catch(\Exception $e) {
return Response::json(array(
'error' => true,
'status_code' => 400,
'response' => 'fruit_id not found',
));
}
} else {
return "User Fruit doesn't exists!!";
}

Lumen Custom Authentication with custom Fields and Store in Auth Guard

I am using lumen for API development. I have an issue in Lumen Custom Authentication.
I want to login a user when his credentials and account_name matches with stored record. In the credentials filed there is not username and password type data.
here my login method
public function login(Request $request)
{
$this->validate($request,[
'data.credentials' => 'required',
'data.account_name' => 'required',
]);
try {
$credentials=$request->data['credentials'];
$account_name=$request->data['account_name'];
$user=User::where('account_name',$account_name)->where('credentials',$credentials)->first();
if($user){
// storing the authenticated user to the guard session
$auth_token=Hash::make($account_name . ":" . $credentials);
// update user auth token
$user->auth_token=$auth_token;
$user->update();
$data="Some Data";
return response()->json([
"auth_token"=> $auth_token,
"data"=>$data,
"request_id"=> uniqid(),
"status"=> "success"
]);
}
} catch (\Exception $e) {
return response()->json(array(
'error' => $e->getMessage(),
'status' => 'failed',
'status_code' => 500
));
}
}
I authenticated user with credentials I want to store that user in guard that can be default guard or custom and want to return auth_token from every response. if I use following code it give me an error.
Auth::guard()->attempt(['credentials'=>$credentials,'account_name'=>$account_name]);
It give an error that attempt_undefined_method. and If I use the following code
Auth::guard()->check(['credentials'=>$credentials,'account_name'=>$account]);
it returns the false value and do not store user in guard. I want such type of response from every request where I applied auth middleware
return response()->json([
"auth_token"=> auth()->user()->auth_token,
"data"=>$data,
"request_id"=> uniqid(),
"status"=> "success
]);
following is my AuthMiddleware.php code
$header=$request->header('Auth-Token');
if(Auth::guard('api')){
// we can use $user variable for further :)
return $next($request);
}

Laravel - sending recovery mail

I'm trying to send a recovery mail using Laravel. I have the following recovery method:
public function recovery(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required'
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject(Config::get('boilerplate.recovery_email_subject'));
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->response->noContent();
case Password::INVALID_USER:
return $this->response->errorNotFound();
}
}
I tried to output $request->email and the reset email is the output, but for some reasons I get the following error:
Undefined index: email
at
"/home/pokemoti/public_html/api/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBrokerManager.php" on line 74
Any idea what could have gone wrong?
Fixed it by adding the following line in my config/auth.php passwords->users array:
'email' => 'auth.emails.password',
took it from another project where it worked.

Resources