diff --git a/actix_redis/Cargo.toml b/actix_redis/Cargo.toml index a716e624..b8014247 100644 --- a/actix_redis/Cargo.toml +++ b/actix_redis/Cargo.toml @@ -2,13 +2,15 @@ name = "actix_redis" version = "0.1.0" authors = ["dowwie "] +edition = "2018" +workspace = ".." [dependencies] -actix = "0.7.3" -actix-web = "0.7.3" -actix-redis = "0.5.1" +actix = "0.8.0-alpha.2" +actix-web = "1.0.0-alpha.1" +actix-redis = { git="https://github.com/actix/actix-redis.git" } futures = "0.1.23" redis-async = "0.4.0" serde = "1.0.71" serde_derive = "1.0.71" -env_logger = "0.5.12" +env_logger = "0.6" diff --git a/actix_redis/src/main.rs b/actix_redis/src/main.rs index e8072a21..a9ed3c4c 100644 --- a/actix_redis/src/main.rs +++ b/actix_redis/src/main.rs @@ -1,23 +1,13 @@ -extern crate actix; -extern crate actix_redis; -extern crate actix_web; -extern crate env_logger; -extern crate futures; #[macro_use] extern crate redis_async; -extern crate serde; #[macro_use] extern crate serde_derive; use actix::prelude::*; use actix_redis::{Command, Error as ARError, RedisActor}; -use actix_web::{ - http::Method, middleware, server, App, AsyncResponder, Error as AWError, - HttpRequest, HttpResponse, Json, -}; +use actix_web::{middleware, web, App, Error as AWError, HttpResponse, HttpServer}; use futures::future::{join_all, Future}; use redis_async::resp::RespValue; -use std::sync::Arc; #[derive(Deserialize)] pub struct CacheInfo { @@ -27,10 +17,10 @@ pub struct CacheInfo { } fn cache_stuff( - (info, req): (Json, HttpRequest), + info: web::Json, + redis: web::Data>, ) -> impl Future { let info = info.into_inner(); - let redis = req.state().redis_addr.clone(); let one = redis.send(Command(resp_array!["SET", "mydomain:one", info.one])); let two = redis.send(Command(resp_array!["SET", "mydomain:two", info.two])); @@ -46,26 +36,23 @@ fn cache_stuff( let info_set = join_all(vec![one, two, three].into_iter()); info_set - .map_err(AWError::from) - .and_then(|res: Vec>| - // successful operations return "OK", so confirm that all returned as so - if !res.iter().all(|res| match res { - Ok(RespValue::SimpleString(x)) if x=="OK" => true, - _ => false - }) { - Ok(HttpResponse::InternalServerError().finish()) - } else { - Ok(HttpResponse::Ok().body("successfully cached values")) - } - ) - .responder() + .map_err(AWError::from) + .and_then(|res: Vec>| + // successful operations return "OK", so confirm that all returned as so + if !res.iter().all(|res| match res { + Ok(RespValue::SimpleString(x)) if x=="OK" => true, + _ => false + }) { + Ok(HttpResponse::InternalServerError().finish()) + } else { + Ok(HttpResponse::Ok().body("successfully cached values")) + } + ) } fn del_stuff( - req: HttpRequest, + redis: web::Data>, ) -> impl Future { - let redis = req.state().redis_addr.clone(); - redis .send(Command(resp_array![ "DEL", @@ -83,33 +70,24 @@ fn del_stuff( Ok(HttpResponse::InternalServerError().finish()) } }) - .responder() } -pub struct AppState { - pub redis_addr: Arc>, -} - -fn main() { - ::std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info"); +fn main() -> std::io::Result<()> { + std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info"); env_logger::init(); - let sys = actix::System::new("actix_redis_ex"); - server::new(|| { - let redis_addr = Arc::new(RedisActor::start("127.0.0.1:6379")); - let app_state = AppState { redis_addr }; + HttpServer::new(|| { + let redis_addr = RedisActor::start("127.0.0.1:6379"); - App::with_state(app_state) - .middleware(middleware::Logger::default()) - .resource("/stuff", |r| { - r.method(Method::POST).with_async(cache_stuff); - r.method(Method::DELETE).with_async(del_stuff) - }) + App::new() + .data(redis_addr) + .wrap(middleware::Logger::default()) + .service( + web::resource("/stuff") + .route(web::post().to_async(cache_stuff)) + .route(web::delete().to_async(del_stuff)), + ) }) - .bind("0.0.0.0:8080") - .unwrap() - .workers(1) - .start(); - - let _ = sys.run(); + .bind("0.0.0.0:8080")? + .run() } diff --git a/actix_todo/Cargo.toml b/actix_todo/Cargo.toml index 736178d1..17a35307 100644 --- a/actix_todo/Cargo.toml +++ b/actix_todo/Cargo.toml @@ -6,9 +6,9 @@ workspace = ".." edition = "2018" [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } -actix-files = { git="https://github.com/actix/actix-web.git" } -actix-session = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" +actix-files = "0.1.0-alpha.1" +actix-session = "0.1.0-alpha.1" dotenv = "0.13.0" env_logger = "0.5.10" futures = "0.1.22" diff --git a/async_db/Cargo.toml b/async_db/Cargo.toml index 7848d1b7..2d322de3 100644 --- a/async_db/Cargo.toml +++ b/async_db/Cargo.toml @@ -7,7 +7,7 @@ workspace = ".." [dependencies] actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" dotenv = "0.10" env_logger = "0.5" diff --git a/async_ex1/Cargo.toml b/async_ex1/Cargo.toml index f89f97b5..1be43ae9 100644 --- a/async_ex1/Cargo.toml +++ b/async_ex1/Cargo.toml @@ -7,7 +7,7 @@ workspace = ".." [dependencies] actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git", features=["ssl"] } +actix-web = { version="1.0.0-alpha.1", features=["ssl"] } futures = "0.1" serde = "1.0.43" diff --git a/basics/Cargo.toml b/basics/Cargo.toml index 0147e333..4eb17bcc 100644 --- a/basics/Cargo.toml +++ b/basics/Cargo.toml @@ -7,9 +7,9 @@ edition = "2018" [dependencies] actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git" } -actix-files = { git="https://github.com/actix/actix-web.git" } -actix-session = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" +actix-files = "0.1.0-alpha.1" +actix-session = "0.1.0-alpha.1" futures = "0.1.25" env_logger = "0.5" diff --git a/cookie-auth/Cargo.toml b/cookie-auth/Cargo.toml index efeb709c..d728e3ed 100644 --- a/cookie-auth/Cargo.toml +++ b/cookie-auth/Cargo.toml @@ -6,5 +6,5 @@ edition = "2018" workspace = ".." [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" env_logger = "0.6" diff --git a/cookie-session/Cargo.toml b/cookie-session/Cargo.toml index d7bee4dd..ce876957 100644 --- a/cookie-session/Cargo.toml +++ b/cookie-session/Cargo.toml @@ -6,8 +6,8 @@ workspace = ".." edition = "2018" [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } -actix-session = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" +actix-session = "0.1.0-alpha.1" futures = "0.1" time = "0.1" diff --git a/diesel/Cargo.toml b/diesel/Cargo.toml index 4089a877..d8dfb918 100644 --- a/diesel/Cargo.toml +++ b/diesel/Cargo.toml @@ -6,7 +6,7 @@ workspace = ".." edition = "2018" [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" bytes = "0.4" env_logger = "0.6" diff --git a/error_handling/Cargo.toml b/error_handling/Cargo.toml index c4cb0973..7e05407c 100644 --- a/error_handling/Cargo.toml +++ b/error_handling/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" workspace = ".." [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" derive_more = "0.14.0" futures = "0.1.23" diff --git a/form/Cargo.toml b/form/Cargo.toml index a849fed4..150b9417 100644 --- a/form/Cargo.toml +++ b/form/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" workspace = ".." [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" serde = "1.0" serde_derive = "1.0" diff --git a/hello-world/Cargo.toml b/hello-world/Cargo.toml index d3d38429..502b1410 100644 --- a/hello-world/Cargo.toml +++ b/hello-world/Cargo.toml @@ -6,5 +6,5 @@ workspace = ".." edition = "2018" [dependencies] +actix-web = "1.0.0-alpha.1" env_logger = "0.6" -actix-web = { git="https://github.com/actix/actix-web.git" } diff --git a/http-full-proxy/Cargo.toml b/http-full-proxy/Cargo.toml index b7686cfe..f906fdd2 100644 --- a/http-full-proxy/Cargo.toml +++ b/http-full-proxy/Cargo.toml @@ -7,7 +7,7 @@ edition = "2018" [dependencies] actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" clap = "2.32.0" futures = "0.1.25" diff --git a/http-proxy/Cargo.toml b/http-proxy/Cargo.toml index ca1176d4..487d4580 100644 --- a/http-proxy/Cargo.toml +++ b/http-proxy/Cargo.toml @@ -15,7 +15,7 @@ path = "src/server.rs" [dependencies] actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" env_logger = "0.5" futures = "0.1" diff --git a/json/Cargo.toml b/json/Cargo.toml index c5d09827..82b525c8 100644 --- a/json/Cargo.toml +++ b/json/Cargo.toml @@ -6,7 +6,7 @@ workspace = ".." edition = "2018" [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" bytes = "0.4" futures = "0.1" diff --git a/juniper/Cargo.toml b/juniper/Cargo.toml index 07ac6365..ff47263a 100644 --- a/juniper/Cargo.toml +++ b/juniper/Cargo.toml @@ -6,7 +6,7 @@ workspace = ".." edition = "2018" [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" env_logger = "0.6" futures = "0.1" serde = "1.0" diff --git a/middleware/Cargo.toml b/middleware/Cargo.toml index 7905b56c..c5657087 100644 --- a/middleware/Cargo.toml +++ b/middleware/Cargo.toml @@ -7,6 +7,6 @@ workspace = ".." [dependencies] actix-service = "0.3.3" -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" futures = "0.1.25" env_logger = "0.6" \ No newline at end of file diff --git a/multipart/Cargo.toml b/multipart/Cargo.toml index 771e28f7..994c80fc 100644 --- a/multipart/Cargo.toml +++ b/multipart/Cargo.toml @@ -2,15 +2,16 @@ name = "multipart-example" version = "0.1.0" authors = ["Nikolay Kim "] -workspace = "../" +workspace = ".." +edition = "2018" [[bin]] name = "multipart" path = "src/main.rs" [dependencies] -env_logger = "*" -futures = "0.1" +#actix-web = "1.0.0-alpha.1" +actix-web = { git="https://github.com/actix/actix-web.git" } -actix = "0.7" -actix-web = "0.7" +env_logger = "0.6" +futures = "0.1.25" diff --git a/multipart/src/main.rs b/multipart/src/main.rs index 37c17bf6..40f22d38 100644 --- a/multipart/src/main.rs +++ b/multipart/src/main.rs @@ -1,44 +1,30 @@ -#![allow(unused_variables)] -extern crate actix; -extern crate actix_web; -extern crate env_logger; -extern crate futures; - use std::cell::Cell; use std::fs; use std::io::Write; -use actix_web::{ - dev, error, http, middleware, multipart, server, App, Error, FutureResponse, - HttpMessage, HttpRequest, HttpResponse, -}; - -use futures::future; +use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer}; +use futures::future::{err, Either}; use futures::{Future, Stream}; pub struct AppState { pub counter: Cell, } -pub fn save_file( - field: multipart::Field, -) -> Box> { +pub fn save_file(field: web::MultipartField) -> impl Future { let file_path_string = "upload.png"; let mut file = match fs::File::create(file_path_string) { Ok(file) => file, - Err(e) => return Box::new(future::err(error::ErrorInternalServerError(e))), + Err(e) => return Either::A(err(error::ErrorInternalServerError(e))), }; - Box::new( + Either::B( field .fold(0i64, move |acc, bytes| { - let rt = file - .write_all(bytes.as_ref()) + file.write_all(bytes.as_ref()) .map(|_| acc + bytes.len() as i64) .map_err(|e| { println!("file.write_all failed: {:?}", e); error::MultipartError::Payload(error::PayloadError::Io(e)) - }); - future::result(rt) + }) }) .map_err(|e| { println!("save_file failed, {:?}", e); @@ -48,13 +34,11 @@ pub fn save_file( } pub fn handle_multipart_item( - item: multipart::MultipartItem, + item: web::MultipartItem, ) -> Box> { match item { - multipart::MultipartItem::Field(field) => { - Box::new(save_file(field).into_stream()) - } - multipart::MultipartItem::Nested(mp) => Box::new( + web::MultipartItem::Field(field) => Box::new(save_file(field).into_stream()), + web::MultipartItem::Nested(mp) => Box::new( mp.map_err(error::ErrorInternalServerError) .map(handle_multipart_item) .flatten(), @@ -62,24 +46,26 @@ pub fn handle_multipart_item( } } -pub fn upload(req: HttpRequest) -> FutureResponse { - req.state().counter.set(req.state().counter.get() + 1); - println!("{:?}", req.state().counter.get()); - Box::new( - req.multipart() - .map_err(error::ErrorInternalServerError) - .map(handle_multipart_item) - .flatten() - .collect() - .map(|sizes| HttpResponse::Ok().json(sizes)) - .map_err(|e| { - println!("failed: {}", e); - e - }), - ) +pub fn upload( + multipart: web::Multipart, + counter: web::Data>, +) -> impl Future { + counter.set(counter.get() + 1); + println!("{:?}", counter.get()); + + multipart + .map_err(error::ErrorInternalServerError) + .map(handle_multipart_item) + .flatten() + .collect() + .map(|sizes| HttpResponse::Ok().json(sizes)) + .map_err(|e| { + println!("failed: {}", e); + e + }) } -fn index(_req: HttpRequest) -> Result { +fn index() -> HttpResponse { let html = r#" Upload Test @@ -90,28 +76,23 @@ fn index(_req: HttpRequest) -> Result { "#; - Ok(HttpResponse::Ok().body(html)) + HttpResponse::Ok().body(html) } -fn main() { - ::std::env::set_var("RUST_LOG", "actix_web=info"); +fn main() -> std::io::Result<()> { + std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info"); env_logger::init(); - let sys = actix::System::new("multipart-example"); - server::new(|| { - App::with_state(AppState { - counter: Cell::new(0), - }) - .middleware(middleware::Logger::default()) - .resource("/", |r| { - r.method(http::Method::GET).with(index); - r.method(http::Method::POST).with(upload); - }) + HttpServer::new(|| { + App::new() + .data(Cell::new(0usize)) + .wrap(middleware::Logger::default()) + .service( + web::resource("/") + .route(web::get().to(index)) + .route(web::post().to_async(upload)), + ) }) - .bind("127.0.0.1:8080") - .unwrap() - .start(); - - println!("Starting http server: 127.0.0.1:8080"); - let _ = sys.run(); + .bind("127.0.0.1:8080")? + .run() } diff --git a/r2d2/Cargo.toml b/r2d2/Cargo.toml index a0b5e037..0f6d7b57 100644 --- a/r2d2/Cargo.toml +++ b/r2d2/Cargo.toml @@ -3,11 +3,11 @@ name = "r2d2-example" version = "0.1.0" authors = ["Nikolay Kim "] edition = "2018" -workspace = "../" +workspace = ".." [dependencies] actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" futures = "0.1" env_logger = "0.6" diff --git a/redis-session/Cargo.toml b/redis-session/Cargo.toml index 8b6152a6..5198d902 100644 --- a/redis-session/Cargo.toml +++ b/redis-session/Cargo.toml @@ -2,10 +2,12 @@ name = "redis-session" version = "0.1.0" authors = ["Nikolay Kim "] -workspace = "../" +workspace = ".." +edition = "2018" [dependencies] -env_logger = "0.5" -actix = "0.7" -actix-web = "0.7.3" -actix-redis = { version = "0.5.1", features = ["web"] } +actix = "0.8.0-alpha.2" +actix-web = "1.0.0-alpha.1" +actix-session = "0.1.0-alpha.1" +actix-redis = { git = "https://github.com/actix/actix-redis.git", features = ["web"] } +env_logger = "0.6" diff --git a/redis-session/src/main.rs b/redis-session/src/main.rs index 18a68e15..0c49c6bf 100644 --- a/redis-session/src/main.rs +++ b/redis-session/src/main.rs @@ -1,50 +1,38 @@ //! Example of redis based session //! //! [User guide](https://actix.rs/book/actix-web/sec-9-middlewares.html#user-sessions) -extern crate actix; -extern crate actix_redis; -extern crate actix_web; -extern crate env_logger; - -use actix_redis::RedisSessionBackend; -use actix_web::middleware::session::{RequestSession, SessionStorage}; -use actix_web::{middleware, server, App, HttpRequest, HttpResponse, Result}; +use actix_redis::RedisSession; +use actix_session::Session; +use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Result}; /// simple handler -fn index(req: &HttpRequest) -> Result { +fn index(req: HttpRequest, session: Session) -> Result { println!("{:?}", req); // session - if let Some(count) = req.session().get::("counter")? { + if let Some(count) = session.get::("counter")? { println!("SESSION value: {}", count); - req.session().set("counter", count + 1)?; + session.set("counter", count + 1)?; } else { - req.session().set("counter", 1)?; + session.set("counter", 1)?; } Ok("Welcome!".into()) } -fn main() { - ::std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info"); +fn main() -> std::io::Result<()> { + std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info"); env_logger::init(); - let sys = actix::System::new("basic-example"); - server::new(|| { + HttpServer::new(|| { App::new() // enable logger - .middleware(middleware::Logger::default()) + .wrap(middleware::Logger::default()) // redis session middleware - .middleware(SessionStorage::new(RedisSessionBackend::new( - "127.0.0.1:6379", - &[0; 32], - ))) + .wrap(RedisSession::new("127.0.0.1:6379", &[0; 32])) // register simple route, handle all methods - .resource("/", |r| r.f(index)) + .service(web::resource("/").to(index)) }) - .bind("127.0.0.1:8080") - .unwrap() - .start(); - - let _ = sys.run(); + .bind("127.0.0.1:8080")? + .run() } diff --git a/simple-auth-server/Cargo.toml b/simple-auth-server/Cargo.toml index 25ba9407..0c6a42be 100644 --- a/simple-auth-server/Cargo.toml +++ b/simple-auth-server/Cargo.toml @@ -2,18 +2,22 @@ name = "simple-auth-server" version = "0.1.0" authors = ["mygnu "] +edition = "2018" +workspace = ".." [dependencies] -actix = "0.7.7" -actix-web = "0.7.14" +actix = { version = "0.8.0-alpha.2", features = ["http"] } +actix-web = "1.0.0-alpha.1" +actix-files = "0.1.0-alpha.1" + bcrypt = "0.2.1" chrono = { version = "0.4.6", features = ["serde"] } diesel = { version = "1.3.3", features = ["postgres", "uuid", "r2d2", "chrono"] } dotenv = "0.13.0" +derive_more = "0.14" env_logger = "0.6.0" -failure = "0.1.3" jsonwebtoken = "5.0" -futures = "0.1" +futures = "0.1.25" r2d2 = "0.8.3" serde_derive="1.0.80" serde_json="1.0" diff --git a/simple-auth-server/src/app.rs b/simple-auth-server/src/app.rs deleted file mode 100644 index 05fdf2f7..00000000 --- a/simple-auth-server/src/app.rs +++ /dev/null @@ -1,56 +0,0 @@ -use actix::prelude::*; -use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService}; -use actix_web::{fs, http::Method, middleware::Logger, App}; -use auth_routes::{get_me, login, logout}; -use chrono::Duration; -use invitation_routes::register_email; -use models::DbExecutor; -use register_routes::register_user; - -pub struct AppState { - pub db: Addr, -} - -/// creates and returns the app after mounting all routes/resources -pub fn create_app(db: Addr) -> App { - // secret is a random minimum 32 bytes long base 64 string - let secret: String = - std::env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(8)); - let domain: String = - std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string()); - - App::with_state(AppState { db }) - .middleware(Logger::default()) - .middleware(IdentityService::new( - CookieIdentityPolicy::new(secret.as_bytes()) - .name("auth") - .path("/") - .domain(domain.as_str()) - .max_age(Duration::days(1)) - .secure(false), // this can only be true if you have https - )) - // everything under '/api/' route - .scope("/api", |api| { - // routes for authentication - api.resource("/auth", |r| { - r.method(Method::POST).with(login); - r.method(Method::DELETE).with(logout); - r.method(Method::GET).with(get_me); - }) - // routes to invitation - .resource("/invitation", |r| { - r.method(Method::POST).with(register_email); - }) - // routes to register as a user after the - .resource("/register/{invitation_id}", |r| { - r.method(Method::POST).with(register_user); - }) - }) - // serve static files - .handler( - "/", - fs::StaticFiles::new("./static/") - .unwrap() - .index_file("index.html"), - ) -} diff --git a/simple-auth-server/src/auth_handler.rs b/simple-auth-server/src/auth_handler.rs index 161a951f..13eb1476 100644 --- a/simple-auth-server/src/auth_handler.rs +++ b/simple-auth-server/src/auth_handler.rs @@ -1,10 +1,12 @@ use actix::{Handler, Message}; -use actix_web::{middleware::identity::RequestIdentity, FromRequest, HttpRequest}; +use actix_web::{dev::ServiceFromRequest, Error}; +use actix_web::{middleware::identity::Identity, FromRequest, HttpRequest}; use bcrypt::verify; use diesel::prelude::*; -use errors::ServiceError; -use models::{DbExecutor, SlimUser, User}; -use utils::decode_token; + +use crate::errors::ServiceError; +use crate::models::{DbExecutor, SlimUser, User}; +use crate::utils::decode_token; #[derive(Debug, Deserialize)] pub struct AuthData { @@ -19,7 +21,7 @@ impl Message for AuthData { impl Handler for DbExecutor { type Result = Result; fn handle(&mut self, msg: AuthData, _: &mut Self::Context) -> Self::Result { - use schema::users::dsl::{email, users}; + use crate::schema::users::dsl::{email, users}; let conn: &PgConnection = &self.0.get().unwrap(); let mut items = users.filter(email.eq(&msg.email)).load::(conn)?; @@ -44,14 +46,15 @@ impl Handler for DbExecutor { // simple aliasing makes the intentions clear and its more readable pub type LoggedUser = SlimUser; -impl FromRequest for LoggedUser { - type Config = (); - type Result = Result; - fn from_request(req: &HttpRequest, _: &Self::Config) -> Self::Result { - if let Some(identity) = req.identity() { +impl

