ajax post security in laravel? - security

I am developing an application in laravel 5.1, I need to use sensitive user data and i was wondering about security when using ajax posts instead of a standard post. is it recommended using ajax, is there a way of performing some kind of protected ajax posts? Thanks :D

In laravel 5.1 you can use the HTTP Middleware in order to create something similar to the filters of older version.
1: Define Middleware
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// Check all your ajax stuff
return $next($request);
}
}
Inside the definition you can check wheter the request is Ajax, or other (have a look at the Class Reference) and define, for example, if the user has authorization to that specific route.
2: Assign middleware to routes
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'myMiddleware' => \Path\To\The\MiddleWare::class,
];
3: use the middleware key in the route options array
Route::post('your/route', ['middleware' => 'myMiddleware', function () {
//
}]);

Related

Validation Error: Using global entity manager instance methods for context specific actions is disallowed

Using MikroORM and getting this error:
ValidationError: Using global EntityManager instance methods for context specific actions is disallowed.
If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead
The code that it corresponds to is below:
import { MikroORM } from "#mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import mikroConfig from "./mikro-orm.config";
const main = async () => {
const orm = await MikroORM.init(mikroConfig);
const post = orm.em.create(Post, {
title: "my first post",
});
await orm.em.persistAndFlush(post);
await orm.em.nativeInsert(Post, { title: "my first post 2" });
};
main().catch((error) => {
console.error(error);
});
I am unsure where I need to use the .fork() method
Don't disable validations without understanding them!
I can't believe what I see in the replies here. For anybody coming here, please don't disable the validation (either via MIKRO_ORM_ALLOW_GLOBAL_CONTEXT env var or via allowGlobalContext configuration). Disabling the validation is fine only under very specific circumstances, mainly in unit tests.
In case you don't know me, I am the one behind MikroORM, as well as the one who added this validation - for a very good reason, so please don't just disable that, it means you have a problem to solve, not that you should add one line to your configuration to shut it up.
This validation was added to MikroORM v5 (so not typeorm, please dont confuse those two), and it means exactly what it says - you are trying to work with the global context, while you should be working with request specific one. Consult the docs for why you need request context here: https://mikro-orm.io/docs/identity-map#why-is-request-context-needed. In general using single (global) context will result in instable API response and basically a one huge memory leak.
So now we should understand why the validation is there and why we should not disable it. Next how to get around it properly.
As others mentined (and as the validation error message mentioned too), we can create fork and use that instead:
const fork = orm.em.fork();
const res = await fork.find(...);
But that would be quite tedious, in real world apps, we usually have middlewares we can use to do this for us automatically. That is where the RequestContext helper comes into play. It uses the AsyncLocalStorage under the hood and is natively supported in the ORM.
Following text is mostly an extraction of the MikroORM docs.
How does RequestContext helper work?
Internally all EntityManager methods that work with the Identity Map (e.g. em.find() or em.getReference()) first call em.getContext() to access the contextual fork. This method will first check if we are running inside RequestContext handler and prefer the EntityManager fork from it.
// we call em.find() on the global EM instance
const res = await orm.em.find(Book, {});
// but under the hood this resolves to
const res = await orm.em.getContext().find(Book, {});
// which then resolves to
const res = await RequestContext.getEntityManager().find(Book, {});
The RequestContext.getEntityManager() method then checks AsyncLocalStorage static instance we use for creating new EM forks in the RequestContext.create() method.
The AsyncLocalStorage class from Node.js core is the magician here. It allows us to track the context throughout the async calls. It allows us to decouple the EntityManager fork creation (usually in a middleware as shown in previous section) from its usage through the global EntityManager instance.
Using RequestContext helper via middleware
If we use dependency injection container like inversify or the one in nestjs framework, it can be hard to achieve this, because we usually want to access our repositories via DI container, but it will always provide we with the same instance, rather than new one for each request.
To solve this, we can use RequestContext helper, that will use node's AsyncLocalStorage in the background to isolate the request context. MikroORM will always use request specific (forked) entity manager if available, so all we need to do is to create new request context preferably as a middleware:
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
We should register this middleware as the last one just before request handlers and before any of our custom middleware that is using the ORM. There might be issues when we register it before request processing middleware like queryParser or bodyParser, so definitely register the context after them.
Later on we can then access the request scoped EntityManager via RequestContext.getEntityManager(). This method is used under the hood automatically, so we should not need it.
RequestContext.getEntityManager() will return undefined if the context was not started yet.
Simple usage without the helper
Now your example code from the OP is very basic, for that forking seems like the easiest thing to do, as its very bare bones, you dont have any web server there, so no middlewares:
const orm = await MikroORM.init(mikroConfig);
const emFork = orm.em.fork(); // <-- create the fork
const post = emFork.create(Post, { // <-- use the fork instead of global `orm.em`
title: "my first post",
});
await emFork.persistAndFlush(post); // <-- use the fork instead of global
await orm.em.nativeInsert(Post, { title: "my first post 2" }); // <-- this line could work with the global EM too, why? because `nativeInsert` is not touching the identity map = the context
But we can use the RequestContext here too, to demonstrate how it works:
const orm = await MikroORM.init(mikroConfig);
// run things in the `RequestContext` handler
await RequestContext.createAsync(orm.em, async () => {
// inside this handler the `orm.em` will actually use the contextual fork, created via `RequestContext.createAsync()`
const post = orm.em.create(Post, {
title: "my first post",
});
await orm.em.persistAndFlush(post);
await orm.em.nativeInsert(Post, { title: "my first post 2" });
});
The #UseRequestContext() decorator
Middlewares are executed only for regular HTTP request handlers, what if we need
a request scoped method outside that? One example of that is queue handlers or
scheduled tasks (e.g. CRON jobs).
We can use the #UseRequestContext() decorator. It requires us to first inject the
MikroORM instance to current context, it will be then used to create the context
for us. Under the hood, the decorator will register new request context for our
method and execute it inside the context.
This decorator will wrap the underlying method in RequestContext.createAsync() call. Every call to such method will create new context (new EntityManager fork) which will be used inside.
#UseRequestContext() should be used only on the top level methods. It should not be nested - a method decorated with it should not call another method that is also decorated with it.
#Injectable()
export class MyService {
constructor(private readonly orm: MikroORM) { }
#UseRequestContext()
async doSomething() {
// this will be executed in a separate context
}
}
Alternatively we can provide a callback that will return the MikroORM instance.
import { DI } from '..';
export class MyService {
#UseRequestContext(() => DI.orm)
async doSomething() {
// this will be executed in a separate context
}
}
Note that this is not a universal workaround, you should not blindly put the decorator everywhere - its actually the opposite, it should be used only for a very specific use case like CRON jobs, in other contexts where you can use middlewares this is not needed at all.
I faced a similar issue today when I upgraded the mikrorm setup from v4 to v5. After doing some RnD, I found the following changes helped me solve the mentioned error.
In the config object which is passed to the MikroORM.init call, pass the following property
allowGlobalContext: true
Don't directly use em to create database entry. Instead use the following code
const post = orm.em.fork({}).create(Post, {
title: "my first post",
});
The above changes should help you fix the error.
I am also very new to MikroORM. so, I am not sure why this error appears. But my uneducated guess is, they are restricting access to any changes to the global EntityManager em instance.
After doing some digging I found this solution:
yarn install dotenv
create a .env file in the root of the project
In your .env file paste the following:
MIKRO_ORM_ALLOW_GLOBAL_CONTEXT = true
Problem solved!

