Quickstart for Node.js

This guide will walk you through your first change to an Oso policy file. There are three steps:

  1. Download a minimal Node.js starter project that’s already integrated with Oso.
  2. Run the server and visit the app in your browser.
  3. Make a small change to the policy to allow a new type of access.

The Oso Library works best in monolithic applications. If you’re building authorization for more than one service or want to share a policy across multiple applications, read how to get started with Oso Cloud.

1. Clone the repo and install dependencies

First, clone the Node.js quickstart repo, and install the dependencies:

git clone https://github.com/osohq/oso-nodejs-quickstart.git
cd oso-nodejs-quickstart
npm install

2. Run the server

With the dependencies installed, you should be ready to start the server:

npm run dev

If all is well, the server should be listening on port 5000.

Visit http://localhost:5000/repo/gmail in your browser. You should see a successful response, indicating that you have access to the gmail repo.

To see an unsuccessful response, visit http://localhost:5000/repo/react. You’ll see an error: Repo named react was not found. There actually is a repo named react, but you don’t have access to it. Let’s fix that now.

3. Update the policy

In main.polar, add the following two lines to define a new “rule.” This rule will allow any “actor” (or user) to perform the "read" action on a repository if that repository is marked as isPublic.

main.polar
actor User {}

resource Repository {
  permissions = ["read", "push", "delete"];
  roles = ["contributor", "maintainer", "admin"];

  "read" if "contributor";
  "push" if "maintainer";
  "delete" if "admin";

  "maintainer" if "admin";
  "contributor" if "maintainer";
}

# This rule tells Oso how to fetch roles for a repository
has_role(actor: User, role_name: String, repository: Repository) if
  role in actor.roles and
  role_name = role.name and
  repository = role.repository;

has_permission(_actor: User, "read", repository: Repository) if
  repository.isPublic;

allow(actor, action, resource) if
  has_permission(actor, action, resource);

Restart the server, and again visit http://localhost:5000/repo/react. Now, you’ll see a successful response:

A
200 response from /repo/react

What just happened?

The quickstart server uses an Oso policy to make sure users are allowed to view repos. The call to oso.authorize() in server.js performs this check in the /repo/:name route. If the user does not have access to a repository, an error response is returned to them.

In this case, the repo with the name react is public because of its definition in the models.js file, so it should be accessible to everyone. By making the change to main.polar, you told Oso to allow users to "read" repositories that have the isPublic field set to true.

That way, when you visited the react repo in your browser, Oso determined that the action was permitted!

Check out the full code for the example below:

server.js
const { Oso, NotFoundError } = require("oso");
const { User, Repository } = require("./models");
const express = require("express");

async function start() {
  const oso = new Oso();
  oso.registerClass(User);
  oso.registerClass(Repository);
  await oso.loadFiles(["main.polar"]);

  const app = express();

  app.get("/repo/:name", async (req, res) => {
    const name = req.params.name;
    const repo = Repository.getByName(name);
    const user = User.getCurrentUser();

    try {
      await oso.authorize(user, "read", repo);
      res.send(`<h1>A Repo</h1><p>Welcome to repo ${repo.name}</p>`);
    } catch (e) {
      if (e instanceof NotFoundError) {
        res.status(404);
        res.send(`<h1>Whoops!</h1><p>Repo named ${name} was not found</p>`);
      } else {
        throw e;
      }
    }
  });
  app.listen(5000, () => console.log("Server running on port 5000"));
}

start();
models.js
class Repository {
  constructor(name, isPublic = false) {
    this.name = name;
    this.isPublic = isPublic;
  }

  static getByName(name) {
    return repos_db[name];
  }
}

class Role {
  constructor(name, repository) {
    this.name = name;
    this.repository = repository;
  }
}

class User {
  constructor(roles) {
    this.roles = roles;
  }

  static getCurrentUser() {
    return users_db["larry"];
  }
}

const repos_db = {
  gmail: new Repository("gmail"),
  react: new Repository("react", true),
  oso: new Repository("oso"),
};

const users_db = {
  larry: new User([new Role("admin", repos_db["gmail"])]),
  anne: new User([new Role("maintainer", repos_db["react"])]),
  graham: new User([new Role("contributor", repos_db["oso"])]),
};

module.exports = { Repository, User };

Connect with us on Slack

If you have any questions, or just want to talk something through, jump into Slack. An Oso engineer or one of the thousands of developers in the growing community will be happy to help.