How to return JSON in Laravel AuthServiceProvider? - json

I'm checking for a token in the boot() method and catching Invalid Tokens. How can I return some response in the case of an invalid token?
Here's my code:
public function boot(Authenticator $authenticator)
{
Auth::viaRequest('auth-token', function ($request) use ($authenticator) {
$bearerToken = $request->bearerToken();
if ($bearerToken) {
try {
return $authenticator->getUser($bearerToken);
} catch (InvalidTokenException $exeception) {
return response()->json(['token_invalid'], 400);
}
}
});
}
And it pips me the error:
Method Illuminate\Http\JsonResponse::getAuthIdentifier does not exist.

From the docs:
The second argument passed to the method should be a Closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, null
So instead of returning a response object, return null:
if ($bearerToken) {
try {
return $authenticator->getUser($bearerToken);
} catch (InvalidTokenException $exeception) {
return null;
}
}

Related

Laravel 8 API Unauthorized Handler Not Showing

I would like to add a custom response when an endpoint is being accessed without access token. I added this line of code into my Handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof AuthorizationException) {
return response()->json([
'message' => 'Unauthorized'
],401);
}
return parent::render($request, $exception);
}
Instead of getting the json response, I got a blank response with 500 error code on postman. What am I doing wrong?
The Response:
I figured it out by making sure that the server's response is in JSON. So I made a middleware file called ForceJsonResponse.php. Here is the code:
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
Registered it in Kernel.php on $middleware as
\App\Http\Middleware\ForceJsonResponse::class,
And in $routeMiddleware as
'json.response' => \App\Http\Middleware\ForceJsonResponse::class,

Java 'throws' keyword in Dart

Im coming from a Java background where I use the throws keyword to lead an exception to the method calling another method. How can I do that I dart?
Method called:
void _updateCurrentUserEmail() async {
await FirebaseAuth.instance
.currentUser()
.then((FirebaseUser user) {
_email = user.email;
});
}
How it is called:
try {
_updateCurrentUserEmail();
} on Exception {
return errorScreen("No User Signed In!", barActions);
}
But it seems like the Exception is not caught, because I still get a NoSuchMethodException and the errorScreen is not shown.
While you correctly used try/catch, the exception is coming from an async function that you did not await.
try/catch only catch exceptions thrown within that block. But since you wrote:
try {
doSomethingAsyncThatWillTrowLater();
} catch (e) {
}
Then the exception thrown by the async method is thrown outside of the body of try (as try finished before the async function did), and therefore not caught.
Your solution is to either use await:
try {
await doSomethingAsyncThatWillTrowLater();
} catch (e) {
}
Or use Future.catchError/Future.then:
doSomethingAsyncThatWillTrowLater().catchError((error) {
print('Error: $error');
});
From the docs,
If the catch clause does not specify a type, that clause can handle any type of thrown object:
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e'); <------------------
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}
Change it to this:
try {
_updateCurrentUserEmail();
} on Exception catch(e){
print('error caught: $e')
}
Another way to handle error is to do the following:
void _updateCurrentUserEmail() async {
await FirebaseAuth.instance
.currentUser()
.then((FirebaseUser user) {
_email = user.email;
throw("some arbitrary error");
});
.catchError(handleError);
}
handleError(e) {
print('Error: ${e.toString()}');
}
If currentUser()’s Future completes with a value, then()’s callback fires. If code within then()’s callback throws (as it does in the example above), then()’s Future completes with an error. That error is handled by catchError().
Check the docs:
https://dart.dev/guides/libraries/futures-error-handling
Throw
Here’s an example of throwing, or raising, an exception:
throw FormatException('Expected at least 1 section');
You can also throw arbitrary objects:
throw 'Out of llamas!';
throwing an exception is an expression, you can throw exceptions in => statements, as well as anywhere else that allows expressions:
void someMethod(Point other) => throw UnimplementedError();
here is example
main() {
try {
test_age(-2);
}
catch(e) {
print('Age cannot be negative');
}
}
void test_age(int age) {
if(age<0) {
throw new FormatException();
}
}
hope it helps..

try/catch error handling in web app

