1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

add session ttl customization example

This commit is contained in:
Rob Ede 2022-08-28 18:39:28 +01:00
parent d259177eab
commit fcd013fcde
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
18 changed files with 84 additions and 60 deletions

View File

@ -1,5 +1,4 @@
use actix_identity::Identity; use actix_identity::{CookieIdentityPolicy, Identity, IdentityService};
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpResponse, HttpServer}; use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use rand::Rng; use rand::Rng;

View File

@ -5,8 +5,14 @@
//! //!
//! [User guide](https://actix.rs/docs/middleware/#user-sessions) //! [User guide](https://actix.rs/docs/middleware/#user-sessions)
use actix_session::{storage::CookieSessionStore, Session, SessionMiddleware}; use actix_session::{
use actix_web::{cookie::Key, middleware::Logger, web, App, HttpRequest, HttpServer, Result}; config::PersistentSession, storage::CookieSessionStore, Session, SessionMiddleware,
};
use actix_web::{
cookie::{self, Key},
middleware::Logger,
web, App, HttpRequest, HttpServer, Result,
};
/// simple index handler with session /// simple index handler with session
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> { async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
@ -39,6 +45,10 @@ async fn main() -> std::io::Result<()> {
.wrap( .wrap(
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64])) SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
.cookie_secure(false) .cookie_secure(false)
// customize session and cookie expiration
.session_lifecycle(
PersistentSession::default().session_ttl(cookie::time::Duration::hours(2)),
)
.build(), .build(),
) )
.service(web::resource("/").to(index)) .service(web::resource("/").to(index))

View File

