line-bot-sdk-rust 3.0.0

LINE Messaging API SDK for Rust
Documentation
/*
* Copyright 2023 nanato12
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

//! actix-web framework integration for LINE webhook signature extraction.

use actix_web::dev::Payload;
use actix_web::{error::ErrorBadRequest, Error, FromRequest, HttpRequest};
use std::future::{self, Ready};

/// Extracts the `x-line-signature` header value from an actix-web request.
///
/// Implements [`FromRequest`] so it can be used as an extractor.
///
/// # Example
///
/// ```ignore
/// use actix_web::{post, web, Error, HttpResponse};
/// use line_bot_sdk_rust::support::actix::Signature;
///
/// #[post("/callback")]
/// async fn callback(signature: Signature, bytes: web::Bytes) -> Result<HttpResponse, Error> {
///     // Use signature.key for validation
///     Ok(HttpResponse::Ok().body("ok"))
/// }
/// ```
#[derive(Debug)]
pub struct Signature {
    /// The value of the `x-line-signature` header.
    pub key: String,
}

impl FromRequest for Signature {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        let res = match req.headers().get("x-line-signature") {
            Some(value) => match value.to_str() {
                Ok(key) => Ok(Signature {
                    key: key.to_string(),
                }),
                Err(_) => Err(ErrorBadRequest(
                    "x-line-signature contains invalid characters",
                )),
            },
            None => Err(ErrorBadRequest("x-line-signature is missing")),
        };
        future::ready(res)
    }
}