mirror of
https://github.com/actix/examples
synced 2024-11-23 14:31:07 +01:00
reenable uds example; cargo fmt
This commit is contained in:
parent
7525903fe6
commit
44053504ad
@ -33,7 +33,7 @@ members = [
|
|||||||
"template_yarte",
|
"template_yarte",
|
||||||
"template_handlebars",
|
"template_handlebars",
|
||||||
"tls",
|
"tls",
|
||||||
#"unix-socket",
|
"unix-socket",
|
||||||
"web-cors/backend",
|
"web-cors/backend",
|
||||||
"websocket",
|
"websocket",
|
||||||
"websocket-chat",
|
"websocket-chat",
|
||||||
|
@ -6,56 +6,63 @@
|
|||||||
//!
|
//!
|
||||||
use actix_redis::RedisSession;
|
use actix_redis::RedisSession;
|
||||||
use actix_session::Session;
|
use actix_session::Session;
|
||||||
use actix_web::{middleware, web, App, HttpResponse, HttpServer, Result,
|
use actix_web::{
|
||||||
web::{resource, get, post}};
|
middleware, web,
|
||||||
|
web::{get, post, resource},
|
||||||
|
App, HttpResponse, HttpServer, Result,
|
||||||
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||||
pub struct IndexResponse {
|
pub struct IndexResponse {
|
||||||
user_id: Option<String>,
|
user_id: Option<String>,
|
||||||
counter: i32
|
counter: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn index(session: Session) -> Result<HttpResponse> {
|
fn index(session: Session) -> Result<HttpResponse> {
|
||||||
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
|
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
|
||||||
let counter: i32 = session.get::<i32>("counter")
|
let counter: i32 = session
|
||||||
.unwrap_or(Some(0))
|
.get::<i32>("counter")
|
||||||
.unwrap_or(0);
|
.unwrap_or(Some(0))
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(IndexResponse{user_id, counter}))
|
Ok(HttpResponse::Ok().json(IndexResponse { user_id, counter }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fn do_something(session: Session) -> Result<HttpResponse> {
|
fn do_something(session: Session) -> Result<HttpResponse> {
|
||||||
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
|
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
|
||||||
let counter: i32 = session.get::<i32>("counter")
|
let counter: i32 = session
|
||||||
.unwrap_or(Some(0))
|
.get::<i32>("counter")
|
||||||
.map_or(1, |inner| inner + 1);
|
.unwrap_or(Some(0))
|
||||||
|
.map_or(1, |inner| inner + 1);
|
||||||
session.set("counter", counter)?;
|
session.set("counter", counter)?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(IndexResponse{user_id, counter}))
|
Ok(HttpResponse::Ok().json(IndexResponse { user_id, counter }))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Identity {
|
struct Identity {
|
||||||
user_id: String
|
user_id: String,
|
||||||
}
|
}
|
||||||
fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
|
fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
|
||||||
let id = user_id.into_inner().user_id;
|
let id = user_id.into_inner().user_id;
|
||||||
session.set("user_id", &id)?;
|
session.set("user_id", &id)?;
|
||||||
session.renew();
|
session.renew();
|
||||||
|
|
||||||
let counter: i32 = session.get::<i32>("counter")
|
let counter: i32 = session
|
||||||
.unwrap_or(Some(0))
|
.get::<i32>("counter")
|
||||||
.unwrap_or(0);
|
.unwrap_or(Some(0))
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(IndexResponse{user_id: Some(id), counter}))
|
Ok(HttpResponse::Ok().json(IndexResponse {
|
||||||
|
user_id: Some(id),
|
||||||
|
counter,
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn logout(session: Session) -> Result<HttpResponse> {
|
fn logout(session: Session) -> Result<HttpResponse> {
|
||||||
let id: Option<String> = session.get("user_id")?;
|
let id: Option<String> = session.get("user_id")?;
|
||||||
if let Some(x) = id{
|
if let Some(x) = id {
|
||||||
session.purge();
|
session.purge();
|
||||||
Ok(format!("Logged out: {}", x).into())
|
Ok(format!("Logged out: {}", x).into())
|
||||||
} else {
|
} else {
|
||||||
@ -71,7 +78,7 @@ fn main() -> std::io::Result<()> {
|
|||||||
App::new()
|
App::new()
|
||||||
// redis session middleware
|
// redis session middleware
|
||||||
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32]))
|
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32]))
|
||||||
// enable logger - always register actix-web Logger middleware last
|
// enable logger - always register actix-web Logger middleware last
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
.service(resource("/").route(get().to(index)))
|
.service(resource("/").route(get().to(index)))
|
||||||
.service(resource("/do_something").route(post().to(do_something)))
|
.service(resource("/do_something").route(post().to(do_something)))
|
||||||
@ -82,29 +89,32 @@ fn main() -> std::io::Result<()> {
|
|||||||
.run()
|
.run()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
use actix_http::{HttpService, httpmessage::HttpMessage};
|
use actix_http::{httpmessage::HttpMessage, HttpService};
|
||||||
use actix_http_test::{TestServer, block_on};
|
use actix_http_test::{block_on, TestServer};
|
||||||
use actix_web::{middleware, App, web::{resource, get, post}};
|
use actix_web::{
|
||||||
|
middleware,
|
||||||
|
web::{get, post, resource},
|
||||||
|
App,
|
||||||
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use time;
|
use time;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_workflow() {
|
fn test_workflow() {
|
||||||
// Step 1: GET index
|
// Step 1: GET index
|
||||||
// - set-cookie actix-session will be in response (session cookie #1)
|
// - set-cookie actix-session will be in response (session cookie #1)
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
// Step 2: GET index, including session cookie #1 in request
|
// Step 2: GET index, including session cookie #1 in request
|
||||||
// - set-cookie will *not* be in response
|
// - set-cookie will *not* be in response
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
// Step 3: POST to do_something, including session cookie #1 in request
|
// Step 3: POST to do_something, including session cookie #1 in request
|
||||||
// - adds new session state in redis: {"counter": 1}
|
// - adds new session state in redis: {"counter": 1}
|
||||||
// - response should be: {"counter": 1, "user_id": None}
|
// - response should be: {"counter": 1, "user_id": None}
|
||||||
// Step 4: POST again to do_something, including session cookie #1 in request
|
// Step 4: POST again to do_something, including session cookie #1 in request
|
||||||
// - updates session state in redis: {"counter": 2}
|
// - updates session state in redis: {"counter": 2}
|
||||||
// - response should be: {"counter": 2, "user_id": None}
|
// - response should be: {"counter": 2, "user_id": None}
|
||||||
// Step 5: POST to login, including session cookie #1 in request
|
// Step 5: POST to login, including session cookie #1 in request
|
||||||
// - set-cookie actix-session will be in response (session cookie #2)
|
// - set-cookie actix-session will be in response (session cookie #2)
|
||||||
@ -124,86 +134,124 @@ mod test {
|
|||||||
// - set-cookie actix-session will be in response (session cookie #3)
|
// - set-cookie actix-session will be in response (session cookie #3)
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
|
|
||||||
let mut srv =
|
let mut srv = TestServer::new(|| {
|
||||||
TestServer::new(|| {
|
HttpService::new(
|
||||||
HttpService::new(
|
App::new()
|
||||||
App::new()
|
.wrap(
|
||||||
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32])
|
RedisSession::new("127.0.0.1:6379", &[0; 32])
|
||||||
.cookie_name("test-session"))
|
.cookie_name("test-session"),
|
||||||
.wrap(middleware::Logger::default())
|
)
|
||||||
.service(resource("/").route(get().to(index)))
|
.wrap(middleware::Logger::default())
|
||||||
.service(resource("/do_something").route(post().to(do_something)))
|
.service(resource("/").route(get().to(index)))
|
||||||
.service(resource("/login").route(post().to(login)))
|
.service(resource("/do_something").route(post().to(do_something)))
|
||||||
.service(resource("/logout").route(post().to(logout)))
|
.service(resource("/login").route(post().to(login)))
|
||||||
)
|
.service(resource("/logout").route(post().to(logout))),
|
||||||
});
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Step 1: GET index
|
||||||
// Step 1: GET index
|
|
||||||
// - set-cookie actix-session will be in response (session cookie #1)
|
// - set-cookie actix-session will be in response (session cookie #1)
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
let req_1a = srv.get("/").send();
|
let req_1a = srv.get("/").send();
|
||||||
let mut resp_1 = srv.block_on(req_1a).unwrap();
|
let mut resp_1 = srv.block_on(req_1a).unwrap();
|
||||||
let cookie_1 = resp_1.cookies().unwrap().clone()
|
let cookie_1 = resp_1
|
||||||
.into_iter().find(|c| c.name() == "test-session")
|
.cookies()
|
||||||
.unwrap();
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.name() == "test-session")
|
||||||
|
.unwrap();
|
||||||
let result_1 = block_on(resp_1.json::<IndexResponse>()).unwrap();
|
let result_1 = block_on(resp_1.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_1, IndexResponse{user_id: None, counter: 0});
|
assert_eq!(
|
||||||
|
result_1,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: None,
|
||||||
|
counter: 0
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Step 2: GET index, including session cookie #1 in request
|
// Step 2: GET index, including session cookie #1 in request
|
||||||
// - set-cookie will *not* be in response
|
// - set-cookie will *not* be in response
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
let req_2 = srv.get("/").cookie(cookie_1.clone()).send();
|
let req_2 = srv.get("/").cookie(cookie_1.clone()).send();
|
||||||
let resp_2 = srv.block_on(req_2).unwrap();
|
let resp_2 = srv.block_on(req_2).unwrap();
|
||||||
let cookie_2 = resp_2.cookies().unwrap().clone()
|
let cookie_2 = resp_2
|
||||||
.into_iter().find(|c| c.name() == "test-session");
|
.cookies()
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.name() == "test-session");
|
||||||
assert_eq!(cookie_2, None);
|
assert_eq!(cookie_2, None);
|
||||||
|
|
||||||
|
|
||||||
// Step 3: POST to do_something, including session cookie #1 in request
|
// Step 3: POST to do_something, including session cookie #1 in request
|
||||||
// - adds new session state in redis: {"counter": 1}
|
// - adds new session state in redis: {"counter": 1}
|
||||||
// - response should be: {"counter": 1, "user_id": None}
|
// - response should be: {"counter": 1, "user_id": None}
|
||||||
let req_3 = srv.post("/do_something").cookie(cookie_1.clone()).send();
|
let req_3 = srv.post("/do_something").cookie(cookie_1.clone()).send();
|
||||||
let mut resp_3 = srv.block_on(req_3).unwrap();
|
let mut resp_3 = srv.block_on(req_3).unwrap();
|
||||||
let result_3 = block_on(resp_3.json::<IndexResponse>()).unwrap();
|
let result_3 = block_on(resp_3.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_3, IndexResponse{user_id: None, counter: 1});
|
assert_eq!(
|
||||||
|
result_3,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: None,
|
||||||
|
counter: 1
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Step 4: POST again to do_something, including session cookie #1 in request
|
// Step 4: POST again to do_something, including session cookie #1 in request
|
||||||
// - updates session state in redis: {"counter": 2}
|
// - updates session state in redis: {"counter": 2}
|
||||||
// - response should be: {"counter": 2, "user_id": None}
|
// - response should be: {"counter": 2, "user_id": None}
|
||||||
let req_4 = srv.post("/do_something").cookie(cookie_1.clone()).send();
|
let req_4 = srv.post("/do_something").cookie(cookie_1.clone()).send();
|
||||||
let mut resp_4 = srv.block_on(req_4).unwrap();
|
let mut resp_4 = srv.block_on(req_4).unwrap();
|
||||||
let result_4 = block_on(resp_4.json::<IndexResponse>()).unwrap();
|
let result_4 = block_on(resp_4.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_4, IndexResponse{user_id: None, counter: 2});
|
assert_eq!(
|
||||||
|
result_4,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: None,
|
||||||
|
counter: 2
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Step 5: POST to login, including session cookie #1 in request
|
// Step 5: POST to login, including session cookie #1 in request
|
||||||
// - set-cookie actix-session will be in response (session cookie #2)
|
// - set-cookie actix-session will be in response (session cookie #2)
|
||||||
// - updates session state in redis: {"counter": 2, "user_id": "ferris"}
|
// - updates session state in redis: {"counter": 2, "user_id": "ferris"}
|
||||||
let req_5 = srv.post("/login")
|
let req_5 = srv
|
||||||
.cookie(cookie_1.clone())
|
.post("/login")
|
||||||
.send_json(&json!({"user_id": "ferris"}));
|
.cookie(cookie_1.clone())
|
||||||
|
.send_json(&json!({"user_id": "ferris"}));
|
||||||
let mut resp_5 = srv.block_on(req_5).unwrap();
|
let mut resp_5 = srv.block_on(req_5).unwrap();
|
||||||
let cookie_2 = resp_5.cookies().unwrap().clone()
|
let cookie_2 = resp_5
|
||||||
.into_iter().find(|c| c.name() == "test-session")
|
.cookies()
|
||||||
.unwrap();
|
.unwrap()
|
||||||
assert_eq!(true, cookie_1.value().to_string() != cookie_2.value().to_string());
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.name() == "test-session")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
true,
|
||||||
|
cookie_1.value().to_string() != cookie_2.value().to_string()
|
||||||
|
);
|
||||||
|
|
||||||
let result_5 = block_on(resp_5.json::<IndexResponse>()).unwrap();
|
let result_5 = block_on(resp_5.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_5, IndexResponse{user_id: Some("ferris".into()), counter: 2});
|
assert_eq!(
|
||||||
|
result_5,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: Some("ferris".into()),
|
||||||
|
counter: 2
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Step 6: GET index, including session cookie #2 in request
|
// Step 6: GET index, including session cookie #2 in request
|
||||||
// - response should be: {"counter": 2, "user_id": "ferris"}
|
// - response should be: {"counter": 2, "user_id": "ferris"}
|
||||||
let req_6 = srv.get("/")
|
let req_6 = srv.get("/").cookie(cookie_2.clone()).send();
|
||||||
.cookie(cookie_2.clone())
|
|
||||||
.send();
|
|
||||||
let mut resp_6 = srv.block_on(req_6).unwrap();
|
let mut resp_6 = srv.block_on(req_6).unwrap();
|
||||||
let result_6 = block_on(resp_6.json::<IndexResponse>()).unwrap();
|
let result_6 = block_on(resp_6.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_6, IndexResponse{user_id: Some("ferris".into()), counter: 2});
|
assert_eq!(
|
||||||
|
result_6,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: Some("ferris".into()),
|
||||||
|
counter: 2
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Step 7: POST again to do_something, including session cookie #2 in request
|
// Step 7: POST again to do_something, including session cookie #2 in request
|
||||||
// - updates session state in redis: {"counter": 3, "user_id": "ferris"}
|
// - updates session state in redis: {"counter": 3, "user_id": "ferris"}
|
||||||
@ -211,50 +259,71 @@ mod test {
|
|||||||
let req_7 = srv.post("/do_something").cookie(cookie_2.clone()).send();
|
let req_7 = srv.post("/do_something").cookie(cookie_2.clone()).send();
|
||||||
let mut resp_7 = srv.block_on(req_7).unwrap();
|
let mut resp_7 = srv.block_on(req_7).unwrap();
|
||||||
let result_7 = block_on(resp_7.json::<IndexResponse>()).unwrap();
|
let result_7 = block_on(resp_7.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_7, IndexResponse{user_id: Some("ferris".into()), counter: 3});
|
assert_eq!(
|
||||||
|
result_7,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: Some("ferris".into()),
|
||||||
|
counter: 3
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Step 8: GET index, including session cookie #1 in request
|
// Step 8: GET index, including session cookie #1 in request
|
||||||
// - set-cookie actix-session will be in response (session cookie #3)
|
// - set-cookie actix-session will be in response (session cookie #3)
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
let req_8 = srv.get("/")
|
let req_8 = srv.get("/").cookie(cookie_1.clone()).send();
|
||||||
.cookie(cookie_1.clone())
|
|
||||||
.send();
|
|
||||||
let mut resp_8 = srv.block_on(req_8).unwrap();
|
let mut resp_8 = srv.block_on(req_8).unwrap();
|
||||||
let cookie_3 = resp_8.cookies().unwrap().clone()
|
let cookie_3 = resp_8
|
||||||
.into_iter().find(|c| c.name() == "test-session")
|
.cookies()
|
||||||
.unwrap();
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.name() == "test-session")
|
||||||
|
.unwrap();
|
||||||
let result_8 = block_on(resp_8.json::<IndexResponse>()).unwrap();
|
let result_8 = block_on(resp_8.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_8, IndexResponse{user_id: None, counter: 0});
|
assert_eq!(
|
||||||
|
result_8,
|
||||||
|
IndexResponse {
|
||||||
|
user_id: None,
|
||||||
|
counter: 0
|
||||||
|
}
|
||||||
|
);
|
||||||
assert!(cookie_3.value().to_string() != cookie_2.value().to_string());
|
assert!(cookie_3.value().to_string() != cookie_2.value().to_string());
|
||||||
|
|
||||||
|
|
||||||
// Step 9: POST to logout, including session cookie #2
|
// Step 9: POST to logout, including session cookie #2
|
||||||
// - set-cookie actix-session will be in response with session cookie #2
|
// - set-cookie actix-session will be in response with session cookie #2
|
||||||
// invalidation logic
|
// invalidation logic
|
||||||
let req_9 = srv.post("/logout")
|
let req_9 = srv.post("/logout").cookie(cookie_2.clone()).send();
|
||||||
.cookie(cookie_2.clone())
|
|
||||||
.send();
|
|
||||||
let resp_9 = srv.block_on(req_9).unwrap();
|
let resp_9 = srv.block_on(req_9).unwrap();
|
||||||
let cookie_4 = resp_9.cookies().unwrap().clone()
|
let cookie_4 = resp_9
|
||||||
.into_iter().find(|c| c.name() == "test-session")
|
.cookies()
|
||||||
.unwrap();
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.name() == "test-session")
|
||||||
|
.unwrap();
|
||||||
assert!(&time::now().tm_year != &cookie_4.expires().map(|t| t.tm_year).unwrap());
|
assert!(&time::now().tm_year != &cookie_4.expires().map(|t| t.tm_year).unwrap());
|
||||||
|
|
||||||
|
|
||||||
// Step 10: GET index, including session cookie #2 in request
|
// Step 10: GET index, including session cookie #2 in request
|
||||||
// - set-cookie actix-session will be in response (session cookie #3)
|
// - set-cookie actix-session will be in response (session cookie #3)
|
||||||
// - response should be: {"counter": 0, "user_id": None}
|
// - response should be: {"counter": 0, "user_id": None}
|
||||||
let req_10 = srv.get("/")
|
let req_10 = srv.get("/").cookie(cookie_2.clone()).send();
|
||||||
.cookie(cookie_2.clone())
|
|
||||||
.send();
|
|
||||||
let mut resp_10 = srv.block_on(req_10).unwrap();
|
let mut resp_10 = srv.block_on(req_10).unwrap();
|
||||||
let result_10 = block_on(resp_10.json::<IndexResponse>()).unwrap();
|
let result_10 = block_on(resp_10.json::<IndexResponse>()).unwrap();
|
||||||
assert_eq!(result_10, IndexResponse{user_id: None, counter: 0});
|
assert_eq!(
|
||||||
|
result_10,
|
||||||
let cookie_5 = resp_10.cookies().unwrap().clone()
|
IndexResponse {
|
||||||
.into_iter().find(|c| c.name() == "test-session")
|
user_id: None,
|
||||||
.unwrap();
|
counter: 0
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let cookie_5 = resp_10
|
||||||
|
.cookies()
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.name() == "test-session")
|
||||||
|
.unwrap();
|
||||||
assert!(cookie_5.value().to_string() != cookie_2.value().to_string());
|
assert!(cookie_5.value().to_string() != cookie_2.value().to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use actix_identity::Identity;
|
use actix_identity::Identity;
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::Payload, error::BlockingError, web, Error, FromRequest, HttpRequest, HttpResponse,
|
dev::Payload, error::BlockingError, web, Error, FromRequest, HttpRequest,
|
||||||
|
HttpResponse,
|
||||||
};
|
};
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
use diesel::PgConnection;
|
use diesel::PgConnection;
|
||||||
|
@ -11,8 +11,8 @@ static ref API_KEY: String = std::env::var("SPARKPOST_API_KEY").expect("SPARKPOS
|
|||||||
|
|
||||||
pub fn send_invitation(invitation: &Invitation) -> Result<(), ServiceError> {
|
pub fn send_invitation(invitation: &Invitation) -> Result<(), ServiceError> {
|
||||||
let tm = Transmission::new_eu(API_KEY.as_str());
|
let tm = Transmission::new_eu(API_KEY.as_str());
|
||||||
let sending_email =
|
let sending_email = std::env::var("SENDING_EMAIL_ADDRESS")
|
||||||
std::env::var("SENDING_EMAIL_ADDRESS").expect("SENDING_EMAIL_ADDRESS must be set");
|
.expect("SENDING_EMAIL_ADDRESS must be set");
|
||||||
// new email message with sender name and email
|
// new email message with sender name and email
|
||||||
let mut email = Message::new(EmailAddress::new(sending_email, "Let's Organise"));
|
let mut email = Message::new(EmailAddress::new(sending_email, "Let's Organise"));
|
||||||
|
|
||||||
|
@ -22,10 +22,12 @@ impl ResponseError for ServiceError {
|
|||||||
match self {
|
match self {
|
||||||
ServiceError::InternalServerError => HttpResponse::InternalServerError()
|
ServiceError::InternalServerError => HttpResponse::InternalServerError()
|
||||||
.json("Internal Server Error, Please try later"),
|
.json("Internal Server Error, Please try later"),
|
||||||
ServiceError::BadRequest(ref message) => HttpResponse::BadRequest()
|
ServiceError::BadRequest(ref message) => {
|
||||||
.json(message),
|
HttpResponse::BadRequest().json(message)
|
||||||
ServiceError::Unauthorized => HttpResponse::Unauthorized()
|
}
|
||||||
.json("Unauthorized"),
|
ServiceError::Unauthorized => {
|
||||||
|
HttpResponse::Unauthorized().json("Unauthorized")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -45,7 +47,8 @@ impl From<DBError> for ServiceError {
|
|||||||
match error {
|
match error {
|
||||||
DBError::DatabaseError(kind, info) => {
|
DBError::DatabaseError(kind, info) => {
|
||||||
if let DatabaseErrorKind::UniqueViolation = kind {
|
if let DatabaseErrorKind::UniqueViolation = kind {
|
||||||
let message = info.details().unwrap_or_else(|| info.message()).to_string();
|
let message =
|
||||||
|
info.details().unwrap_or_else(|| info.message()).to_string();
|
||||||
return ServiceError::BadRequest(message);
|
return ServiceError::BadRequest(message);
|
||||||
}
|
}
|
||||||
ServiceError::InternalServerError
|
ServiceError::InternalServerError
|
||||||
|
@ -16,15 +16,15 @@ pub fn post_invitation(
|
|||||||
pool: web::Data<Pool>,
|
pool: web::Data<Pool>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = ServiceError> {
|
) -> impl Future<Item = HttpResponse, Error = ServiceError> {
|
||||||
// run diesel blocking code
|
// run diesel blocking code
|
||||||
web::block(move || create_invitation(invitation_data.into_inner().email, pool)).then(|res| {
|
web::block(move || create_invitation(invitation_data.into_inner().email, pool)).then(
|
||||||
match res {
|
|res| match res {
|
||||||
Ok(_) => Ok(HttpResponse::Ok().finish()),
|
Ok(_) => Ok(HttpResponse::Ok().finish()),
|
||||||
Err(err) => match err {
|
Err(err) => match err {
|
||||||
BlockingError::Error(service_error) => Err(service_error),
|
BlockingError::Error(service_error) => Err(service_error),
|
||||||
BlockingError::Canceled => Err(ServiceError::InternalServerError),
|
BlockingError::Canceled => Err(ServiceError::InternalServerError),
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
})
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_invitation(
|
fn create_invitation(
|
||||||
@ -36,10 +36,13 @@ fn create_invitation(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Diesel query
|
/// Diesel query
|
||||||
fn query(eml: String, pool: web::Data<Pool>) -> Result<Invitation, crate::errors::ServiceError> {
|
fn query(
|
||||||
|
eml: String,
|
||||||
|
pool: web::Data<Pool>,
|
||||||
|
) -> Result<Invitation, crate::errors::ServiceError> {
|
||||||
use crate::schema::invitations::dsl::invitations;
|
use crate::schema::invitations::dsl::invitations;
|
||||||
|
|
||||||
let new_invitation : Invitation = eml.into();
|
let new_invitation: Invitation = eml.into();
|
||||||
let conn: &PgConnection = &pool.get().unwrap();
|
let conn: &PgConnection = &pool.get().unwrap();
|
||||||
|
|
||||||
let inserted_invitation = diesel::insert_into(invitations)
|
let inserted_invitation = diesel::insert_into(invitations)
|
||||||
|
@ -31,7 +31,8 @@ fn main() -> std::io::Result<()> {
|
|||||||
let pool: models::Pool = r2d2::Pool::builder()
|
let pool: models::Pool = r2d2::Pool::builder()
|
||||||
.build(manager)
|
.build(manager)
|
||||||
.expect("Failed to create pool.");
|
.expect("Failed to create pool.");
|
||||||
let domain: String = std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string());
|
let domain: String =
|
||||||
|
std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string());
|
||||||
|
|
||||||
// Start http server
|
// Start http server
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
@ -51,13 +52,13 @@ fn main() -> std::io::Result<()> {
|
|||||||
// everything under '/api/' route
|
// everything under '/api/' route
|
||||||
.service(
|
.service(
|
||||||
web::scope("/api")
|
web::scope("/api")
|
||||||
|
.service(web::resource("/invitation").route(
|
||||||
|
web::post().to_async(invitation_handler::post_invitation),
|
||||||
|
))
|
||||||
.service(
|
.service(
|
||||||
web::resource("/invitation")
|
web::resource("/register/{invitation_id}").route(
|
||||||
.route(web::post().to_async(invitation_handler::post_invitation)),
|
web::post().to_async(register_handler::register_user),
|
||||||
)
|
),
|
||||||
.service(
|
|
||||||
web::resource("/register/{invitation_id}")
|
|
||||||
.route(web::post().to_async(register_handler::register_user)),
|
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/auth")
|
web::resource("/auth")
|
||||||
|
@ -31,8 +31,10 @@ pub struct Invitation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// any type that implements Into<String> can be used to create Invitation
|
// any type that implements Into<String> can be used to create Invitation
|
||||||
impl<T> From<T> for Invitation where
|
impl<T> From<T> for Invitation
|
||||||
T: Into<String> {
|
where
|
||||||
|
T: Into<String>,
|
||||||
|
{
|
||||||
fn from(email: T) -> Self {
|
fn from(email: T) -> Self {
|
||||||
Invitation {
|
Invitation {
|
||||||
id: uuid::Uuid::new_v4(),
|
id: uuid::Uuid::new_v4(),
|
||||||
|
@ -2,11 +2,11 @@
|
|||||||
name = "unix-socket"
|
name = "unix-socket"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
authors = ["Messense Lv <messense@icloud.com>"]
|
authors = ["Messense Lv <messense@icloud.com>"]
|
||||||
workspace = "../"
|
workspace = ".."
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
env_logger = "0.5"
|
env_logger = "0.5"
|
||||||
tokio-uds = "0.2"
|
tokio-uds = "0.2"
|
||||||
|
|
||||||
actix = "0.7"
|
actix-web = { version = "1.0.5", features = ["uds"] }
|
||||||
actix-web = "0.7"
|
|
||||||
|
@ -7,7 +7,7 @@ Hello world!
|
|||||||
|
|
||||||
Although this will only one thread for handling incoming connections
|
Although this will only one thread for handling incoming connections
|
||||||
according to the
|
according to the
|
||||||
[documentation](https://actix.github.io/actix-web/actix_web/struct.HttpServer.html#method.start_incoming).
|
[documentation](https://actix.github.io/actix-web/actix_web/struct.HttpServer.html#method.bind_uds).
|
||||||
|
|
||||||
And it does not delete the socket file (`/tmp/actix-uds.socket`) when stopping
|
And it does not delete the socket file (`/tmp/actix-uds.socket`) when stopping
|
||||||
the server so it will fail to start next time you run it unless you delete
|
the server so it will fail to start next time you run it unless you delete
|
||||||
|
@ -1,31 +1,22 @@
|
|||||||
extern crate actix;
|
use actix_web::{middleware, web, App, HttpRequest, HttpServer};
|
||||||
extern crate actix_web;
|
|
||||||
extern crate env_logger;
|
|
||||||
extern crate tokio_uds;
|
|
||||||
|
|
||||||
use actix::*;
|
fn index(_req: HttpRequest) -> &'static str {
|
||||||
use actix_web::{middleware, server, App, HttpRequest};
|
|
||||||
use tokio_uds::UnixListener;
|
|
||||||
|
|
||||||
fn index(_req: &HttpRequest) -> &'static str {
|
|
||||||
"Hello world!"
|
"Hello world!"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() -> std::io::Result<()> {
|
||||||
::std::env::set_var("RUST_LOG", "actix_web=info");
|
::std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
let sys = actix::System::new("unix-socket");
|
|
||||||
|
|
||||||
let listener = UnixListener::bind("/tmp/actix-uds.socket").expect("bind failed");
|
HttpServer::new(|| {
|
||||||
server::new(|| {
|
|
||||||
App::new()
|
App::new()
|
||||||
// enable logger
|
// enable logger - always register actix-web Logger middleware last
|
||||||
.middleware(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
.resource("/index.html", |r| r.f(|_| "Hello world!"))
|
.service(
|
||||||
.resource("/", |r| r.f(index))
|
web::resource("/index.html").route(web::get().to(|| "Hello world!")),
|
||||||
|
)
|
||||||
|
.service(web::resource("/").to(index))
|
||||||
})
|
})
|
||||||
.start_incoming(listener.incoming(), false);
|
.bind_uds("/tmp/actix-uds.socket")?
|
||||||
|
.run()
|
||||||
println!("Started http server: /tmp/actix-uds.socket");
|
|
||||||
let _ = sys.run();
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user