Is it possible to have protected routes in Remix.run, so the browser doesn't get the protected source code?

Is it possible to have protected routes in the Remix.run React framework, so that only admin users get the protected components, while regular users don't get the protected components at all as part of the JS bundle sent to the browser?
Also, this may require a form of code splitting on the front end side. Is code splitting supported in Remix.run?
this is a code snippet from a sample app I wrote, this is the home page and can only be accessed if the user is authenticated.
the redirect(`/login?${searchParams}`) will redirect if the user isn't authenticated
// Loaders provide data to components and are only ever called on the server, so
// you can connect to a database or run any server side code you want right next
// to the component that renders it.
// https://remix.run/api/conventions#loader
export let loader = async ({ request }) => {
const redirectTo = new URL(request.url).pathname;
let session = await getSession(request.headers.get("Cookie"));
// if there is no access token in the header then
// the user is not authenticated, go to login
if (!session.has("access_token")) {
let searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
throw redirect(`/login?${searchParams}`);
} else {
// otherwise execute the query for the page, but first get token
const { user, error: sessionErr } = await supabaseClient.auth.api.getUser(
session.get("access_token")
);
// if no error then get then set authenticated session
// to match the user associated with the access_token
if (!sessionErr) {
// activate the session with the auth_token
supabaseClient.auth.setAuth(session.get("access_token"));
// now query the data you want from supabase
const { data: chargers, error } = await supabaseClient
.from("chargers")
.select("*");
// return data and any potential errors alont with user
return { chargers, error, user };
} else {
return { error: sessionErr };
}
}
};
You can protect routes by authorizing the user inside the loader of the Route, there you could decide to redirect it somewhere else or send a flag as part of the loader data so the UI can hide/show components based on it.
For the code splitting, Remix does it at the route level, but it doesn't support server-side code-splitting out of the box, you may be able to support it with react-loadable.
I hope it has, but not. Below is the official answer.
https://remix.run/docs/en/v1/pages/faq#how-can-i-have-a-parent-route-loader-validate-the-user-and-protect-all-child-routes
You can't 😅. During a client side transition, to make your app as speedy as possible, Remix will call all of your loaders in parallel, in separate fetch requests. Each one of them needs to have its own authentication check.
This is probably not different than what you were doing before Remix, it might just be more obvious now. Outside of Remix, when you make multiple fetches to your "API Routes", each of those endpoints needs to validate the user session. In other words, Remix route loaders are their own "API Route" and must be treated as such.
We recommend you create a function that validates the user session that can be added to any routes that require it.

Two endpoints for same controller (route aliases) in NestJS

