1
0
mirror of https://github.com/actix/examples synced 2025-06-26 09:17:41 +02:00

update deps

This commit is contained in:
Rob Ede
2022-10-26 16:51:27 +01:00
parent 83e987ed0c
commit ddda86784a
25 changed files with 672 additions and 858 deletions

View File

@ -5,6 +5,8 @@ edition = "2021"
[dependencies]
actix-web = "4"
actix-identity = "0.4"
actix-identity = "0.5"
actix-session = { version = "0.7", features = ["cookie-session"] }
env_logger = "0.9"
rand = "0.8"

View File

@ -1,23 +1,28 @@
use actix_identity::{CookieIdentityPolicy, Identity, IdentityService};
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use actix_identity::{Identity, IdentityMiddleware};
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
use actix_web::{
cookie::Key, middleware, web, App, HttpMessage as _, HttpRequest, HttpResponse, HttpServer,
};
use rand::Rng;
async fn index(id: Identity) -> String {
format!(
"Hello {}",
id.identity().unwrap_or_else(|| "Anonymous".to_owned())
id.id().unwrap_or_else(|_| "Anonymous".to_owned())
)
}
async fn login(id: Identity) -> HttpResponse {
id.remember("user1".to_owned());
async fn login(req: HttpRequest) -> HttpResponse {
Identity::login(&req.extensions(), "user1".to_owned()).unwrap();
HttpResponse::Found()
.insert_header(("location", "/"))
.finish()
}
async fn logout(id: Identity) -> HttpResponse {
id.forget();
id.logout();
HttpResponse::Found()
.insert_header(("location", "/"))
.finish()
@ -32,13 +37,16 @@ async fn main() -> std::io::Result<()> {
// private key for every project. Anyone with access to the key can generate
// authentication cookies for any user!
let private_key = rand::thread_rng().gen::<[u8; 32]>();
HttpServer::new(move || {
App::new()
.wrap(IdentityService::new(
CookieIdentityPolicy::new(&private_key)
.name("auth-example")
.secure(false),
))
.wrap(IdentityMiddleware::default())
.wrap(
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&private_key))
.cookie_name("auth-example".to_owned())
.cookie_secure(false)
.build(),
)
// enable logger - always register Actix Web Logger middleware last
.wrap(middleware::Logger::default())
.service(web::resource("/login").route(web::post().to(login)))

View File

@ -5,7 +5,8 @@ edition = "2021"
[dependencies]
actix-web = "4"
actix-identity = "0.4"
actix-identity = "0.5"
actix-session = { version = "0.7", features = ["cookie-session"] }
chrono = { version = "0.4", features = ["serde"] }
derive_more = "0.99.5"

View File

@ -1,7 +1,9 @@
use std::future::{ready, Ready};
use actix_identity::Identity;
use actix_web::{dev::Payload, web, Error, FromRequest, HttpRequest, HttpResponse};
use actix_web::{
dev::Payload, web, Error, FromRequest, HttpMessage as _, HttpRequest, HttpResponse,
};
use diesel::prelude::*;
use serde::Deserialize;
@ -27,7 +29,7 @@ impl FromRequest for LoggedUser {
fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
if let Ok(identity) = Identity::from_request(req, pl).into_inner() {
if let Some(user_json) = identity.identity() {
if let Ok(user_json) = identity.id() {
if let Ok(user) = serde_json::from_str(&user_json) {
return ready(Ok(user));
}
@ -39,21 +41,21 @@ impl FromRequest for LoggedUser {
}
pub async fn logout(id: Identity) -> HttpResponse {
id.forget();
HttpResponse::Ok().finish()
id.logout();
HttpResponse::NoContent().finish()
}
pub async fn login(
req: HttpRequest,
auth_data: web::Json<AuthData>,
id: Identity,
pool: web::Data<Pool>,
) -> Result<HttpResponse, actix_web::Error> {
let user = web::block(move || query(auth_data.into_inner(), pool)).await??;
let user_string = serde_json::to_string(&user).unwrap();
id.remember(user_string);
Identity::login(&req.extensions(), user_string).unwrap();
Ok(HttpResponse::Ok().finish())
Ok(HttpResponse::NoContent().finish())
}
pub async fn get_me(logged_user: LoggedUser) -> HttpResponse {

View File

@ -1,8 +1,9 @@
#[macro_use]
extern crate diesel;
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpServer};
use actix_identity::IdentityMiddleware;
use actix_session::{config::PersistentSession, storage::CookieSessionStore, SessionMiddleware};
use actix_web::{cookie::Key, middleware, web, App, HttpServer};
use diesel::{
prelude::*,
r2d2::{self, ConnectionManager},
@ -39,17 +40,21 @@ async fn main() -> std::io::Result<()> {
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.wrap(IdentityMiddleware::default())
.wrap(
SessionMiddleware::builder(
CookieSessionStore::default(),
Key::from(utils::SECRET_KEY.as_bytes()),
)
.session_lifecycle(PersistentSession::default().session_ttl(Duration::days(1)))
.cookie_name("auth-example".to_owned())
.cookie_secure(false)
.cookie_domain(Some(domain.clone()))
.cookie_path("/".to_owned())
.build(),
)
// enable logger
.wrap(middleware::Logger::default())
.wrap(IdentityService::new(
CookieIdentityPolicy::new(utils::SECRET_KEY.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
))
.app_data(web::JsonConfig::default().limit(4096))
// everything under '/api/' route
.service(
web::scope("/api")