This commit is contained in:
parent
dde84caa53
commit
901af1c43c
2 changed files with 11 additions and 2 deletions
|
@ -1,3 +1,5 @@
|
||||||
|
use maud::{PreEscaped, html};
|
||||||
|
|
||||||
use super::User;
|
use super::User;
|
||||||
use crate::get_pg;
|
use crate::get_pg;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
@ -5,9 +7,17 @@ use std::str::FromStr;
|
||||||
pub trait CSRF {
|
pub trait CSRF {
|
||||||
fn get_csrf(&self) -> impl std::future::Future<Output = uuid::Uuid>;
|
fn get_csrf(&self) -> impl std::future::Future<Output = uuid::Uuid>;
|
||||||
fn verify_csrf(&self, csrf: &str) -> impl std::future::Future<Output = bool>;
|
fn verify_csrf(&self, csrf: &str) -> impl std::future::Future<Output = bool>;
|
||||||
|
fn update_csrf(&self) -> impl std::future::Future<Output = PreEscaped<String>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CSRF for User {
|
impl CSRF for User {
|
||||||
|
/// Javascript to update the `value` of an element with id `csrf`.
|
||||||
|
///
|
||||||
|
/// This is useful for htmx requests to update the CSRF token in place.
|
||||||
|
async fn update_csrf(&self) -> PreEscaped<String> {
|
||||||
|
html! { script { (format!("document.getElementById('csrf').value = '{}';", self.get_csrf().await)) }; }
|
||||||
|
}
|
||||||
|
|
||||||
/// Get CSRF Token for the current session
|
/// Get CSRF Token for the current session
|
||||||
async fn get_csrf(&self) -> uuid::Uuid {
|
async fn get_csrf(&self) -> uuid::Uuid {
|
||||||
let res: (uuid::Uuid,) = sqlx::query_as("SELECT csrf FROM user_session WHERE token = $1")
|
let res: (uuid::Uuid,) = sqlx::query_as("SELECT csrf FROM user_session WHERE token = $1")
|
||||||
|
@ -21,7 +31,7 @@ impl CSRF for User {
|
||||||
|
|
||||||
/// Verify CSRF and generate a new one
|
/// Verify CSRF and generate a new one
|
||||||
async fn verify_csrf(&self, csrf: &str) -> bool {
|
async fn verify_csrf(&self, csrf: &str) -> bool {
|
||||||
if self.get_csrf().await == uuid::Uuid::from_str(csrf).unwrap() {
|
if self.get_csrf().await == uuid::Uuid::from_str(csrf).unwrap_or_default() {
|
||||||
sqlx::query("UPDATE user_session SET csrf = gen_random_uuid() WHERE token = $1")
|
sqlx::query("UPDATE user_session SET csrf = gen_random_uuid() WHERE token = $1")
|
||||||
.bind(&self.session)
|
.bind(&self.session)
|
||||||
.execute(get_pg!())
|
.execute(get_pg!())
|
||||||
|
|
|
@ -42,7 +42,6 @@ pub fn format_date(date: &chrono::NaiveDate) -> String {
|
||||||
pub fn format_number(num: i32) -> String {
|
pub fn format_number(num: i32) -> String {
|
||||||
let mut str = num.to_string();
|
let mut str = num.to_string();
|
||||||
let mut result = String::new();
|
let mut result = String::new();
|
||||||
let mut count = 0;
|
|
||||||
|
|
||||||
str = str.chars().rev().collect();
|
str = str.chars().rev().collect();
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue