# Axum (Rust) Reference

PropelAuth's Axum library provides all the building blocks you need to add authentication to your Axum projects.

## Installation

In your `Cargo.toml` file, add the following line:

```toml
propelauth = { version = "0.9.0", features = ["axum07"] }

# For older versions of Axum, use:
# propelauth = { version = "0.9.0", features = ["axum06"] }
```

## Initialize

There are two options for initializing the library. You can call `PropelAuth::fetch_and_init` which is an `async` function that will fetch the metadata needed to verify access tokens. Or, you can call `PropelAuth::init` and pass in the metadata directly. The later is useful for serverless environments.

```rust
let auth = PropelAuth::fetch_and_init(AuthOptions {
    auth_url: "REPLACE_ME".to_string(),
    api_key: "REPLACE_ME".to_string(),
}).await.expect("Unable to initialize authentication");
```

## Protect API Routes

You'll need to add the `PropelAuthLayer` to your Router:

```rust
let auth_layer = PropelAuthLayer::new(auth);

let app = Router::new()
    .route("/whoami", get(whoami))
    .route("/org/:org_id/whoami", get(org_whoami))
    .layer(auth_layer); // <-- here
```

You can then take `User` in as an argument, which will look for an `access token` in the `Authorization` HTTP header:

```rust
// User will automatically return a 401 (Unauthorized) if a valid access token wasn't provided
async fn whoami(user: User) -> String {
    user.user_id
}
```

Verifying the access token doesn't require an external request.

## Authorization / Organizations

You can also verify which organizations the user is in, and which roles and permissions they have, with the `validate_org_membership` function on the `user` object.

### 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` object.

```rust
// If the user isn't in the provided organization, a 403 is returned
async fn org_whoami(user: User,
                    Path(org_name): Path<String>) -> Result<String, UnauthorizedOrForbiddenError> {
    let org = user.validate_org_membership(RequiredOrg::OrgId(&org_id),
                                           UserRequirementsInOrg::None)?;
    Ok(format!("You are in {}", 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` or `OrgMemberInfo` objects.

```rust
// Assuming a Role structure of Owner => Admin => Member
async fn org_whoami(user: User,
                    Path(org_name): Path<String>) -> Result<String, UnauthorizedOrForbiddenError> {
    let org = user.validate_org_membership(RequiredOrg::OrgId(&org_id),
                                           UserRequirementsInOrg::IsRole("Admin"))?;
    Ok(format!("You are a {} in {}", org.user_role, 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` or `OrgMemberInfo` objects.

```rust
async fn org_whoami(user: User,
                    Path(org_name): Path<String>) -> Result<String, UnauthorizedOrForbiddenError> {
    let org = user.validate_org_membership(RequiredOrg::OrgId(&org_id),
                                           UserRequirementsInOrg::HasPermission("can_view_billing"))?;
    Ok(format!("You can view billing in org {}", org.org_name))
}
```

## User

The User object contains information about the user that made the request.

- **`user_id`**: The unique id of the user.
- **`email`**: The email of the user.
- **`first_name`**: The first name of the user.
- **`last_name`**: The last name of the user.
- **`username`**: The username of the user.
- **`legacy_user_id`**: 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.
- **`impersonator_user_id`**: If the user is being impersonated, this is id of the user that impersonated them.
- **`login_method`**: The method the user used to log in. Returns the [Login Method Property](https://docs.propelauth.com/overview/authentication/login-methods).
- **`active_org_id`**: The ID of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- **`properties`**: A dictionary of [custom properties](https://docs.propelauth.com/overview/user-management/user-properties#custom-user-properties) associated with the user.
- **`org_id_to_org_member_info`**: A dictionary mapping from organization id to [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/axum#org-member-info) object.
- **`validate_org_membership(...)`**: A function that validates the user is in the specified organization, and has the specified role and permissions.
- **`get_org(RequiredOrg)`**: Returns the [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/axum#org-member-info) object for the specified organization.
- **`get_all_orgs()`**: Returns a list of [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/axum#org-member-info) objects for all organizations the user is in.
- **`get_active_org_id`**: Returns the ID of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- **`get_active_org`**: Returns the [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/axum#org-member-info) of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- **`is_impersonated`**: Whether the current user is being impersonated by someone else. See [User Impersonation](https://docs.propelauth.com/features/user-impersonation) for more information.

## OrgMemberInfo

The OrgMemberInfo object contains information about the user's membership in an organization.

- **`org_id`**: The unique id of the organization.
- **`org_name`**: The name of the organization.
- **`org_metadata`**: The metadata associated with the organization.
- **`user_role`**: The role of the user in the organization.
- **`user_permissions`**: A list of permissions the user has in the organization, based on their role.
- **`url_safe_org_name`**: The URL-safe name of the organization.
- **`inherited_user_roles_plus_current_role`**: The role of the user within this organization plus each inherited role.
- **`is_role`**: A function that returns true if the user has the specified role in the organization.
- **`is_at_least_role`**: A function that returns true if the user has at least the specified role in the organization.
- **`has_permission`**: A function that returns true if the user has the specified permission in the organization.
- **`has_all_permissions`**: A function that returns true if the user has all of the specified permissions in the organization.
- **`org_role_structure`**: 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.
- **`additional_roles`**: If using multiple roles per user, returns an array of roles that the user belongs to. Excludes the `user_role`.

## 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.

```rust
// Extension(auth) is useful for making API requests
async fn make_req(Extension(auth): Extension<Arc<PropelAuth>>) -> String {
    let magic_link = auth.user().create_magic_link(CreateMagicLinkRequest {
        email: "user@customer.com".to_string(),
        ..Default::default()
    }).await.expect("Couldn't create magic link");
    magic_link.url
}
```

See the [API Reference](https://docs.propelauth.com/reference) for more information.
