redsunlib/src/settings.rs

65 lines
1.7 KiB
Rust
Raw Normal View History

2021-01-06 15:04:49 +13:00
// CRATES
use crate::utils::cookie;
use actix_web::{cookie::Cookie, web::Form, HttpRequest, HttpResponse}; // http::Method,
use askama::Template;
use time::{Duration, OffsetDateTime};
// STRUCTS
#[derive(Template)]
2021-01-08 05:38:05 +13:00
#[template(path = "settings.html")]
2021-01-06 15:04:49 +13:00
struct SettingsTemplate {
layout: String,
2021-01-08 05:38:05 +13:00
comment_sort: String,
2021-01-06 15:04:49 +13:00
}
#[derive(serde::Deserialize)]
2021-01-08 05:38:05 +13:00
pub struct SettingsForm {
2021-01-06 15:04:49 +13:00
layout: Option<String>,
2021-01-08 05:38:05 +13:00
comment_sort: Option<String>,
2021-01-06 15:04:49 +13:00
}
// FUNCTIONS
// Retrieve cookies from request "Cookie" header
pub async fn get(req: HttpRequest) -> HttpResponse {
2021-01-08 05:38:05 +13:00
let s = SettingsTemplate {
layout: cookie(req.to_owned(), "layout"),
comment_sort: cookie(req, "comment_sort"),
}
.render()
.unwrap();
2021-01-06 15:04:49 +13:00
HttpResponse::Ok().content_type("text/html").body(s)
}
// Set cookies using response "Set-Cookie" header
2021-01-08 05:38:05 +13:00
pub async fn set(req: HttpRequest, form: Form<SettingsForm>) -> HttpResponse {
2021-01-06 15:04:49 +13:00
let mut response = HttpResponse::Found();
match &form.layout {
Some(value) => response.cookie(
Cookie::build("layout", value)
.path("/")
.http_only(true)
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
.finish(),
),
None => response.del_cookie(&actix_web::HttpMessage::cookie(&req, "layout").unwrap()),
};
2021-01-08 05:38:05 +13:00
match &form.comment_sort {
Some(value) => response.cookie(
Cookie::build("comment_sort", value)
.path("/")
.http_only(true)
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
.finish(),
),
None => response.del_cookie(&actix_web::HttpMessage::cookie(&req, "comment_sort").unwrap()),
};
2021-01-06 15:04:49 +13:00
response
.content_type("text/html")
.set_header("Location", "/settings")
.body(r#"Redirecting to <a href="/settings">settings</a>..."#)
}