@ -2,13 +2,14 @@ use std::future::{ready, Ready};
use actix_identity::Identity; use actix_identity::Identity;
use actix_web::{dev::Payload, web, Error, FromRequest, HttpRequest, HttpResponse}; use actix_web::{dev::Payload, web, Error, FromRequest, HttpRequest, HttpResponse};
use diesel::prelude::*; use diesel::{prelude::*, PgConnection};
use diesel::PgConnection;
use serde::Deserialize; use serde::Deserialize;
use crate::errors::ServiceError; use crate::{
use crate::models::{Pool, SlimUser, User}; errors::ServiceError,
use crate::utils::verify; models::{Pool, SlimUser, User},
utils::verify,
};
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct AuthData { pub struct AuthData {

View File

@ -2,8 +2,10 @@ use actix_web::{web, HttpResponse};
use diesel::{prelude::*, PgConnection}; use diesel::{prelude::*, PgConnection};
use serde::Deserialize; use serde::Deserialize;
use crate::email_service::send_invitation; use crate::{
use crate::models::{Invitation, Pool}; email_service::send_invitation,
models::{Invitation, Pool},
};
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct InvitationData { pub struct InvitationData {

View File

@ -3,8 +3,10 @@ extern crate diesel;
use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpServer}; use actix_web::{middleware, web, App, HttpServer};
use diesel::prelude::*; use diesel::{
use diesel::r2d2::{self, ConnectionManager}; prelude::*,
r2d2::{self, ConnectionManager},
};
use time::Duration; use time::Duration;
mod auth_handler; mod auth_handler;

View File

@ -2,9 +2,11 @@ use actix_web::{web, HttpResponse};
use diesel::prelude::*; use diesel::prelude::*;
use serde::Deserialize; use serde::Deserialize;
use crate::errors::ServiceError; use crate::{
use crate::models::{Invitation, Pool, SlimUser, User}; errors::ServiceError,
use crate::utils::hash_password; models::{Invitation, Pool, SlimUser, User},
utils::hash_password,
};
// UserData is used to extract data from a post request by the client // UserData is used to extract data from a post request by the client
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@ -34,8 +36,10 @@ fn query(
password: String, password: String,
pool: web::Data<Pool>, pool: web::Data<Pool>,
) -> Result<SlimUser, crate::errors::ServiceError> { ) -> Result<SlimUser, crate::errors::ServiceError> {
use crate::schema::invitations::dsl::{id, invitations}; use crate::schema::{
use crate::schema::users::dsl::users; invitations::dsl::{id, invitations},
users::dsl::users,
};
let invitation_id = uuid::Uuid::parse_str(&invitation_id)?; let invitation_id = uuid::Uuid::parse_str(&invitation_id)?;
let conn: &PgConnection = &pool.get().unwrap(); let conn: &PgConnection = &pool.get().unwrap();

View File

@ -24,9 +24,7 @@ async fn main() -> std::io::Result<()> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_web::body::to_bytes; use actix_web::{body::to_bytes, dev::Service, http, test, web, App, Error};
use actix_web::dev::Service;
use actix_web::{http, test, web, App, Error};
use super::*; use super::*;

View File

@ -18,10 +18,14 @@
//! //!
//! Check [user guide](https://actix.rs/docs/application/#state) for more info. //! Check [user guide](https://actix.rs/docs/application/#state) for more info.
use std::cell::Cell; use std::{
use std::io; cell::Cell,
use std::sync::atomic::{AtomicUsize, Ordering}; io,
use std::sync::Mutex; sync::{
atomic::{AtomicUsize, Ordering},
Mutex,
},
};
use actix_web::{ use actix_web::{
middleware, middleware,

View File

@ -1,5 +1,4 @@
use actix_web::web::Data; use actix_web::{get, web::Data, App, HttpServer};
use actix_web::{get, App, HttpServer};
use redis_tang::{Builder, Pool, RedisManager}; use redis_tang::{Builder, Pool, RedisManager};
#[actix_web::main] #[actix_web::main]

View File

@ -70,11 +70,16 @@ async fn handle_post_3(req: HttpRequest, params: web::Form<MyParams>) -> impl Re
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_web::body::to_bytes; use actix_web::{
use actix_web::dev::{Service, ServiceResponse}; body::to_bytes,
use actix_web::http::{header::HeaderValue, header::CONTENT_TYPE, StatusCode}; dev::{Service, ServiceResponse},
use actix_web::test::{self, TestRequest}; http::{
use actix_web::web::{Bytes, Form}; header::{HeaderValue, CONTENT_TYPE},
StatusCode,
},
test::{self, TestRequest},
web::{Bytes, Form},
};
use super::*; use super::*;

View File

@ -1,13 +1,11 @@
use std::fs; use std::fs;
use actix_multipart::Multipart; use actix_multipart::Multipart;
use actix_web::body::SizedStream;
use actix_web::{delete, error};
use actix_web::{ use actix_web::{
get, middleware::Logger, post, web, App, Error, HttpResponse, HttpServer, Responder, body::SizedStream, delete, error, get, middleware::Logger, post, web, App, Error, HttpResponse,
HttpServer, Responder,
}; };
use actix_web_lab::extract::Path; use actix_web_lab::{extract::Path, respond::Html};
use actix_web_lab::respond::Html;
use aws_config::meta::region::RegionProviderChain; use aws_config::meta::region::RegionProviderChain;
use dotenv::dotenv; use dotenv::dotenv;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -18,10 +16,7 @@ mod temp_file;
mod upload_file; mod upload_file;
mod utils; mod utils;
use self::client::Client; use self::{client::Client, temp_file::TempFile, upload_file::UploadedFile, utils::split_payload};
use self::temp_file::TempFile;
use self::upload_file::UploadedFile;
use self::utils::split_payload;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]

View File

@ -1,5 +1,7 @@
use r2d2_mysql::mysql::{Opts, OptsBuilder}; use r2d2_mysql::{
use r2d2_mysql::MysqlConnectionManager; mysql::{Opts, OptsBuilder},
MysqlConnectionManager,
};
pub type Pool = r2d2::Pool<MysqlConnectionManager>; pub type Pool = r2d2::Pool<MysqlConnectionManager>;

View File

@ -1,5 +1,4 @@
use juniper::FieldResult; use juniper::{EmptySubscription, FieldResult, RootNode};
use juniper::{EmptySubscription, RootNode};
#[derive(GraphQLEnum)] #[derive(GraphQLEnum)]
enum Episode { enum Episode {

View File

@ -1,7 +1,7 @@
//! JSON-RPC 2.0 Specification //! JSON-RPC 2.0 Specification
//! See: https://www.jsonrpc.org/specification //! See: https://www.jsonrpc.org/specification
use std::error;
use std::fmt; use std::{error, fmt};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;

View File

@ -3,10 +3,9 @@ use std::{
task::{Context, Poll}, task::{Context, Poll},
}; };
use actix_web::Error;
use actix_web::{ use actix_web::{
dev::{Service, ServiceRequest, ServiceResponse, Transform}, dev::{Service, ServiceRequest, ServiceResponse, Transform},
HttpMessage, Error, HttpMessage,
}; };
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View File

@ -1,9 +1,10 @@
use std::future::{ready, Ready}; use std::future::{ready, Ready};
use actix_web::body::EitherBody; use actix_web::{
use actix_web::dev::{self, ServiceRequest, ServiceResponse}; body::EitherBody,
use actix_web::dev::{Service, Transform}; dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
use actix_web::{http, Error, HttpResponse}; http, Error, HttpResponse,
};
use futures_util::future::LocalBoxFuture; use futures_util::future::LocalBoxFuture;
pub struct CheckLogin; pub struct CheckLogin;

View File

@ -1,2 +1,3 @@
reorder_imports = true
group_imports = "StdExternalCrate" group_imports = "StdExternalCrate"
imports_granularity = "Crate"
use_field_init_shorthand = true

View File

@ -1,11 +1,14 @@
use std::collections::HashMap; use std::collections::HashMap;
use actix_web::body::BoxBody; use actix_web::{
use actix_web::dev::ServiceResponse; body::BoxBody,
use actix_web::http::header::ContentType; dev::ServiceResponse,
use actix_web::http::StatusCode; error,
use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers}; http::{header::ContentType, StatusCode},
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer, Result}; middleware,
middleware::{ErrorHandlerResponse, ErrorHandlers},
web, App, Error, HttpResponse, HttpServer, Result,
};
use serde_json::json; use serde_json::json;
use tinytemplate::TinyTemplate; use tinytemplate::TinyTemplate;