Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ratings CRUD #516

Merged
merged 15 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/migrations/20240406031915_create_applications.sql
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ CREATE INDEX IDX_multi_option_answer_options_question_options on multi_option_an
CREATE INDEX IDX_multi_option_answer_options_answers on multi_option_answer_options (answer_id);

CREATE TABLE application_ratings (
id SERIAL PRIMARY KEY,
id BIGINT PRIMARY KEY,
application_id BIGINT NOT NULL,
rater_id BIGINT NOT NULL,
rating INTEGER NOT NULL,
Expand Down
1 change: 1 addition & 0 deletions backend/server/src/handler/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod auth;
pub mod organisation;
pub mod ratings;
82 changes: 82 additions & 0 deletions backend/server/src/handler/ratings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use crate::models::app::AppState;
use crate::models::auth::{
ApplicationReviewerAdminGivenApplicationId, ApplicationReviewerAdminGivenRatingId,
RatingCreatorAdmin, SuperUser,
};
use crate::models::error::ChaosError;
use crate::models::ratings::{NewRating, Rating};
use crate::models::transaction::DBTransaction;
use axum::extract::{Json, Path, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;

pub struct RatingsHandler;

impl RatingsHandler {
// TODO: are all the user permissions as required? Who should be able to do what with ratings?
pub async fn create_rating(
State(state): State<AppState>,
Path(application_id): Path<i64>,
// TODO: Potential bug: the check whether user is allowed to access rating doesn't make sense here, because no rating exists yet
_admin: ApplicationReviewerAdminGivenApplicationId,
mut transaction: DBTransaction<'_>,
Json(new_rating): Json<NewRating>,
) -> Result<impl IntoResponse, ChaosError> {
Rating::create(
new_rating,
application_id,
state.snowflake_generator,
&mut transaction.tx,
)
.await?;
transaction.tx.commit().await?;
Ok((StatusCode::OK, "Successfully created rating"))
}

pub async fn update(
State(_state): State<AppState>,
Path(rating_id): Path<i64>,
_admin: RatingCreatorAdmin,
mut transaction: DBTransaction<'_>,
Json(updated_rating): Json<NewRating>,
) -> Result<impl IntoResponse, ChaosError> {
Rating::update(rating_id, updated_rating, &mut transaction.tx).await?;
transaction.tx.commit().await?;
Ok((StatusCode::OK, "Successfully updated rating"))
}

pub async fn get_ratings_for_application(
State(_state): State<AppState>,
Path(application_id): Path<i64>,
_admin: ApplicationReviewerAdminGivenApplicationId,
mut transaction: DBTransaction<'_>,
) -> Result<impl IntoResponse, ChaosError> {
let ratings =
Rating::get_all_ratings_from_application_id(application_id, &mut transaction.tx)
.await?;
transaction.tx.commit().await?;
Ok((StatusCode::OK, Json(ratings)))
}

pub async fn get(
State(_state): State<AppState>,
Path(rating_id): Path<i64>,
_admin: ApplicationReviewerAdminGivenRatingId,
mut transaction: DBTransaction<'_>,
) -> Result<impl IntoResponse, ChaosError> {
let org = Rating::get_rating(rating_id, &mut transaction.tx).await?;
transaction.tx.commit().await?;
Ok((StatusCode::OK, Json(org)))
}

pub async fn delete(
State(_state): State<AppState>,
Path(rating_id): Path<i64>,
_admin: ApplicationReviewerAdminGivenRatingId,
mut transaction: DBTransaction<'_>,
) -> Result<impl IntoResponse, ChaosError> {
Rating::delete(rating_id, &mut transaction.tx).await?;
transaction.tx.commit().await?;
Ok((StatusCode::OK, "Successfully deleted rating"))
}
}
17 changes: 16 additions & 1 deletion backend/server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ use crate::handler::auth::google_callback;
use crate::handler::organisation::OrganisationHandler;
use crate::models::storage::Storage;
use anyhow::Result;
use axum::routing::{get, patch, post, put};
use axum::routing::{delete, get, patch, post, put};
use axum::Router;
use handler::ratings::RatingsHandler;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
use models::app::AppState;
use snowflake::SnowflakeIdGenerator;
Expand Down Expand Up @@ -89,6 +90,20 @@ async fn main() -> Result<()> {
.put(OrganisationHandler::update_admins)
.delete(OrganisationHandler::remove_admin),
)
.route(
"/api/v1/ratings/:rating_id",
get(RatingsHandler::get)
.delete(RatingsHandler::delete)
.put(RatingsHandler::update),
)
fritzrehde marked this conversation as resolved.
Show resolved Hide resolved
.route(
"/api/v1/:application_id/rating",
post(RatingsHandler::create_rating),
)
.route(
"/api/v1/:application_id/ratings",
get(RatingsHandler::get_ratings_for_application),
)
.with_state(state);

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
Expand Down
143 changes: 141 additions & 2 deletions backend/server/src/models/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ use crate::models::app::AppState;
use crate::models::error::ChaosError;
use crate::service::auth::is_super_user;
use crate::service::jwt::decode_auth_token;
use crate::service::organisation::user_is_admin;
use crate::service::organisation::assert_user_is_admin;
use crate::service::ratings::{
assert_user_is_application_reviewer_admin_given_application_id,
assert_user_is_application_reviewer_admin_given_rating_id,
assert_user_is_rating_creator_and_organisation_member,
};
use axum::extract::{FromRef, FromRequestParts, Path};
use axum::http::request::Parts;
use axum::response::{IntoResponse, Redirect, Response};
Expand Down Expand Up @@ -139,8 +144,142 @@ where
.await
.map_err(|_| ChaosError::BadRequest)?;

user_is_admin(user_id, organisation_id, pool).await?;
assert_user_is_admin(user_id, organisation_id, pool).await?;

Ok(OrganisationAdmin { user_id })
}
}

