From f6e9039b59cfb4fac3f429e09c3889bbb3aa5b7a Mon Sep 17 00:00:00 2001 From: Jef Roosens Date: Sun, 26 Sep 2021 18:36:15 +0200 Subject: [PATCH] Wrote part of posts db boilerplate --- src/db/posts.rs | 50 ++++++++++++++++++++++++++++++++++++------------- src/guards.rs | 30 ++++++++++++++--------------- 2 files changed, 51 insertions(+), 29 deletions(-) diff --git a/src/db/posts.rs b/src/db/posts.rs index 163902e..e729fec 100644 --- a/src/db/posts.rs +++ b/src/db/posts.rs @@ -1,5 +1,6 @@ use chrono::NaiveDate; use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable}; +use serde::Deserialize; use uuid::Uuid; use crate::{ @@ -24,19 +25,27 @@ pub struct NewPost pub section_id: Uuid, pub title: Option, pub publish_date: NaiveDate, + pub content: String, } -/// Returns all posts in the database; should be used with care as this method could quickly return -/// a large amount of data. -/// -/// # Arguments -/// -/// * `conn` - a reference to a database connection -pub fn all(conn: &PgConnection) -> RbResult> +#[derive(Deserialize, AsChangeset)] +#[table_name = "posts"] +pub struct PatchPost { - posts + pub id: Option, + pub section_id: Option, + pub title: Option, + pub publish_date: Option, + pub content: Option, +} + +pub fn get(conn: &PgConnection, offset_: u32, limit_: u32) -> RbResult> +{ + Ok(posts + .offset(offset_.into()) + .limit(limit_.into()) .load::(conn) - .map_err(|_| RbError::DbError("Couldn't get all posts.")) + .map_err(|_| RbError::DbError("Couldn't query posts."))?) } /// Insert a new post into the database. @@ -45,14 +54,29 @@ pub fn all(conn: &PgConnection) -> RbResult> /// /// * `conn` - reference to a database connection /// * `new_post` - the new post object to insert -pub fn create(conn: &PgConnection, new_post: &NewPost) -> RbResult<()> +pub fn create(conn: &PgConnection, new_post: &NewPost) -> RbResult { - insert_into(posts) + Ok(insert_into(posts) .values(new_post) - .execute(conn) - .map_err(|_| RbError::DbError("Couldn't insert post."))?; + .get_result::(conn) + .map_err(|_| RbError::DbError("Couldn't insert post."))?) // TODO check for conflict? +} + +pub fn update(conn: &PgConnection, post: &PatchPost) -> RbResult +{ + Ok(diesel::update(posts) + .set(post) + .get_result::(conn) + .map_err(|_| RbError::DbError("Couldn't update post."))?) +} + +pub fn delete(conn: &PgConnection, post_id: Uuid) -> RbResult<()> +{ + diesel::delete(posts.filter(id.eq(post_id))) + .execute(conn) + .map_err(|_| RbError::DbError("Couldn't delete post."))?; Ok(()) } diff --git a/src/guards.rs b/src/guards.rs index 3510163..1ecd436 100644 --- a/src/guards.rs +++ b/src/guards.rs @@ -26,14 +26,13 @@ impl<'r> FromRequest<'r> for Bearer<'r> Some(val) => val, }; - if !header.starts_with("Bearer ") { - return Outcome::Forward(()); - } - - // Extract the jwt token from the header - match header.get(7..) { - Some(s) => Outcome::Success(Self(s)), - None => Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)), + if header.starts_with("Bearer ") { + match header.get(7..) { + Some(s) => Outcome::Success(Self(s)), + None => Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)), + } + } else { + Outcome::Forward(()) } } } @@ -63,15 +62,14 @@ impl<'r> FromRequest<'r> for Jwt )) }, }; + // Verify token using key - let claims: Claims = match bearer.verify_with_key(&key) { - Ok(claims) => claims, + match bearer.verify_with_key(&key) { + Ok(claims) => Outcome::Success(Self(claims)), Err(_) => { return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)) }, - }; - - Outcome::Success(Self(claims)) + } } } @@ -89,10 +87,10 @@ impl<'r> FromRequest<'r> for User // Verify key hasn't yet expired if chrono::Utc::now().timestamp() > claims.exp { - return Outcome::Failure((Status::Forbidden, Self::Error::AuthTokenExpired)); + Outcome::Failure((Status::Forbidden, Self::Error::AuthTokenExpired)) + } else { + Outcome::Success(Self(claims)) } - - Outcome::Success(Self(claims)) } }