This repository has been archived by the owner on Aug 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Reject unauthenticated admin dashboard users
- Loading branch information
Showing
15 changed files
with
277 additions
and
38 deletions.
There are no files selected for viewing
22 changes: 22 additions & 0 deletions
22
.sqlx/query-33b11051e779866db9aeb86d28a59db07a94323ffdc59a5a2c1da694ebe9a65f.json
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
use crate::{app_state::AppState, session_state::TypedSession}; | ||
use anyhow::Context; | ||
use askama::Template; | ||
use askama_axum::IntoResponse; | ||
use axum::{ | ||
extract::State, | ||
http::StatusCode, | ||
response::{Redirect, Response}, | ||
}; | ||
use sqlx::PgPool; | ||
use uuid::Uuid; | ||
|
||
#[tracing::instrument(name = "Get admin dashboard", skip(app_state, session))] | ||
pub(super) async fn admin_dashboard( | ||
State(app_state): State<AppState>, | ||
session: TypedSession, | ||
) -> Result<Response, DashboardError> { | ||
let response = match session | ||
.get_user_id() | ||
.await | ||
.map_err(|e| DashboardError::InvalidSession(e.into()))? | ||
{ | ||
Some(user_id) => Dashboard { | ||
title: "Admin Dashboard", | ||
username: get_username(&app_state.db_pool, user_id).await?, | ||
} | ||
.into_response(), | ||
None => Redirect::to("/login").into_response(), | ||
}; | ||
|
||
Ok(response) | ||
} | ||
|
||
#[tracing::instrument(skip(db_pool))] | ||
async fn get_username(db_pool: &PgPool, user_id: Uuid) -> Result<String, anyhow::Error> { | ||
let row = sqlx::query!( | ||
r#" | ||
SELECT username | ||
FROM users | ||
WHERE user_id = $1 | ||
"#, | ||
user_id, | ||
) | ||
.fetch_one(db_pool) | ||
.await | ||
.context("Failed to perform a query to retrieve a username")?; | ||
|
||
Ok(row.username) | ||
} | ||
|
||
#[derive(Template)] | ||
#[template(path = "web/dashboard.html")] | ||
struct Dashboard<'a> { | ||
title: &'a str, | ||
username: String, | ||
} | ||
|
||
#[derive(Debug, thiserror::Error)] | ||
pub enum DashboardError { | ||
#[error("Invalid session")] | ||
InvalidSession(#[source] anyhow::Error), | ||
#[error("Something went wrong")] | ||
UnexpectedError(#[from] anyhow::Error), | ||
} | ||
|
||
impl IntoResponse for DashboardError { | ||
fn into_response(self) -> Response { | ||
tracing::error!("{:#?}", self); | ||
|
||
match self { | ||
Self::InvalidSession(_) => StatusCode::UNAUTHORIZED.into_response(), | ||
Self::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
use crate::app_state::AppState; | ||
use axum::{routing::get, Router}; | ||
use dashboard::admin_dashboard; | ||
|
||
mod dashboard; | ||
|
||
pub fn router() -> Router<AppState> { | ||
Router::new().route("/admin/dashboard", get(admin_dashboard)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
pub mod admin; | ||
pub mod health_check; | ||
pub mod home; | ||
pub mod login; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
use axum::{ | ||
async_trait, | ||
extract::FromRequestParts, | ||
http::{request::Parts, StatusCode}, | ||
}; | ||
use tower_sessions::{session::Error, Session}; | ||
use uuid::Uuid; | ||
|
||
pub struct TypedSession(Session); | ||
|
||
impl TypedSession { | ||
const USER_ID_KEY: &'static str = "user_id"; | ||
|
||
pub async fn cycle_id(&self) -> Result<(), Error> { | ||
self.0.cycle_id().await | ||
} | ||
|
||
pub async fn insert_user_id(&self, user_id: Uuid) -> Result<(), Error> { | ||
self.0.insert(Self::USER_ID_KEY, user_id).await | ||
} | ||
|
||
pub async fn get_user_id(&self) -> Result<Option<Uuid>, Error> { | ||
self.0.get(Self::USER_ID_KEY).await | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl<S> FromRequestParts<S> for TypedSession | ||
where | ||
S: Send + Sync, | ||
{ | ||
type Rejection = (StatusCode, &'static str); | ||
|
||
async fn from_request_parts(req: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | ||
let session = Session::from_request_parts(req, state).await?; | ||
Ok(TypedSession(session)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{% extends "base.html" %} | ||
|
||
{% block content %} | ||
<p>Welcome {{ username }}!</p> | ||
{% endblock %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
use crate::helpers::TestApp; | ||
|
||
#[tokio::test] | ||
async fn login_is_required_to_access_admin_dashboard() { | ||
// given | ||
let app = TestApp::spawn().await; | ||
|
||
// when | ||
let response = app.get_admin_dashboard().await; | ||
|
||
// then | ||
assert_eq!(response.status(), 303); | ||
assert_eq!(response.headers().get("Location").unwrap(), "/login"); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.