FromRequest

for LoggedUser { + type Error = Error; + type Future = Result; + + fn from_request(req: &mut ServiceFromRequest

) -> Self::Future { + if let Some(identity) = Identity::from_request(req)?.identity() { let user: SlimUser = decode_token(&identity)?; return Ok(user as LoggedUser); } - Err(ServiceError::Unauthorized) + Err(ServiceError::Unauthorized.into()) } } diff --git a/simple-auth-server/src/auth_routes.rs b/simple-auth-server/src/auth_routes.rs index 90cafec4..269c3a67 100644 --- a/simple-auth-server/src/auth_routes.rs +++ b/simple-auth-server/src/auth_routes.rs @@ -1,34 +1,32 @@ -use actix_web::middleware::identity::RequestIdentity; -use actix_web::{ - AsyncResponder, FutureResponse, HttpRequest, HttpResponse, Json, ResponseError, -}; -use futures::future::Future; -use utils::create_token; +use actix::Addr; +use actix_web::middleware::identity::Identity; +use actix_web::{web, Error, HttpRequest, HttpResponse, Responder, ResponseError}; +use futures::Future; -use app::AppState; -use auth_handler::{AuthData, LoggedUser}; +use crate::auth_handler::{AuthData, LoggedUser}; +use crate::models::DbExecutor; +use crate::utils::create_token; pub fn login( - (auth_data, req): (Json, HttpRequest), -) -> FutureResponse { - req.state() - .db - .send(auth_data.into_inner()) + auth_data: web::Json, + id: Identity, + db: web::Data>, +) -> impl Future { + db.send(auth_data.into_inner()) .from_err() .and_then(move |res| match res { Ok(user) => { let token = create_token(&user)?; - req.remember(token); + id.remember(token); Ok(HttpResponse::Ok().into()) } Err(err) => Ok(err.error_response()), }) - .responder() } -pub fn logout(req: HttpRequest) -> HttpResponse { - req.forget(); - HttpResponse::Ok().into() +pub fn logout(id: Identity) -> impl Responder { + id.forget(); + HttpResponse::Ok() } pub fn get_me(logged_user: LoggedUser) -> HttpResponse { diff --git a/simple-auth-server/src/email_service.rs b/simple-auth-server/src/email_service.rs index d9854f49..290d37ab 100644 --- a/simple-auth-server/src/email_service.rs +++ b/simple-auth-server/src/email_service.rs @@ -1,4 +1,4 @@ -use models::Invitation; +use crate::models::Invitation; use sparkpost::transmission::{ EmailAddress, Message, Options, Recipient, Transmission, TransmissionResponse, }; diff --git a/simple-auth-server/src/errors.rs b/simple-auth-server/src/errors.rs index 0be63125..bac56094 100644 --- a/simple-auth-server/src/errors.rs +++ b/simple-auth-server/src/errors.rs @@ -1,17 +1,18 @@ use actix_web::{error::ResponseError, HttpResponse}; +use derive_more::Display; use diesel::result::{DatabaseErrorKind, Error}; use std::convert::From; use uuid::ParseError; -#[derive(Fail, Debug)] +#[derive(Debug, Display)] pub enum ServiceError { - #[fail(display = "Internal Server Error")] + #[display(fmt = "Internal Server Error")] InternalServerError, - #[fail(display = "BadRequest: {}", _0)] + #[display(fmt = "BadRequest: {}", _0)] BadRequest(String), - #[fail(display = "Unauthorized")] + #[display(fmt = "Unauthorized")] Unauthorized, } diff --git a/simple-auth-server/src/invitation_handler.rs b/simple-auth-server/src/invitation_handler.rs index ac117f79..b0a8ceb7 100644 --- a/simple-auth-server/src/invitation_handler.rs +++ b/simple-auth-server/src/invitation_handler.rs @@ -1,10 +1,11 @@ use actix::{Handler, Message}; use chrono::{Duration, Local}; use diesel::{self, prelude::*}; -use errors::ServiceError; -use models::{DbExecutor, Invitation}; use uuid::Uuid; +use crate::errors::ServiceError; +use crate::models::{DbExecutor, Invitation}; + #[derive(Deserialize)] pub struct CreateInvitation { pub email: String, @@ -18,7 +19,7 @@ impl Handler for DbExecutor { type Result = Result; fn handle(&mut self, msg: CreateInvitation, _: &mut Self::Context) -> Self::Result { - use schema::invitations::dsl::*; + use crate::schema::invitations::dsl::*; let conn: &PgConnection = &self.0.get().unwrap(); // creating a new Invitation object with expired at time that is 24 hours from now diff --git a/simple-auth-server/src/invitation_routes.rs b/simple-auth-server/src/invitation_routes.rs index bd6a46c6..ea76bca2 100644 --- a/simple-auth-server/src/invitation_routes.rs +++ b/simple-auth-server/src/invitation_routes.rs @@ -1,18 +1,16 @@ -use actix_web::{ - AsyncResponder, FutureResponse, HttpResponse, Json, ResponseError, State, -}; +use actix::Addr; +use actix_web::{web, Error, HttpResponse, ResponseError}; use futures::future::Future; -use app::AppState; -use email_service::send_invitation; -use invitation_handler::CreateInvitation; +use crate::email_service::send_invitation; +use crate::invitation_handler::CreateInvitation; +use crate::models::DbExecutor; pub fn register_email( - (signup_invitation, state): (Json, State), -) -> FutureResponse { - state - .db - .send(signup_invitation.into_inner()) + signup_invitation: web::Json, + db: web::Data>, +) -> impl Future { + db.send(signup_invitation.into_inner()) .from_err() .and_then(|db_response| match db_response { Ok(invitation) => { @@ -21,5 +19,4 @@ pub fn register_email( } Err(err) => Ok(err.error_response()), }) - .responder() } diff --git a/simple-auth-server/src/main.rs b/simple-auth-server/src/main.rs index 5c1b3c27..90024095 100644 --- a/simple-auth-server/src/main.rs +++ b/simple-auth-server/src/main.rs @@ -1,26 +1,21 @@ -// to avoid the warning from diesel macros -#![allow(proc_macro_derive_resolution_fallback)] +#![allow(unused_imports)] -extern crate actix; -extern crate actix_web; -extern crate bcrypt; -extern crate chrono; -extern crate dotenv; -extern crate env_logger; -extern crate futures; -extern crate jsonwebtoken as jwt; -extern crate r2d2; -extern crate serde; -extern crate sparkpost; -extern crate uuid; #[macro_use] extern crate diesel; #[macro_use] extern crate serde_derive; -#[macro_use] -extern crate failure; -mod app; +use actix::prelude::*; +use actix_files as fs; +use actix_web::middleware::{ + identity::{CookieIdentityPolicy, IdentityService}, + Logger, +}; +use actix_web::{web, App, HttpServer}; +use chrono::Duration; +use diesel::{r2d2::ConnectionManager, PgConnection}; +use dotenv::dotenv; + mod auth_handler; mod auth_routes; mod email_service; @@ -33,20 +28,17 @@ mod register_routes; mod schema; mod utils; -use actix::prelude::*; -use actix_web::server; -use diesel::{r2d2::ConnectionManager, PgConnection}; -use dotenv::dotenv; -use models::DbExecutor; -use std::env; +use crate::models::DbExecutor; -fn main() { +fn main() -> std::io::Result<()> { dotenv().ok(); - std::env::set_var("RUST_LOG", "simple-auth-server=debug,actix_web=info"); - std::env::set_var("RUST_BACKTRACE", "1"); + std::env::set_var( + "RUST_LOG", + "simple-auth-server=debug,actix_web=info,actix_server=info", + ); env_logger::init(); - let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); - let sys = actix::System::new("Actix_Tutorial"); + + let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); // create db connection pool let manager = ConnectionManager::::new(database_url); @@ -57,10 +49,49 @@ fn main() { let address: Addr = SyncArbiter::start(4, move || DbExecutor(pool.clone())); - server::new(move || app::create_app(address.clone())) - .bind("127.0.0.1:3000") - .expect("Can not bind to '127.0.0.1:3000'") - .start(); + HttpServer::new(move || { + // secret is a random minimum 32 bytes long base 64 string + let secret: String = + std::env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(8)); + let domain: String = + std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string()); - sys.run(); + App::new() + .data(address.clone()) + .wrap(Logger::default()) + .wrap(IdentityService::new( + CookieIdentityPolicy::new(secret.as_bytes()) + .name("auth") + .path("/") + .domain(domain.as_str()) + .max_age(Duration::days(1)) + .secure(false), // this can only be true if you have https + )) + // everything under '/api/' route + .service( + web::scope("/api") + // routes for authentication + .service( + web::resource("/auth") + .route(web::post().to_async(auth_routes::login)) + .route(web::delete().to(auth_routes::logout)) + .route(web::get().to_async(auth_routes::get_me)), + ) + // routes to invitation + .service( + web::resource("/invitation").route( + web::post().to_async(invitation_routes::register_email), + ), + ) + // routes to register as a user after the + .service( + web::resource("/register/{invitation_id}") + .route(web::post().to_async(register_routes::register_user)), + ), + ) + // serve static files + .service(fs::Files::new("/", "./static/").index_file("index.html")) + }) + .bind("127.0.0.1:3000")? + .run() } diff --git a/simple-auth-server/src/models.rs b/simple-auth-server/src/models.rs index 651ad9f3..76dcfac7 100644 --- a/simple-auth-server/src/models.rs +++ b/simple-auth-server/src/models.rs @@ -5,7 +5,7 @@ use diesel::r2d2::{ConnectionManager, Pool}; use std::convert::From; use uuid::Uuid; -use schema::{invitations, users}; +use crate::schema::{invitations, users}; /// This is db executor actor. can be run in parallel pub struct DbExecutor(pub Pool>); diff --git a/simple-auth-server/src/register_handler.rs b/simple-auth-server/src/register_handler.rs index 961061b0..04fe164e 100644 --- a/simple-auth-server/src/register_handler.rs +++ b/simple-auth-server/src/register_handler.rs @@ -1,11 +1,12 @@ use actix::{Handler, Message}; use chrono::Local; use diesel::prelude::*; -use errors::ServiceError; -use models::{DbExecutor, Invitation, SlimUser, User}; -use utils::hash_password; use uuid::Uuid; +use crate::errors::ServiceError; +use crate::models::{DbExecutor, Invitation, SlimUser, User}; +use crate::utils::hash_password; + // UserData is used to extract data from a post request by the client #[derive(Debug, Deserialize)] pub struct UserData { @@ -26,8 +27,8 @@ impl Message for RegisterUser { impl Handler for DbExecutor { type Result = Result; fn handle(&mut self, msg: RegisterUser, _: &mut Self::Context) -> Self::Result { - use schema::invitations::dsl::{id, invitations}; - use schema::users::dsl::users; + use crate::schema::invitations::dsl::{id, invitations}; + use crate::schema::users::dsl::users; let conn: &PgConnection = &self.0.get().unwrap(); // try parsing the string provided by the user as url parameter diff --git a/simple-auth-server/src/register_routes.rs b/simple-auth-server/src/register_routes.rs index 79b9f9a2..19b3866f 100644 --- a/simple-auth-server/src/register_routes.rs +++ b/simple-auth-server/src/register_routes.rs @@ -1,27 +1,25 @@ -use actix_web::{ - AsyncResponder, FutureResponse, HttpResponse, Json, Path, ResponseError, State, -}; -use futures::future::Future; +use actix::Addr; +use actix_web::{web, Error, HttpResponse, ResponseError}; +use futures::Future; -use app::AppState; -use register_handler::{RegisterUser, UserData}; +use crate::models::DbExecutor; +use crate::register_handler::{RegisterUser, UserData}; pub fn register_user( - (invitation_id, user_data, state): (Path, Json, State), -) -> FutureResponse { + invitation_id: web::Path, + user_data: web::Json, + db: web::Data>, +) -> impl Future { let msg = RegisterUser { // into_inner() returns the inner string value from Path invitation_id: invitation_id.into_inner(), password: user_data.password.clone(), }; - state - .db - .send(msg) + db.send(msg) .from_err() .and_then(|db_response| match db_response { Ok(slim_user) => Ok(HttpResponse::Ok().json(slim_user)), Err(service_error) => Ok(service_error.error_response()), }) - .responder() } diff --git a/simple-auth-server/src/utils.rs b/simple-auth-server/src/utils.rs index 1f65d3e8..37035277 100644 --- a/simple-auth-server/src/utils.rs +++ b/simple-auth-server/src/utils.rs @@ -1,14 +1,13 @@ use bcrypt::{hash, DEFAULT_COST}; use chrono::{Duration, Local}; -use errors::ServiceError; -use jwt::{decode, encode, Header, Validation}; -use models::SlimUser; -use std::convert::From; -use std::env; +use jsonwebtoken::{decode, encode, Header, Validation}; + +use crate::errors::ServiceError; +use crate::models::SlimUser; pub fn hash_password(plain: &str) -> Result { // get the hashing cost from the env variable or use default - let hashing_cost: u32 = match env::var("HASH_ROUNDS") { + let hashing_cost: u32 = match std::env::var("HASH_ROUNDS") { Ok(cost) => cost.parse().unwrap_or(DEFAULT_COST), _ => DEFAULT_COST, }; @@ -64,5 +63,5 @@ pub fn decode_token(token: &str) -> Result { } fn get_secret() -> String { - env::var("JWT_SECRET").unwrap_or_else(|_| "my secret".into()) + std::env::var("JWT_SECRET").unwrap_or_else(|_| "my secret".into()) } diff --git a/state/Cargo.toml b/state/Cargo.toml index 39bf08a7..962b35d8 100644 --- a/state/Cargo.toml +++ b/state/Cargo.toml @@ -6,7 +6,6 @@ workspace = ".." edition = "2018" [dependencies] -actix-web = { git="https://github.com/actix/actix-web.git" } - -futures = "0.1" +actix-web = "1.0.0-alpha.1" +futures = "0.1.25" env_logger = "0.6" diff --git a/static_index/Cargo.toml b/static_index/Cargo.toml index 2dcdba30..6ae309a8 100644 --- a/static_index/Cargo.toml +++ b/static_index/Cargo.toml @@ -9,5 +9,5 @@ edition = "2018" futures = "0.1" env_logger = "0.5" -actix-web = { git="https://github.com/actix/actix-web.git" } -actix-files = { git="https://github.com/actix/actix-web.git" } +actix-web = "1.0.0-alpha.1" +actix-files = "0.1.0-alpha.1" diff --git a/template_askama/Cargo.toml b/template_askama/Cargo.toml index 242087ac..68ca3a9f 100644 --- a/template_askama/Cargo.toml +++ b/template_askama/Cargo.toml @@ -6,9 +6,9 @@ workspace = ".." edition = "2018" [dependencies] +actix-web = "1.0.0-alpha.1" env_logger = "0.6" askama = "0.6" -actix-web = { git="https://github.com/actix/actix-web.git" } [build-dependencies] askama = "0.6" diff --git a/template_askama/src/main.rs b/template_askama/src/main.rs index b27e94af..b07879ab 100644 --- a/template_askama/src/main.rs +++ b/template_askama/src/main.rs @@ -1,6 +1,3 @@ -#[macro_use] -extern crate askama; - use std::collections::HashMap; use actix_web::{web, App, HttpResponse, HttpServer, Result}; diff --git a/template_tera/Cargo.toml b/template_tera/Cargo.toml index ff35ad15..81ecb160 100644 --- a/template_tera/Cargo.toml +++ b/template_tera/Cargo.toml @@ -7,5 +7,5 @@ edition = "2018" [dependencies] env_logger = "0.6" -tera = "*" -actix-web = { git="https://github.com/actix/actix-web.git" } +tera = "0.11" +actix-web = "1.0.0-alpha.1" diff --git a/template_yarte/Cargo.toml b/template_yarte/Cargo.toml index 47a03b22..328052ee 100644 --- a/template_yarte/Cargo.toml +++ b/template_yarte/Cargo.toml @@ -4,14 +4,12 @@ version = "0.0.1" authors = ["Rust-iendo Barcelona "] publish = false edition = "2018" - workspace = ".." [dependencies] +actix-web = "1.0.0-alpha.1" env_logger = "0.6" - yarte = "0.1" -actix-web = { git="https://github.com/actix/actix-web.git" } [build-dependencies] yarte = "0.1" diff --git a/tls/Cargo.toml b/tls/Cargo.toml index 0442f206..6e9be047 100644 --- a/tls/Cargo.toml +++ b/tls/Cargo.toml @@ -10,8 +10,7 @@ name = "tls-server" path = "src/main.rs" [dependencies] -env_logger = "0.5" -openssl = { version="0.10" } - actix-rt = "0.2" -actix-web = { git="https://github.com/actix/actix-web.git", features=["ssl"] } +actix-web = { version="1.0.0-alpha.1", features=["ssl"] } +env_logger = "0.6" +openssl = { version="0.10" } diff --git a/web-cors/backend/Cargo.toml b/web-cors/backend/Cargo.toml index f78d7adc..c50eb197 100644 --- a/web-cors/backend/Cargo.toml +++ b/web-cors/backend/Cargo.toml @@ -3,16 +3,13 @@ name = "actix-web-cors" version = "0.1.0" authors = ["krircc "] workspace = "../../" +edition = "2018" [dependencies] +actix-web = "1.0.0-alpha.1" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" -http = "0.1" - -actix = "0.7" -actix-web = "0.7" - dotenv = "0.10" -env_logger = "0.5" +env_logger = "0.6" futures = "0.1" diff --git a/web-cors/backend/src/main.rs b/web-cors/backend/src/main.rs index 2fcec25b..5d951e03 100644 --- a/web-cors/backend/src/main.rs +++ b/web-cors/backend/src/main.rs @@ -1,49 +1,29 @@ #[macro_use] extern crate serde_derive; -extern crate actix; -extern crate actix_web; -extern crate env_logger; -extern crate futures; -extern crate serde; -extern crate serde_json; use actix_web::{ - http::{header, Method}, - middleware, - middleware::cors::Cors, - server, App, + http::header, middleware::cors::Cors, middleware::Logger, web, App, HttpServer, }; -use std::env; mod user; -use user::info; -fn main() { - env::set_var("RUST_LOG", "actix_web=info"); +fn main() -> std::io::Result<()> { + std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); - let sys = actix::System::new("Actix-web-CORS"); - - server::new(move || { + HttpServer::new(move || { App::new() - .middleware(middleware::Logger::default()) - .configure(|app| { - Cors::for_app(app) + .wrap( + Cors::new() .allowed_origin("http://localhost:1234") .allowed_methods(vec!["GET", "POST"]) .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT]) .allowed_header(header::CONTENT_TYPE) - .max_age(3600) - .resource("/user/info", |r| { - r.method(Method::POST).with(info); - }) - .register() - }) + .max_age(3600), + ) + .wrap(Logger::default()) + .service(web::resource("/user/info").route(web::post().to(user::info))) }) - .bind("127.0.0.1:8000") - .unwrap() - .shutdown_timeout(2) - .start(); - - let _ = sys.run(); + .bind("127.0.0.1:8000")? + .run() } diff --git a/web-cors/backend/src/user.rs b/web-cors/backend/src/user.rs index aca44cbf..ed795589 100644 --- a/web-cors/backend/src/user.rs +++ b/web-cors/backend/src/user.rs @@ -1,4 +1,4 @@ -use actix_web::{Json, Result}; +use actix_web::web; #[derive(Deserialize, Serialize, Debug)] pub struct Info { @@ -8,12 +8,12 @@ pub struct Info { confirm_password: String, } -pub fn info(info: Json) -> Result> { +pub fn info(info: web::Json) -> web::Json { println!("=========={:?}=========", info); - Ok(Json(Info { + web::Json(Info { username: info.username.clone(), email: info.email.clone(), password: info.password.clone(), confirm_password: info.confirm_password.clone(), - })) + }) } diff --git a/websocket/Cargo.toml b/websocket/Cargo.toml index a68b058f..2ceab26e 100644 --- a/websocket/Cargo.toml +++ b/websocket/Cargo.toml @@ -14,10 +14,10 @@ path = "src/main.rs" #path = "src/client.rs" [dependencies] -actix = { git="https://github.com/actix/actix.git" } -actix-web = { git="https://github.com/actix/actix-web.git" } -actix-web-actors = { git="https://github.com/actix/actix-web.git" } -actix-files = { git="https://github.com/actix/actix-web.git" } +actix = "0.8.0-alpha.1" +actix-web = "1.0.0-alpha.1" +actix-web-actors = "1.0.0-alpha.1" +actix-files = "0.1.0-alpha.1" env_logger = "0.6" futures = "0.1" bytes = "0.4" \ No newline at end of file diff --git a/websocket/src/client.rs b/websocket/src/client.rs index 7cb5fa3b..11f827bb 100644 --- a/websocket/src/client.rs +++ b/websocket/src/client.rs @@ -1,16 +1,9 @@ //! Simple websocket client. - -#![allow(unused_variables)] -extern crate actix; -extern crate actix_web; -extern crate env_logger; -extern crate futures; - use std::time::Duration; use std::{io, thread}; use actix::*; -use actix_web::ws::{Client, ClientWriter, Message, ProtocolError}; +use actix_web::client::{Client, ClientWriter, Message, ProtocolError}; use futures::Future; fn main() {