A scope is a data structure used to keep information about the current request or session, such as the current user logged in, the organization/company it belongs to, permissions, and so on. Think about it as a container that holds information that is required in the huge majority of pages in your application. It can also hold important request metadata, such as IP addresses.
Scopes also play a very important role in security. OWASP (Open Worldwide Application Security Project) lists "Broken access control" as the biggest security risk in web applications. That's because most data in an application is not publicly available. Instead, it most often belongs to a user, a team, or an organization. Therefore, it is extremely important that, when you query the database, your queries, inserts, updates, and deletes are properly scoped to the current user/team/organization.
By using scopes, you have a single data structure that contains all relevant information, which is then passed around so all of your operations are properly scoped. By defining your own scopes, Phoenix generators such as
mix phx.gen.html
,mix phx.gen.json
, andmix phx.gen.live
will automatically make sure all operations pertain to that scope, ensuring that all generated code is safe by default.Scopes are also flexible: you can have more than one scope in your application and choose the relevant scope when invoking the relevant generator. When you run
mix phx.gen.auth
, it will automatically generate a scope for you, but you may also add your own.This guide will:
- Show how
mix phx.gen.auth
generates a scope for you- Discuss how generators, such as
mix phx.gen.context
, rely on scopes for security- How to define your own scope from scratch and all valid options
- Augment the built-in scope with additional scopes
continue reading on hexdocs.pm
⚠️ This post links to an external website. ⚠️
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.