Skip to content

Commit

Permalink
Merge pull request #4 from simonsan/update-patch
Browse files Browse the repository at this point in the history
Added more Clippy lints and fixed (most of) them
  • Loading branch information
jbertovic authored Jul 31, 2022
2 parents b11dc1d + f5563e6 commit 655c03e
Show file tree
Hide file tree
Showing 10 changed files with 39 additions and 22 deletions.
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
name = "svelte-axum-project"
version = "0.1.0"
edition = "2021"

repository = "https://github.com/jbertovic/svelte-axum-project"
keywords = ["template", "backend", "frontend", "axum", "svelte"]
license = ""
categories = []
description = ""
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
Expand Down
14 changes: 10 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
#![deny(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![allow(missing_docs)]

use axum::{
http::StatusCode,
middleware,
Expand Down Expand Up @@ -64,7 +69,7 @@ async fn main() {
// NON-AUTH AREA routes: login, logout and session
// `/test` shows example of a non implemented route
let non_auth_backend = Router::new()
.route("/auth/session", get(routes::session_data_handler)) // gets session data
.route("/auth/session", get(routes::session::data_handler)) // gets session data
.route("/auth/login", post(routes::login)) // sets username in session
.route("/auth/logout", get(routes::logout)) // deletes username in session
.route("/test", get(routes::not_implemented_route));
Expand All @@ -73,10 +78,10 @@ async fn main() {
// `/secure` shows an example of checking session information for user_id to allow access
// `/api` can be accessed using an authorization header and with no session
let auth_backend_using_token = Router::new()
.route("/api", get(routes::api_handler))
.route("/api", get(routes::api::handler))
.route_layer(middleware::from_fn(middlewares::auth));
let auth_backend_using_session = Router::new()
.route("/secure", get(routes::session_out_handler))
.route("/secure", get(routes::session::handler))
.route_layer(middleware::from_fn(middlewares::user_secure));

// could add tower::ServiceBuilder here to group layers, especially if you add more layers.
Expand All @@ -99,6 +104,7 @@ async fn main() {
.unwrap();
}

#[allow(clippy::unused_async)]
async fn handle_error(_err: io::Error) -> impl IntoResponse {
(
StatusCode::INTERNAL_SERVER_ERROR,
Expand All @@ -107,7 +113,7 @@ async fn handle_error(_err: io::Error) -> impl IntoResponse {
}

/// Tokio signal handler that will wait for a user to press CTRL+C.
/// We use this in our hyper `Server` method `with_graceful_shutdown`.
/// We use this in our `Server` method `with_graceful_shutdown`.
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
Expand Down
13 changes: 7 additions & 6 deletions src/middlewares/authenticator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ use crate::store::Store;

/// middleware function to authenticate authorization token
/// check store that contains token and see if it matches authorization header starting with "Bearer"
/// used example in axum docs on middleware https://docs.rs/axum/latest/axum/middleware/index.html
/// used example in axum docs on middleware <https://docs.rs/axum/latest/axum/middleware/index.html>
///
/// Returns Error's in JSON format.
pub async fn auth<B>(
#[allow(clippy::missing_errors_doc)]
pub async fn auth<B: Send + Sync>(
req: Request<B>,
next: Next<B>,
) -> Result<Response, (StatusCode, Json<JsonError>)> {
Expand Down Expand Up @@ -58,18 +59,18 @@ pub struct JsonError {
}

impl JsonError {
pub fn new(error: String) -> Self {
JsonError { error }
pub const fn new(error: String) -> Self {
Self { error }
}

pub fn unauthorized() -> Self {
JsonError {
Self {
error: "Unauthorized".into(),
}
}

pub fn internal() -> Self {
JsonError {
Self {
error: "Internal Server Error".into(),
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/usersecure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use axum::{
};
use axum_sessions::async_session::Session;

pub async fn user_secure<B>(req: Request<B>, next: Next<B>) -> Result<Response, StatusCode> {
#[allow(clippy::missing_errors_doc)]
pub async fn user_secure<B: Send>(req: Request<B>, next: Next<B>) -> Result<Response, StatusCode> {
tracing::info!("Middleware: checking if user exists");
let session = req
.extensions()
Expand Down
7 changes: 2 additions & 5 deletions src/routes.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
mod api;
pub mod api;
mod auth;
mod notimplemented;
mod session;
pub mod session;

pub use api::api_handler;
pub use auth::login;
pub use auth::logout;
pub use notimplemented::not_implemented_route;
pub use session::session_data_handler;
pub use session::session_out_handler;
3 changes: 2 additions & 1 deletion src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use axum::{response::IntoResponse, Json};
use axum_sessions::async_session::serde_json::json;

/// imitating an API response
pub async fn api_handler() -> impl IntoResponse {
#[allow(clippy::unused_async)]
pub async fn handler() -> impl IntoResponse {
tracing::info!("Seeking api data");
Json(
json!({"result": "ok", "message": "You've reached the backend API by using a valid token."}),
Expand Down
5 changes: 4 additions & 1 deletion src/routes/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use axum_sessions::async_session::{serde_json::json, Session};
use serde::Deserialize;

/// route to handle log in
#[allow(clippy::unused_async)]
#[allow(clippy::missing_panics_doc)]
pub async fn login(
Json(login): Json<Login>,
Extension(mut session): Extension<Session>,
Expand All @@ -18,6 +20,7 @@ pub async fn login(
}

/// route to handle log out
#[allow(clippy::unused_async)]
pub async fn logout(Extension(mut session): Extension<Session>) -> impl IntoResponse {
let user = session.get_raw("user_id").unwrap_or_default();
tracing::info!("Logging out user: {}", user);
Expand All @@ -27,7 +30,7 @@ pub async fn logout(Extension(mut session): Extension<Session>) -> impl IntoResp
}

// assume all passwords work
fn check_password(_username: &str, _password: &str) -> bool {
const fn check_password(_username: &str, _password: &str) -> bool {
true
}

Expand Down
1 change: 1 addition & 0 deletions src/routes/notimplemented.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use axum::{body::Body, http::Request, response::IntoResponse};

#[allow(clippy::unused_async)]
pub async fn not_implemented_route(req: Request<Body>) -> impl IntoResponse {
// add which route is requesting this?
format!("Route is planned but not yet implemented for {}", req.uri())
Expand Down
6 changes: 4 additions & 2 deletions src/routes/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ use axum::{response::IntoResponse, Extension, Json};
use axum_sessions::async_session::{serde_json::json, Session};

/// output entire session object
pub async fn session_out_handler(Extension(session): Extension<Session>) -> impl IntoResponse {
#[allow(clippy::unused_async)]
pub async fn handler(Extension(session): Extension<Session>) -> impl IntoResponse {
tracing::info!("Seeking session info");
Json(json!({ "session": format!("{:?}", session) }))
}

/// output session data in json
pub async fn session_data_handler(Extension(session): Extension<Session>) -> impl IntoResponse {
#[allow(clippy::unused_async)]
pub async fn data_handler(Extension(session): Extension<Session>) -> impl IntoResponse {
tracing::info!("Seeking session data");
let user_id = session.get("user_id").unwrap_or_else(|| "".to_string());
Json(json!({ "user_id": user_id }))
Expand Down
2 changes: 1 addition & 1 deletion src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub struct Store {

impl Store {
pub fn new(api_token: &str) -> Self {
Store {
Self {
api_token: api_token.to_string(),
}
}
Expand Down

0 comments on commit 655c03e

Please sign in to comment.