libreddit/src/settings.rs

65 lines
1.6 KiB
Rust
Raw Normal View History

2021-01-06 03:04:49 +01:00
// CRATES
use crate::utils::cookie;
2021-01-09 02:35:04 +01:00
use actix_web::{cookie::Cookie, web::Form, HttpMessage, HttpRequest, HttpResponse};
2021-01-06 03:04:49 +01:00
use askama::Template;
use time::{Duration, OffsetDateTime};
// STRUCTS
#[derive(Template)]
2021-01-07 17:38:05 +01:00
#[template(path = "settings.html")]
2021-01-06 03:04:49 +01:00
struct SettingsTemplate {
layout: String,
2021-01-07 17:38:05 +01:00
comment_sort: String,
2021-01-09 02:35:04 +01:00
hide_nsfw: String,
2021-01-06 03:04:49 +01:00
}
#[derive(serde::Deserialize)]
2021-01-07 17:38:05 +01:00
pub struct SettingsForm {
2021-01-06 03:04:49 +01:00
layout: Option<String>,
2021-01-07 17:38:05 +01:00
comment_sort: Option<String>,
2021-01-09 02:35:04 +01:00
hide_nsfw: Option<String>,
2021-01-06 03:04:49 +01:00
}
// FUNCTIONS
// Retrieve cookies from request "Cookie" header
pub async fn get(req: HttpRequest) -> HttpResponse {
2021-01-07 17:38:05 +01:00
let s = SettingsTemplate {
layout: cookie(req.to_owned(), "layout"),
2021-01-09 02:35:04 +01:00
comment_sort: cookie(req.to_owned(), "comment_sort"),
hide_nsfw: cookie(req, "hide_nsfw"),
2021-01-07 17:38:05 +01:00
}
.render()
.unwrap();
2021-01-06 03:04:49 +01:00
HttpResponse::Ok().content_type("text/html").body(s)
}
// Set cookies using response "Set-Cookie" header
2021-01-07 17:38:05 +01:00
pub async fn set(req: HttpRequest, form: Form<SettingsForm>) -> HttpResponse {
2021-01-09 02:35:04 +01:00
let mut res = HttpResponse::Found();
2021-01-06 03:04:49 +01:00
2021-01-09 02:35:04 +01:00
let names = vec!["layout", "comment_sort", "hide_nsfw"];
let values = vec![&form.layout, &form.comment_sort, &form.hide_nsfw];
2021-01-06 03:04:49 +01:00
2021-01-09 02:35:04 +01: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-07 17:38:05 +01:00
2021-01-09 02:35:04 +01:00
res
2021-01-06 03:04:49 +01:00
.content_type("text/html")
.set_header("Location", "/settings")
.body(r#"Redirecting to <a href="/settings">settings</a>..."#)
}