I want to change an entity name from Person to Individual. I want to keep the old /person endpoint (for temporary backward compatibility) and add a new /individual endpoint.
What would be the easiest way to do it in Node.js using Nest?
I can copy the code but I'm hoping for a better solution that won't require duplication
The #Controller() decorator accepts an array of prefix, thus you can use like this:
import { Controller, Get } from '#nestjs/common';
#Controller(['person', 'individual'])
export class IndividualController {
#Get()
findAll(): { /* ... */ }
}
to me this is the easiest way.
source
In NestJS, We can have multiple routes for the whole controller or for a single route. This is supported for all HTTP methods (POST, GET, PATCH etc., )
#Controller(['route-1', 'route-2'])
export class IndividualController {
#Get(['/sub-route-1','/sub-route-2'])
public async getSomething(...){...}
All HTTP methods support either a single string route or an array of string routes. We could use this technique to deprecate a bad route and start introducing a better route without breaking the consumers immediately.
if you mean expressjs instead of jestjs (which is a testing framework), my approach would be the following:
simply exclude your controller code into a function and pass it to your routes.
// your controller code
const doSomethingWithPersonEntity = (req, res, next) => {
res.status(200).json(persons);
}
router.get("/person", doSomethingWithPersonEntity);
router.get("/individual", doSomethingWithPersonEntity);

How to save the chat log locally and access in Bot framework NodeJS v4?

A logger is implemented as a middle-ware. Need to access the output of the logger through another dialog.
Look at the Botbuilder-Samples repo, the 17.multilingual-conversations sample. It demonstrates how you can interact with the dialog by receiving and sending activities based around the current context and inputs.
First, assign your middleware to the adapter in the index.js file:
const { LoggerMiddleware } = require('./logger-middleware');
adapter.use(new LoggerMiddleware (parameter_1, parameter_2));
Like the translator-middleware.js file, you will want to pass any necessary parameters thru the constructor of your middleware file:
constructor(parameter_1, parameter_2) {
this.parameter_1 = parameter_1;
this.parameter_2 = parameter_2;
}
After which, you create the onTurn method (and any associated methods), passing in the context and utilizing the class constructor parameters you need. Here you can create new dialogs that make use of the passed in logged data.
async onTurn(turnContext, next) {
let loggerText = this.parameter_1;
[...do stuff with <loggerText> data...]
await next();
}
In many respects, the middleware looks and functions like your main bot.js file. It is simply called at a different point in the process.
Hope of help.

Servicestack Display 404 page CatchAllHandlers

Im using servicestack Core with kestrel. I made a CatchAllHandlers delegate with the following code.
var requestType = typeof(NotFoundPage);
var restPath = new RestPath(requestType, pathInfo);
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
But the problem is that my ServicestackApi now is no longer reachable, url: /json/reply/GetApiCall goes to the 404 not found page.
Is there a way to solve this? can i check if its an api call or can i go later in the pipeline to handle the request?
update
I found that if i remove CatchAllHandler and just add the next middleware this middleware is called:
app.Use((context, next) =>
{
context.Response.Body.Write("yaayaya");
return Task.CompletedTask;
});
But this is not what i want, i want to stay inside the servicestack request.
update 2
Looking at the source-code i find HttpHandlerFactory has a property NotFoundHttpHandler Which is filled from the AppHost.
CustomErrorHttpHandlers.Add(HttpStatusCode.NotFound, new PageNotFoundHandler());
The only downside is that i can't provide any request specific information to this Urlhandler, such as the url itself:
public class PageNotFoundHandler : RestHandler
{
public PageNotFoundHandler()
{
var restPath = new RestPath(typeof(Error404), "/Url/For?");
}
}
Trying to make this work but i'm getting stuck on that my RestHandler has different amount of components than the url since this PageNotFoundHandler is made before the RestHandler.
But Basically what im looking for is to Handle a different service/InputDto
I've tried RequestConverters but this code is not reached when CatchAllHandlers doesn't return an Handler. so im stuck in this space in the middle. Anyway i could make all the left over routes, route to a single Dto?
.NET Core's new pipeline programming model expects you to call the next middleware if it wasn't already handled by any of the previously registered middleware which is how .NET Core lets you combine multiple different middlewares into the same App.
Handling Not Found Requests with the last Middleware
The last middleware that's registered will be able to handle any unhandled requests so for instance if you wanted to return a static image for unhandled requests you could register middleware after ServiceStack, e.g:
app.UseServiceStack(new AppHost());
app.Use(new StaticFileHandler("wwwroot/img/404.png"));
Or if you wanted to return a custom 404 page instead:
app.Use(new RazorHandler("/404"));
Which will render the /wwwroot/404.cshtml Razor View with ServiceStack's MVC Razor Views.
This would be the preferred way to handle Not Found requests in .NET Core in which you will be able to register additional middleware after ServiceStack to handle non-ServiceStack requests.
Calling a ServiceStack Service for unhandled requests
If you wanted to call a ServiceStack Service for any unhandled requests you can use a Fallback Route which matches on any request, e.g:
[FallbackRoute("/{Path*}")]
public class Error404
{
public string Path { get; set; }
}
public class UnhandledRequestService : Service
{
public object Any(Error404 request) => ...;
}

Resources