# Django Rest Framework Reference

## [Installation](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#installation)

```bash
pip install propelauth-django-rest-framework
```

## [Initialize](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#initialize)

`init_auth` performs a one-time initialization of the library. It will verify your `api_key` is correct and fetch the metadata needed to verify access tokens in [IsUserAuthenticated and AllowAny](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#protect-api-routes).

### main.py

```py
from propelauth_django_rest_framework import init_auth

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")
```

### Async Support

If you prefer to use asynchronous functions you can use `init_auth_async` instead of `init_auth`. When using `init_auth_async`, each [backend API request](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#calling-backend-apis) will be async.

### main.py

```py
from propelauth_django_rest_framework import init_auth_async

auth = init_auth_async(
    "YOUR_AUTH_URL",
    "YOUR_API_KEY",
    httpx_client=httpx.AsyncClient() # Optional. Only needed if you want to use a custom client
)
```

## [Protect API Routes](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#protect-api-routes)

Protecting an API route is as simple as adding a Django permission to the route.

None of the Django permissions make a external request to PropelAuth. They all are verified locally using the [access token](https://docs.propelauth.com/recipes/access-tokens) provided in the request, making it very fast.

### IsUserAuthenticated

A Django permission that will verify the request was made by a valid user. If a valid [access token](https://docs.propelauth.com/recipes/access-tokens) is provided, it will set `request.propelauth_user` to be a [User](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user) Class. If not, the request is rejected with a 401 status code. While not required, you can use the `RequiredRequest` Class to get full type support.

Function-based viewsClass-based views

```py
from propelauth_django_rest_framework import init_auth, RequiredRequest

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

@api_view(['GET'])
@permission_classes([auth.IsUserAuthenticated])
def whoami(request: RequiredRequest):
    return HttpResponse(request.propelauth_user.user_id)
```

### AllowAny

Similar to `IsUserAuthenticated`, except if an access token is missing or invalid, the request is allowed to continue, but `request.propelauth_user` will be `None`. While not required, you can use the `OptionalRequest` Class to get full type support.

```py
from propelauth_django_rest_framework import OptionalRequest

class OptionalUserView(APIView):
    permission_classes = [auth.AllowAny]

def get(self, request: OptionalRequest):
        if request.propelauth_user is None:
            return HttpResponse("none")
        return HttpResponse(request.propelauth_user.user_id)
```

## [Authorization / Organizations](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#authorization-organizations)

You can also verify which organizations the user is in, and which roles and permissions they have in each organization all through the [User Class](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user).

### Check Org Membership

Verify that the request was made by a valid user **and** that the user is a member of the specified organization. This can be done using the [User](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user) Class.

```py
from propelauth_django_rest_framework import RequiredRequest

@api_view(['GET'])
@permission_classes([auth.IsUserAuthenticated])
def org_membership(request: RequiredRequest, org_id):
    org = request.propelauth_user.get_org(org_id)
    if org is None:
        # return 403 error
    return Response(f"You are in org {org.org_name}")
```

### Check Org Membership and Role

Similar to checking org membership, but will also verify that the user has a specific Role in the organization. This can be done using either the [User](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user) or [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#org-member-info) classes.

A user has a Role within an organization. By default, the available roles are Owner, Admin, or Member, but these can be configured. These roles are also hierarchical, so Owner > Admin > Member.

```py
## Assuming a Role structure of Owner => Admin => Member

@api_view(['GET'])
@permission_classes([auth.IsUserAuthenticated])
def org_owner(request: RequiredRequest, org_id):
    org = request.propelauth_user.get_org(org_id)
    if (org is None) or (org.user_is_role("Owner") == False):
        # return 403 error
    return Response(f"You are an Owner in org {org.org_name}")
```

### Check Org Membership and Permission

Similar to checking org membership, but will also verify that the user has the specified permission in the organization. This can be done using either the [User](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user) or [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#org-member-info) classes.

Permissions are arbitrary strings associated with a role. For example, `can_view_billing`, `ProductA::CanCreate`, and `ReadOnly` are all valid permissions. You can create these permissions in the PropelAuth dashboard.

```py
@api_view(['GET'])
@permission_classes([auth.IsUserAuthenticated])
def org_billing(request: RequiredRequest, org_id):
    org = request.propelauth_user.get_org(org_id)
    if (org is None) or (org.user_has_permission("can_view_billing") == False):
        # return 403 error
    return Response(f"You can view billing information for org {org.org_name}")
```

## [User](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user)

The User Class contains information about the user that made the request. It can be retrieved by using the [IsUserAuthenticated](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#protect-api-routes) permission.

```py
@api_view(['GET'])
@permission_classes([auth.IsUserAuthenticated])
def whoami(request: RequiredRequest):
    user = request.propelauth_user
    return Response(user.user_id)
```

- Name `user_id`
  - Type string
  - Description The unique id of the user.
- Name `org_id_to_org_member_info`
  - Type dict
  - Description A dictionary mapping from organization id to [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#org-member-info) object.
- Name `email`
  - Type string
  - Description The email of the user.
- Name `first_name`
  - Type string
  - Description The first name of the user.
- Name `last_name`
  - Type string
  - Description The last name of the user.
- Name `username`
  - Type string
  - Description The username of the user.
- Name `properties`
  - Type dict
  - Description A dictionary of [custom properties](https://docs.propelauth.com/overview/user-management/user-properties#custom-user-properties) associated with the user.
- Name `legacy_user_id`
  - Type string
  - Description If the user was migrated using our [Migration API](https://docs.propelauth.com/migrations), this will be the id of the user in the legacy system.
- Name `impersonator_user_id`
  - Type string
  - Description If the user is being impersonated, this is id of the user that impersonated them.
- Name `active_org_id`
  - Type string | undefined
  - Description Returns the ID of the [Active Org](https://docs.propelauth.com/recipes/active-org), if the user has an Active Org set.
- Name `login_method`
  - Type object
  - Description The method the user used to log in. Returns the [Login Method Property](https://docs.propelauth.com/overview/authentication/login-methods).
- Name `is_impersonated()`
  - Type bool
  - Description True if the user is being impersonated.
- Name `get_active_org()`
  - Type dict
  - Description Returns the [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#org-member-info) of the [Active Org](https://docs.propelauth.com/recipes/active-org), if the user has an Active Org set.
- Name `get_active_org_id()`
  - Type string
  - Description Returns the ID of the [Active Org](https://docs.propelauth.com/recipes/active-org), if the user has an Active Org set.
- Name `get_org(org_id)`
  - Type dict
  - Description Returns the org member info for the org_id, if the user is in the org.
- Name `get_org_by_name(org_name)`
  - Type dict
  - Description Returns the org member info for the org_name, if the user is in the org.
- Name `get_user_property(property_name)`
  - Description Returns the user property value, if it exists.
- Name `get_orgs()`
  - Type array
  - Description Returns the orgs the user is in.
- Name `is_role_in_org(org_id, role)`
  - Type bool
  - Description Returns true if the user is the role in the org.
- Name `is_at_least_role_in_org(org_id, role)`
  - Type bool
  - Description Returns true if the user is at least the role in the org.
- Name `has_permission_in_org(org_id, permission)`
  - Type bool
  - Description Returns true if the user has the permission in the org.
- Name `has_all_permissions_in_org(org_id, permissions)`
  - Type bool
  - Description Returns true if the user has all the permissions in the org.

## [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#org-member-info)

The OrgMemberInfo Class contains information about the user's membership in an organization. It can be retrieved by first getting the [User](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#user) Class and using either `get_org()`, `get_active_org()`, or `get_orgs()`.

```py
@api_view(['GET'])
@permission_classes([auth.IsUserAuthenticated])
def org_membership(request: RequiredRequest, org_id):
    orgMemberInfo = request.propelauth_user.get_org(org_id)
    return Response(orgMemberInfo.org_name)
```

- Name `org_id`
  - Type string
  - Description The unique id of the organization.
- Name `org_name`
  - Type string
  - Description The name of the organization.
- Name `org_metadata`
  - Type object
  - Description The metadata associated with the organization.
- Name `user_assigned_role`
  - Type string
  - Description The role of the user in the organization.
- Name `user_inherited_roles_plus_current_role`
  - Type list[string]
  - Description The role of the user within this organization plus each inherited role.
- Name `user_permissions`
  - Type list[string]
  - Description A list of permissions the user has in the organization, based on their role.
- Name `url_safe_org_name`
  - Type string
  - Description A URL-safe version of the org_name property.
- Name `user_is_role`
  - Type fn(role: string) -> bool
  - Description A function that returns true if the user has the specified role in the organization.
- Name `user_is_at_least_role`
  - Type fn(role: string) -> bool
  - Description A function that returns true if the user has at least the specified role in the organization.
- Name `user_has_permission`
  - Type fn(permission: string) -> bool
  - Description A function that returns true if the user has the specified permission in the organization.
- Name `user_has_all_permissions`
  - Type fn(permissions: list[string]) -> bool
  - Description A function that returns true if the user has all of the specified permissions in the organization.
- Name `org_role_structure`
  - Type string
  - Description The role structure set for your project. See [multi roles per user](https://docs.propelauth.com/overview/authorization/managing-roles-permissions#multiple-roles-per-user) for more information.
- Name `assigned_additional_roles`
  - Type list[string]
  - Description If using multiple roles per user, returns an array of roles that the user belongs to. Excludes the `user_assigned_role`.
- Name `legacy_org_id`
  - Type string
  - Description If the org was migrated from another system, this will be the ID of the org in the legacy system.

## [Calling Backend APIs](https://docs.propelauth.com/reference/backend-apis/drf?ref=propelauth.mymidnight.blog#calling-backend-apis)

You can also use the library to call the PropelAuth APIs directly, allowing you to fetch users, create orgs, and a lot more. See the [API Reference](https://docs.propelauth.com/reference) for more information.

StandardAsync

```py
from propelauth_django_rest_framework import init_auth

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

magic_link = auth.create_magic_link(email="test@example.com")
```
