For Stackd 2 we’re using Phoenix to build our API. This is my first time using Phoenix, and I love how you can use plugs and pattern matching to perform authentication and authorization. Here’s a look at how it works…
The first thing we want to do is figure out who is making the request. Our API uses OAuth2, so authentication is done by including an OAuth token in the Authorization header. Our RequireToken plug checks the Authorization header for an OAuth token and if successful it will assign(conn, :token, token). If it’s not successful, it will halt the request and respond with an OAuth error.
Our API has two different kinds of tokens:
Service tokens – used to access the API on behalf of internal services
User tokens – used to access the API on behalf of a user
With that in mind, let’s take a look at how our GET /users/:user_id/emails endpoint works. We want to make it so service tokens can list any user’s emails, but user tokens can only list their own emails.
First, we include the RequireToken plug. Then we use Elixir pattern matching to accomplish authorization. We have 3 different index/2 methods our request can match on:
Service token => show the emails
User token with the same user_id as the URL => show the emails
Any other token => 404 not found
Want to learn more about Stackd? Check out Origin to Pointer, our blog and podcast on tech, bootstrapping a business, product design, development, and whatever else is on our minds.