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
16 changed files
with
305 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,54 @@ | ||
use crate::{ | ||
app_state::AppState, | ||
session_state::TypedSession, | ||
utils::{e500, redirect_to, HttpError}, | ||
}; | ||
use anyhow::{Context, Error}; | ||
use askama::Template; | ||
use askama_axum::IntoResponse; | ||
use axum::{extract::State, response::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, HttpError<Error>> { | ||
let response = match session.get_user_id().await.map_err(e500)? { | ||
Some(user_id) => Dashboard { | ||
title: "Admin Dashboard", | ||
username: get_username(&app_state.db_pool, user_id) | ||
.await | ||
.map_err(e500)?, | ||
} | ||
.into_response(), | ||
None => redirect_to("/login"), | ||
}; | ||
|
||
Ok(response) | ||
} | ||
|
||
#[tracing::instrument(skip(db_pool))] | ||
async fn get_username(db_pool: &PgPool, user_id: Uuid) -> Result<String, 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, | ||
} |
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,48 @@ | ||
use anyhow::{Context, Error}; | ||
use axum::{ | ||
async_trait, | ||
extract::FromRequestParts, | ||
http::{request::Parts, StatusCode}, | ||
}; | ||
use tower_sessions::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 | ||
.context("Failed to cycle session id") | ||
} | ||
|
||
pub async fn insert_user_id(&self, user_id: Uuid) -> Result<(), Error> { | ||
self.0 | ||
.insert(Self::USER_ID_KEY, user_id) | ||
.await | ||
.context("Failed to insert user id into session") | ||
} | ||
|
||
pub async fn get_user_id(&self) -> Result<Option<Uuid>, Error> { | ||
self.0 | ||
.get(Self::USER_ID_KEY) | ||
.await | ||
.context("Failed to retrieve user id from session") | ||
} | ||
} | ||
|
||
#[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,38 @@ | ||
use axum::{ | ||
http::StatusCode, | ||
response::{IntoResponse, Redirect, Response}, | ||
}; | ||
use std::fmt::Debug; | ||
|
||
pub fn redirect_to(uri: &str) -> Response { | ||
Redirect::to(uri).into_response() | ||
} | ||
|
||
pub fn e500<T>(error: T) -> HttpError<T> | ||
where | ||
T: Debug, | ||
{ | ||
HttpError::InternalServerError(error) | ||
} | ||
|
||
#[derive(Debug, thiserror::Error)] | ||
pub enum HttpError<T> | ||
where | ||
T: Debug, | ||
{ | ||
#[error("Something went wrong")] | ||
InternalServerError(#[from] T), | ||
} | ||
|
||
impl<T> IntoResponse for HttpError<T> | ||
where | ||
T: Debug, | ||
{ | ||
fn into_response(self) -> Response { | ||
tracing::error!("{:#?}", self); | ||
|
||
match self { | ||
Self::InternalServerError(_) => 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,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"); | ||
} |
Oops, something went wrong.