princeton-ddss / blackfish

Machine learning as a service (MLaaS) for busy researchers
https://princeton-ddss.github.io/blackfish/
0 stars 0 forks source link

Authenticate pages and endpoints #50

Closed cswaney closed 1 week ago

cswaney commented 1 month ago

In general, we should assume that the application is running in a shared environment. In that case, we want to limit access to the application to the user. A simple way to do this is to create a random authentication token at start up that the user can use to log in. We can authenticate subsequent requests using sessions. (There is no "authorization"—authenticated users have access to everything).

Authentication should work differently for endpoints that return HTML ("pages") and endpoints that return JSON ("endpoints"). If an endpoint returns a JSON response, then unauthorized requests should just raise an error and return 401. If an endpoint returns HTML, then an unauthorized request needs to redirect to a login page. Furthermore, the login page should not be accessible to authenticated users: if a user is logged in, they should be redirected to their dashboard.

There are a few endpoints that should not be authenticated. First, the login page should be accessible to everyone accept logged in users. We could make a separate middleware to handle this, but for now probably just check within the endpoint and redirect to the dashboard. Second, the login endpoint should be accessible to everyone accept logged in users. Again, we can just check within the endpoint if the user is logged in.

We can handle the different cases using two pieces of middleware. Endpoints can be protected by "guards", and pages can be protected by custom authentication middleware.

# Pages
[auth_middleware] GET  / ↪ /dashboard
[auth_middleware] GET  /dashboard
                  GET  /dashboard/login ↪ /dashboard (if authenticated)
[auth_middleware] GET  /text-generation
[auth_middleware] ...
# Endpoints
                  POST /login ↪ /dashboard
[auth_guard]      POST /logout ↪ /dashboard/login
[auth_guard]      POST /services
[auth_guard]      GET  /services
[auth_guard]      ...

Authentication can be turned off for development purposes by setting BLACKFISH_DEV_MODE=True.