// TODO: Not very idiomatic way. The reason this impl was chosen was because we
// couldn't figure out how to dynamically check whether the id passed in path
// was a rating id or an application id.

/// Get the application reviewer given a path that contains the application id.
pub struct ApplicationReviewerAdminGivenApplicationId {
pub user_id: i64,
}

#[async_trait]
impl<S> FromRequestParts<S> for ApplicationReviewerAdminGivenApplicationId
where
AppState: FromRef<S>,
S: Send + Sync,
{
type Rejection = ChaosError;

async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// TODO: put into separate function, since this is just getting the id through jwt, and duplicated here.
let app_state = AppState::from_ref(state);
let decoding_key = &app_state.decoding_key;
let jwt_validator = &app_state.jwt_validator;
let TypedHeader(cookies) = parts
.extract::<TypedHeader<Cookie>>()
.await
.map_err(|_| ChaosError::NotLoggedIn)?;

let token = cookies.get("auth_token").ok_or(ChaosError::NotLoggedIn)?;

let claims =
decode_auth_token(token, decoding_key, jwt_validator).ok_or(ChaosError::NotLoggedIn)?;

let pool = &app_state.db;
let user_id = claims.sub;

let Path(application_id) = parts
.extract::<Path<i64>>()
.await
.map_err(|_| ChaosError::BadRequest)?;

assert_user_is_application_reviewer_admin_given_application_id(
user_id,
application_id,
pool,
)
.await?;

Ok(ApplicationReviewerAdminGivenApplicationId { user_id })
}
}

/// Get the application reviewer given a path that contains the rating id.
pub struct ApplicationReviewerAdminGivenRatingId {
pub user_id: i64,
}

#[async_trait]
impl<S> FromRequestParts<S> for ApplicationReviewerAdminGivenRatingId
KavikaPalletenne marked this conversation as resolved.
Show resolved Hide resolved
where
AppState: FromRef<S>,
S: Send + Sync,
{
type Rejection = ChaosError;

async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// TODO: put into separate function, since this is just getting the id through jwt, and duplicated here.
let app_state = AppState::from_ref(state);
let decoding_key = &app_state.decoding_key;
let jwt_validator = &app_state.jwt_validator;
let TypedHeader(cookies) = parts
.extract::<TypedHeader<Cookie>>()
.await
.map_err(|_| ChaosError::NotLoggedIn)?;

let token = cookies.get("auth_token").ok_or(ChaosError::NotLoggedIn)?;

let claims =
decode_auth_token(token, decoding_key, jwt_validator).ok_or(ChaosError::NotLoggedIn)?;

let pool = &app_state.db;
let user_id = claims.sub;

let Path(rating_id) = parts
.extract::<Path<i64>>()
.await
.map_err(|_| ChaosError::BadRequest)?;

assert_user_is_application_reviewer_admin_given_rating_id(user_id, rating_id, pool).await?;

Ok(ApplicationReviewerAdminGivenRatingId { user_id })
}
}

pub struct RatingCreatorAdmin {
pub user_id: i64,
}

#[async_trait]
impl<S> FromRequestParts<S> for RatingCreatorAdmin
where
AppState: FromRef<S>,
S: Send + Sync,
{
type Rejection = ChaosError;

async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// TODO: put into separate function, since this is just getting the id through jwt, and duplicated here.
let app_state = AppState::from_ref(state);
let decoding_key = &app_state.decoding_key;
let jwt_validator = &app_state.jwt_validator;
let TypedHeader(cookies) = parts
.extract::<TypedHeader<Cookie>>()
.await
.map_err(|_| ChaosError::NotLoggedIn)?;

let token = cookies.get("auth_token").ok_or(ChaosError::NotLoggedIn)?;

let claims =
decode_auth_token(token, decoding_key, jwt_validator).ok_or(ChaosError::NotLoggedIn)?;

let pool = &app_state.db;
let user_id = claims.sub;

let Path(rating_id) = parts
.extract::<Path<i64>>()
.await
.map_err(|_| ChaosError::BadRequest)?;

assert_user_is_rating_creator_and_organisation_member(user_id, rating_id, pool).await?;

Ok(RatingCreatorAdmin { user_id })
}
}
1 change: 1 addition & 0 deletions backend/server/src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod auth;
pub mod campaign;
pub mod error;
pub mod organisation;
pub mod ratings;
pub mod storage;
pub mod transaction;
pub mod user;
Loading
Loading