2021-01-06 15:04:49 +13:00
|
|
|
// CRATES
|
2021-01-09 14:50:03 +13:00
|
|
|
use crate::utils::{prefs, Preferences};
|
2021-01-09 14:35:04 +13:00
|
|
|
use actix_web::{cookie::Cookie, web::Form, HttpMessage, HttpRequest, HttpResponse};
|
2021-01-06 15:04:49 +13:00
|
|
|
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 {
|
2021-01-09 14:50:03 +13:00
|
|
|
prefs: Preferences,
|
2021-01-06 15:04:49 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(serde::Deserialize)]
|
2021-01-08 05:38:05 +13:00
|
|
|
pub struct SettingsForm {
|
2021-01-09 17:55:40 +13:00
|
|
|
front_page: Option<String>,
|
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-09 14:35:04 +13:00
|
|
|
hide_nsfw: 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-09 14:50:03 +13:00
|
|
|
let s = SettingsTemplate { prefs: prefs(req) }.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-09 14:35:04 +13:00
|
|
|
let mut res = HttpResponse::Found();
|
2021-01-06 15:04:49 +13:00
|
|
|
|
2021-01-09 17:55:40 +13:00
|
|
|
let names = vec!["front_page", "layout", "comment_sort", "hide_nsfw"];
|
|
|
|
let values = vec![&form.front_page, &form.layout, &form.comment_sort, &form.hide_nsfw];
|
2021-01-06 15:04:49 +13:00
|
|
|
|
2021-01-09 14:35:04 +13:00
|
|
|
for (i, name) in names.iter().enumerate() {
|
|
|
|
match values[i] {
|
|
|
|
Some(value) => res.cookie(
|
|
|
|
Cookie::build(name.to_owned(), value)
|
|
|
|
.path("/")
|
|
|
|
.http_only(true)
|
|
|
|
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
|
|
|
|
.finish(),
|
|
|
|
),
|
|
|
|
None => match HttpMessage::cookie(&req, name.to_owned()) {
|
|
|
|
Some(cookie) => res.del_cookie(&cookie),
|
|
|
|
None => &mut res,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
2021-01-08 05:38:05 +13:00
|
|
|
|
2021-01-09 14:35:04 +13:00
|
|
|
res
|
2021-01-06 15:04:49 +13:00
|
|
|
.content_type("text/html")
|
|
|
|
.set_header("Location", "/settings")
|
|
|
|
.body(r#"Redirecting to <a href="/settings">settings</a>..."#)
|
|
|
|
}
|