Added create section endpoint

This commit is contained in:
Jef Roosens 2021-09-13 22:15:38 +02:00
parent 8534090f0f
commit 3e7612a9a8
Signed by: Jef Roosens
GPG key ID: B580B976584B5F30
11 changed files with 75 additions and 30 deletions

View file

@ -1,8 +1,8 @@
pub mod posts;
pub mod sections;
pub mod tokens;
pub mod users;
pub mod sections;
pub mod posts;
pub use sections::{NewSection, Section};
pub use tokens::{NewRefreshToken, RefreshToken};
pub use users::{NewUser, User};
pub use sections::{Section, NewSection};

View file

@ -1,6 +1,6 @@
use chrono::NaiveDate;
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
use uuid::Uuid;
use chrono::NaiveDate;
use crate::{
errors::{RbError, RbResult},
@ -28,7 +28,9 @@ pub struct NewPost
pub fn all(conn: &PgConnection) -> RbResult<Vec<Post>>
{
posts.load::<Post>(conn).map_err(|_| RbError::DbError("Couldn't get all posts."))
posts
.load::<Post>(conn)
.map_err(|_| RbError::DbError("Couldn't get all posts."))
}
pub fn create(conn: &PgConnection, new_post: &NewPost) -> RbResult<()>

View file

@ -1,4 +1,5 @@
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
use serde::Deserialize;
use uuid::Uuid;
use crate::{
@ -16,19 +17,22 @@ pub struct Section
pub has_titles: bool,
}
#[derive(Insertable)]
#[derive(Deserialize, Insertable)]
#[table_name = "sections"]
// #[serde(rename_all = "camelCase")]
pub struct NewSection
{
title: String,
description: Option<String>,
is_default: bool,
has_titles: bool,
is_default: Option<bool>,
has_titles: Option<bool>,
}
pub fn all(conn: &PgConnection) -> RbResult<Vec<Section>>
{
sections.load::<Section>(conn).map_err(|_| RbError::DbError("Couldn't get all sections"))
sections
.load::<Section>(conn)
.map_err(|_| RbError::DbError("Couldn't get all sections"))
}
pub fn create(conn: &PgConnection, new_section: &NewSection) -> RbResult<()>

View file

@ -61,7 +61,7 @@ impl RbError
RbError::AuthInvalidRefreshToken => "This refresh token is not valid.",
RbError::AuthDuplicateRefreshToken => {
"This refresh token has already been used. The user has been blocked."
}
},
RbError::AuthMissingHeader => "Missing Authorization header.",
RbError::UMDuplicateUser => "This user already exists.",

View file

@ -10,7 +10,7 @@ use sha2::Sha256;
use crate::{auth::jwt::Claims, errors::RbError, RbConfig};
/// Extracts a "Authorization: Bearer" string from the headers.
/// Extracts an "Authorization: Bearer" string from the headers.
pub struct Bearer<'a>(&'a str);
#[rocket::async_trait]
@ -22,7 +22,7 @@ impl<'r> FromRequest<'r> for Bearer<'r>
{
// If the header isn't present, just forward to the next route
let header = match req.headers().get_one("Authorization") {
None => return Outcome::Failure((Status::BadRequest, Self::Error::AuthMissingHeader)),
None => return Outcome::Forward(()),
Some(val) => val,
};
@ -31,12 +31,10 @@ impl<'r> FromRequest<'r> for Bearer<'r>
}
// Extract the jwt token from the header
let auth_string = match header.get(7..) {
Some(s) => s,
None => return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)),
};
Outcome::Success(Self(auth_string))
match header.get(7..) {
Some(s) => Outcome::Success(Self(s)),
None => Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)),
}
}
}
@ -63,14 +61,14 @@ impl<'r> FromRequest<'r> for Jwt
Status::InternalServerError,
Self::Error::Custom("Failed to do Hmac thing."),
))
}
},
};
// Verify token using key
let claims: Claims = match bearer.verify_with_key(&key) {
Ok(claims) => claims,
Err(_) => {
return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized))
}
},
};
Outcome::Success(Self(claims))

View file

@ -27,6 +27,7 @@ pub mod db;
pub mod errors;
pub mod guards;
pub(crate) mod schema;
pub mod sections;
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
@ -111,4 +112,5 @@ fn rocket() -> _
"/api/admin",
routes![admin::get_users, admin::create_user, admin::get_user_info],
)
.mount("/api/sections", routes![sections::create_section])
}

View file

@ -40,9 +40,4 @@ table! {
joinable!(posts -> sections (section_id));
joinable!(refresh_tokens -> users (user_id));
allow_tables_to_appear_in_same_query!(
posts,
refresh_tokens,
sections,
users,
);
allow_tables_to_appear_in_same_query!(posts, refresh_tokens, sections, users,);

16
src/sections.rs Normal file
View file

@ -0,0 +1,16 @@
use rocket::serde::json::Json;
use crate::{db, errors::RbResult, guards::Admin, RbDbConn};
/// Create a new section.
#[post("/", data = "<new_section>")]
pub async fn create_section(
_admin: Admin,
conn: RbDbConn,
new_section: Json<db::NewSection>,
) -> RbResult<()>
{
Ok(conn
.run(move |c| db::sections::create(c, &new_section.into_inner()))
.await?)
}