# Rust Reference

PropelAuth's Rust library provides all the building blocks you need to add authentication to your Rust projects. You should prefer the [Actix](https://docs.propelauth.com/reference/backend-apis/actix) or [Axum](https://docs.propelauth.com/reference/backend-apis/axum) libraries if you are using those frameworks, as they provide a more first-class experience, however, this library can be used in any Rust project.

## [Installation](https://docs.propelauth.com/reference/backend-apis/rust#installation)

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

```toml
propelauth = { version = "0.9.0" }
```

## [Initialize](https://docs.propelauth.com/reference/backend-apis/rust#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](https://docs.propelauth.com/reference/backend-apis/rust#protect-api-routes)

After initializing auth, you can verify access tokens by passing in the Authorization header (formatted `Bearer TOKEN`):

```rust
let result = auth.verify().validate_authorization_header(&authorization_header);
match result {
    Ok(user) => { /* valid access token in the header */ }
    Err(_) => { /* invalid access token, typically we return a 401 Unauthorized here */ }
}
```

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

## [Authorization / Organizations](https://docs.propelauth.com/reference/backend-apis/rust#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](https://docs.propelauth.com/reference/backend-apis/rust#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](https://docs.propelauth.com/reference/backend-apis/rust#user) object.

```rust
let org = user.validate_org_membership(
    RequiredOrg::OrgId(orgId),
    UserRequirementsInOrg::None
)?;
```

### 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/rust#user) or [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info) objects.

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.

```rust
let org = user.validate_org_membership(
    RequiredOrg::OrgId(orgId),
    UserRequirementsInOrg::IsRole("Owner")
)?;
```

### 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/rust#user) or [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info) objects.

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.

```rust
let org = user.validate_org_membership(
    RequiredOrg::OrgId(orgId),
    UserRequirementsInOrg::HasPermission("can_view_billing")
)?;
```

## [User](https://docs.propelauth.com/reference/backend-apis/rust#user)

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

- **`user_id`**  **Type**: string  **Description**: The unique id of the user.
- **`email`**  **Type**: string  **Description**: The email of the user.
- **`first_name`**  **Type**: string  **Description**: The first name of the user.
- **`last_name`**  **Type**: string  **Description**: The last name of the user.
- **`username`**  **Type**: string  **Description**: The username of the user.
- **`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.
- **`impersonator_user_id`**  **Type**: string  **Description**: If the user is being impersonated, this is id of the user that impersonated them.
- **`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).
- **`active_org_id`**  **Type**: string | undefined  **Description**: The ID of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- **`properties`**  **Type**: HashMap<String, Value>  **Description**: 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`**  **Type**: HashMap<String, OrgMemberInfo>  **Description**: A dictionary mapping from organization id to [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info) object.
- **`validate_org_membership(...)`**  **Type**: function  **Description**: A function that validates the user is in the specified organization, and has the specified role and permissions. See [Authorization / Organizations](https://docs.propelauth.com/reference/backend-apis/rust#authorization-organizations) for more information.
- **`get_org(RequiredOrg)`**  **Type**: fn() => Optional<OrgMemberInfo>  **Description**: A function that returns the [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info) object for the specified organization.
- **`get_all_orgs()`**  **Type**: fn() => OrgMemberInfo[]  **Description**: A function that returns a list of [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info) objects for all organizations the user is in.
- **`get_active_org_id`**  **Type**: fn() => string | undefined  **Description**: Returns the ID of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- **`get_active_org`**  **Type**: fn() => Optional<OrgMemberInfo>  **Description**: Returns the [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info) of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- **`is_impersonated`**  **Type**: fn() => bool  **Description**: Whether the current user is being impersonated by someone else. See [User\ Impersonation](https://docs.propelauth.com/overview/user-management/user-impersonation) for more information.

## [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/rust#org-member-info)

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

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

## [Calling backend APIs](https://docs.propelauth.com/reference/backend-apis/rust#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
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");

let magic_link = auth.user().create_magic_link(CreateMagicLinkRequest {
  email: "user@customer.com".to_string(),
  ..Default::default()
}).await.expect("Couldn't create magic link");
```

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