Skip to content

Commit

Permalink
add cookie adapter through actix-cookie subcrate
Browse files Browse the repository at this point in the history
  • Loading branch information
miraclx committed May 1, 2021
1 parent cdae476 commit f3e6f09
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
members = [
"actix-cors",
"actix-cookie",
"actix-identity",
"actix-protobuf",
"actix-protobuf/examples/prost-example",
Expand Down
17 changes: 17 additions & 0 deletions actix-cookie/Cargo.toml
@@ -0,0 +1,17 @@
[package]
name = "actix-cookie"
version = "0.1.0"
authors = [
"Near Inc <hello@nearprotocol.com>",
]
description = "Actix adapter for cookies functionality"
repository = "https://github.com/near/actix-extras.git"
license = "MIT OR Apache-2.0"
edition = "2018"

[lib]
name = "actix_cookie"
path = "src/lib.rs"

[dependencies]
actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
46 changes: 46 additions & 0 deletions actix-cookie/src/lib.rs
@@ -0,0 +1,46 @@
use std::cell::Ref;

use actix_web::{
cookie::{Cookie, ParseError as CookieParseError},
dev::ServiceRequest,
http::header,
HttpMessage,
};

struct Cookies(Vec<Cookie<'static>>);

pub trait Cookied: HttpMessage {
fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
if self.extensions().get::<Cookies>().is_none() {
let mut cookies = Vec::new();
for hdr in self.headers().get_all(header::COOKIE) {
let s = std::str::from_utf8(hdr.as_bytes())
.map_err(CookieParseError::from)?;
for cookie_str in s.split(';').map(|s| s.trim()) {
if !cookie_str.is_empty() {
cookies.push(Cookie::parse_encoded(cookie_str)?.into_owned());
}
}
}
self.extensions_mut().insert(Cookies(cookies));
}

Ok(Ref::map(self.extensions(), |ext| {
&ext.get::<Cookies>().unwrap().0
}))
}

/// Return request cookie.
fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
if let Ok(cookies) = self.cookies() {
for cookie in cookies.iter() {
if cookie.name() == name {
return Some(cookie.to_owned());
}
}
}
None
}
}

impl Cookied for ServiceRequest {}

0 comments on commit f3e6f09

Please sign in to comment.