I noticed that when an error is thrown in a try/catch block within a Google Apps Script, Logger.log(e instanceof Error) returns true. But, when that same object is passed back to the client in the catch statement, it logs false.
GAS sample
function isValid() {
return false
}
function testing() {
try {
if(!isValid()) { throw new Error("failure") }
return "success"
} catch(e) {
Logger.log(e instanceof Error) // true
return e // false in the client when tested with console.log(e instanceof Error)
}
}
client
function foo() {
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).testing();
}
function onSuccess(e) {
console.log(e instanceof Error) // false
console.log(e) // null
}
function onFailure(e) {
console.log(e instanceof Error) // no result
}
Is there a better way to test for an error returned from the script file?
From the client side, you use a .withFailureHandler(...) when calling the .run.myFunction() code. The failure handler is a function in your client side code that will be called if an exception (i.e. error) is thrown in your server-side code and not handled.
Failure handlers will only be called if an exception is thrown. Otherwise, the success handler receives the server-side function's return value.
.gs
function myFn() {
try {
throw new Error("failure");
}
catch (e) {
Logger.log(e);
// Must rethrow to activate the client's FailureHandler function.
throw e;
}
return "success"
}
.html
function foo() {
google.script.run.withFailureHandler(logError).withSuccessHandler(useReturnValue).myFn();
}
function logError(error) {
console.log(error);
}
function useReturnValue(value) {
// do stuff
}
In the client side console, you will see the error get logged.
The problem is that your e variable hasn't an object assigned. Please note that the official Guides use error as the error handling function argument but your code use data and instead of using it on the console statement you use e.
On your client-side code replace data by e or vice versa.
From https://developers.google.com/apps-script/guides/html/reference/run#withFailureHandler(Function)
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function getUnreadEmails() {
// 'got' instead of 'get' will throw an error.
return GmailApp.gotInboxUnreadCount();
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function onFailure(error) {
var div = document.getElementById('output');
div.innerHTML = "ERROR: " + error.message;
}
google.script.run.withFailureHandler(onFailure)
.getUnreadEmails();
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Dart catch clause

I recently stumbled across the following Dart code:
void doSomething(String url, String method) {
HttpRequest request = new HttpRequest();
request.open(method, url);
request.onLoad.listen((event) {
if(request.status < 400) {
try {
String json = request.responseText;
} catch(e) {
print("Error!");
}
} else {
print("Error! (400+)");
}
});
request.setRequestHeader("Accept", ApplicationJSON);
}
I'm wondering what the e variable is in the catch clause:
catch(e) {
...
}
Obviously its some sort of exception, but (1) why do we not need to specify its type, and (2) what could I add in there to specify its concrete type? For instance, how could I handle multiple types of possible exceptions in a similar way to catchError(someHandler, test: (e) => e is SomeException)?
Dart is an optional typed language. So the type of e is not required.
you have to use the following syntax to catch only SomeException :
try {
// ...
} on SomeException catch(e) {
//Handle exception of type SomeException
} catch(e) {
//Handle all other exceptions
}
See catch section of Dart: Up and Running.
Finally catch can accept 2 parameters ( catch(e, s) ) where the second parameter is the StackTrace.

ASP.NET MVC client valitation on ui-dialog?

Razor:
#Html.TextBoxFor(kod => kod.Name)
#Html.ValidationMessage("Name","Client Error Message")
Controller:
[HttpPost]
public JsonResult JsonAddCustomer(Customers customer, string returnUrl)
{
if (customer.Name.Trim().Length == 0)
{
ModelState.AddModelError("Name", "Server Error Message");
}
//Eğer hata yoksa veri tabanına kayıt yapılıyor.
if (ModelState.IsValid)
{
try
{
CusOpp.InsertCustomer(customer);
return Json(new { success = true, redirect = returnUrl });
}
catch (Exception e)
{
ModelState.AddModelError("", "Error");
}
}
return Json(new { errors = GetErrorsFromModelState() });
}
I want to write validation error message. I did this like above, but #Html.ValidationMessage("Name","Client Error Message") does not work. In fact, I was already expecting it.
I want to show like this statement's result: #Html.ValidationMessageFor(m => m.name) ,but I cant use this, because I used entity-data-model.
Should I add [Required] statement to data-model classes or any way that I do this. Sorry for bad explanation.
Thanks.
You should return PartialViews instead of JSON in this case. Only in the case of success you could return JSON:
[HttpPost]
public ActionResult JsonAddCustomer(Customers customer, string returnUrl)
{
// Warning: the following line is something horrible =>
// please decorate your view model with data annotations or use
// FluentValidation.NET to validate it.
// Never write such code in a controller action.
if (customer.Name.Trim().Length == 0)
{
ModelState.AddModelError("Name", "Server Error Message");
}
//Eğer hata yoksa veri tabanına kayıt yapılıyor.
if (ModelState.IsValid)
{
try
{
CusOpp.InsertCustomer(customer);
return Json(new { success = true, redirect = returnUrl });
}
catch (Exception e)
{
ModelState.AddModelError("", "Error");
}
}
return PartialView(customer);
}
Now inside the success callback of your AJAX request you can test whether the POST action succeeded or not:
success: function(result) {
if (result.redirect) {
// we are in the success case => redirect
window.location.href = result.redirect;
} else {
// a partial view with the errors was returned => we must refresh the DOM
$('#some_container').html(result);
// TODO: if you are using unobtrusive client side validation here's
// the place to call the $.validator.unobtrusive.parse("form"); method in order
// to register the unobtrusive validators on the newly added contents
}
}
Here's a similar post that you might also read through.
Your Idea with the Required annotation on the model is a good approach. You can set a Error Message on the Required annotation.
[Required(ErrorMessage = "Please enter a name")]
and remove your if in your action..this:
if (customer.Name.Trim().Length == 0)
{
ModelState.AddModelError("Name", "Server Error Message");
}
the ModelState.IsValid will do the job for you on the client and server side.
And use your #Html.ValidationMessageFor(m => m.name) in your view