Skip to main content

openauth_plugins/device_authorization/
errors.rs

1use http::{header, Response, StatusCode};
2use openauth_core::api::ApiResponse;
3use openauth_core::error::OpenAuthError;
4use openauth_core::plugin::PluginErrorCode;
5use serde::Serialize;
6
7pub const INVALID_DEVICE_CODE: &str = "INVALID_DEVICE_CODE";
8pub const EXPIRED_DEVICE_CODE: &str = "EXPIRED_DEVICE_CODE";
9pub const EXPIRED_USER_CODE: &str = "EXPIRED_USER_CODE";
10pub const AUTHORIZATION_PENDING: &str = "AUTHORIZATION_PENDING";
11pub const ACCESS_DENIED: &str = "ACCESS_DENIED";
12pub const INVALID_USER_CODE: &str = "INVALID_USER_CODE";
13pub const DEVICE_CODE_ALREADY_PROCESSED: &str = "DEVICE_CODE_ALREADY_PROCESSED";
14pub const POLLING_TOO_FREQUENTLY: &str = "POLLING_TOO_FREQUENTLY";
15pub const USER_NOT_FOUND: &str = "USER_NOT_FOUND";
16pub const FAILED_TO_CREATE_SESSION: &str = "FAILED_TO_CREATE_SESSION";
17pub const INVALID_DEVICE_CODE_STATUS: &str = "INVALID_DEVICE_CODE_STATUS";
18pub const AUTHENTICATION_REQUIRED: &str = "AUTHENTICATION_REQUIRED";
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum OAuthDeviceError {
22    InvalidRequest,
23    InvalidClient,
24    InvalidGrant,
25    AuthorizationPending,
26    SlowDown,
27    ExpiredToken,
28    AccessDenied,
29    Unauthorized,
30    ServerError,
31}
32
33impl OAuthDeviceError {
34    fn as_str(self) -> &'static str {
35        match self {
36            Self::InvalidRequest => "invalid_request",
37            Self::InvalidClient => "invalid_client",
38            Self::InvalidGrant => "invalid_grant",
39            Self::AuthorizationPending => "authorization_pending",
40            Self::SlowDown => "slow_down",
41            Self::ExpiredToken => "expired_token",
42            Self::AccessDenied => "access_denied",
43            Self::Unauthorized => "unauthorized",
44            Self::ServerError => "server_error",
45        }
46    }
47}
48
49#[derive(Serialize)]
50struct OAuthErrorBody<'a> {
51    error: &'a str,
52    error_description: &'a str,
53}
54
55pub fn plugin_error_code(code: &str, message: &str) -> PluginErrorCode {
56    PluginErrorCode::new(code, message)
57}
58
59pub fn oauth_error_response(
60    status: StatusCode,
61    error: OAuthDeviceError,
62    description: &str,
63) -> Result<ApiResponse, OpenAuthError> {
64    let body = serde_json::to_vec(&OAuthErrorBody {
65        error: error.as_str(),
66        error_description: description,
67    })
68    .map_err(|error| OpenAuthError::Api(error.to_string()))?;
69
70    Response::builder()
71        .status(status)
72        .header(header::CONTENT_TYPE, "application/json")
73        .body(body)
74        .map_err(|error| OpenAuthError::Api(error.to_string()))
75}