Skip to content

Commit

Permalink
Add verify_jwt_claims for JwtAuthService
Browse files Browse the repository at this point in the history
  • Loading branch information
photino committed Aug 31, 2023
1 parent 8cfac6f commit d75ecee
Show file tree
Hide file tree
Showing 21 changed files with 422 additions and 187 deletions.
10 changes: 5 additions & 5 deletions examples/actix-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ serde_json = "1.0.105"
tracing = "0.1.37"

[dependencies.serde]
version = "1.0.186"
version = "1.0.188"
features = ["derive"]

[dependencies.zino]
path = "../../zino"
version = "0.11.1"
version = "0.11.2"
features = ["actix", "export-pdf"]

[dependencies.zino-core]
path = "../../zino-core"
version = "0.12.1"
version = "0.12.2"
features = [
"connector",
"connector-arrow",
Expand All @@ -33,8 +33,8 @@ features = [

[dependencies.zino-derive]
path = "../../zino-derive"
version = "0.9.1"
version = "0.9.2"

[dependencies.zino-model]
path = "../../zino-model"
version = "0.9.1"
version = "0.9.2"
10 changes: 9 additions & 1 deletion examples/actix-app/src/controller/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,17 @@ use zino_model::user::{JwtAuthService, User};

pub async fn login(mut req: Request) -> Result {
let body: Map = req.parse_body().await?;
let current_time = DateTime::now();
let (user_id, mut data) = User::generate_token(body).await.extract(&req)?;

let mut mutations = Map::from_entry("status", "Active");
let mut mutations = Map::new();
mutations.upsert("status", "Active");
mutations.upsert("last_login_at", data.remove("current_login_at"));
mutations.upsert("last_login_ip", data.remove("current_login_ip"));
mutations.upsert("current_login_at", current_time.to_utc_timestamp());
mutations.upsert("current_login_ip", req.client_ip().map(|ip| ip.to_string()));
mutations.upsert("login_count", Map::from_entry("$inc", 1));

let (validation, user) = User::update_by_id(&user_id, &mut mutations, None)
.await
.extract(&req)?;
Expand Down
4 changes: 2 additions & 2 deletions examples/actix-app/src/middleware/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ where

fn call(&self, req: ServiceRequest) -> Self::Future {
let mut req = Request::from(req);
if let Ok(claims) = req.parse_jwt_claims(JwtClaims::shared_key())
&& let Ok(mut user_session) = UserSession::<Uuid>::try_from_jwt_claims(claims)
if let Ok(claims) = req.parse_jwt_claims(JwtClaims::shared_key()) &&
let Ok(mut user_session) = UserSession::<Uuid>::try_from_jwt_claims(claims)
{
if let Ok(session_id) = req.parse_session_id() {
user_session.set_session_id(session_id);
Expand Down
10 changes: 5 additions & 5 deletions examples/axum-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ serde_json = "1.0.105"
tracing = "0.1.37"

[dependencies.serde]
version = "1.0.186"
version = "1.0.188"
features = ["derive"]

[dependencies.zino]
path = "../../zino"
version = "0.11.1"
version = "0.11.2"
features = ["axum", "export-pdf"]

[dependencies.zino-core]
path = "../../zino-core"
version = "0.12.1"
version = "0.12.2"
features = [
"connector",
"connector-arrow",
Expand All @@ -33,8 +33,8 @@ features = [

[dependencies.zino-derive]
path = "../../zino-derive"
version = "0.9.1"
version = "0.9.2"

[dependencies.zino-model]
path = "../../zino-model"
version = "0.9.1"
version = "0.9.2"
10 changes: 9 additions & 1 deletion examples/axum-app/src/controller/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,17 @@ use zino_model::user::{JwtAuthService, User};

pub async fn login(mut req: Request) -> Result {
let body: Map = req.parse_body().await?;
let current_time = DateTime::now();
let (user_id, mut data) = User::generate_token(body).await.extract(&req)?;

let mut mutations = Map::from_entry("status", "Active");
let mut mutations = Map::new();
mutations.upsert("status", "Active");
mutations.upsert("last_login_at", data.remove("current_login_at"));
mutations.upsert("last_login_ip", data.remove("current_login_ip"));
mutations.upsert("current_login_at", current_time.to_utc_timestamp());
mutations.upsert("current_login_ip", req.client_ip().map(|ip| ip.to_string()));
mutations.upsert("login_count", Map::from_entry("$inc", 1));

let (validation, user) = User::update_by_id(&user_id, &mut mutations, None)
.await
.extract(&req)?;
Expand Down
24 changes: 18 additions & 6 deletions examples/axum-app/src/middleware/access.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
use axum::{body::Body, middleware::Next, response::Response};
use zino::{prelude::*, Request, Result};
use zino_model::user::{JwtAuthService, User};

pub async fn init_user_session(mut req: Request, next: Next<Body>) -> Result<Response> {
if let Ok(claims) = req.parse_jwt_claims(JwtClaims::shared_key())
&& let Ok(mut user_session) = UserSession::<Uuid>::try_from_jwt_claims(claims)
{
if let Ok(session_id) = req.parse_session_id() {
user_session.set_session_id(session_id);
if let Ok(claims) = req.parse_jwt_claims(JwtClaims::shared_key()) {
match User::verify_jwt_claims(&claims).await {
Ok(verified) => {
if verified &&
let Ok(mut user_session) = UserSession::<Uuid>::try_from_jwt_claims(claims)
{
if let Ok(session_id) = req.parse_session_id() {
user_session.set_session_id(session_id);
}
req.set_data(user_session);
} else {
reject!(req, unauthorized, "invalid JWT claims");
}
}
Err(err) => reject!(req, unauthorized, err),
}
req.set_data(user_session);
} else if req.request_method() == "POST" {
reject!(req, unauthorized, "login is required");
}
Ok(next.run(req.into()).await)
}
8 changes: 4 additions & 4 deletions examples/dioxus-desktop/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ dioxus-router = "0.4.1"
tracing = "0.1.37"

[dependencies.serde]
version = "1.0.186"
version = "1.0.188"
features = ["derive"]

[dependencies.zino]
path = "../../zino"
version = "0.11.1"
version = "0.11.2"
features = ["dioxus"]

[dependencies.zino-core]
path = "../../zino-core"
version = "0.12.1"
version = "0.12.2"
features = ["orm-sqlite"]

[dependencies.zino-model]
path = "../../zino-model"
version = "0.9.1"
version = "0.9.2"
14 changes: 7 additions & 7 deletions zino-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "zino-core"
description = "Core types and traits for zino."
version = "0.12.1"
version = "0.12.2"
rust-version = "1.72"
edition = "2021"
license = "MIT"
Expand Down Expand Up @@ -104,19 +104,19 @@ mime_guess = "2.0.4"
multer = "2.1.0"
parking_lot = "0.12.1"
rand = "0.8.5"
regex = "1.9.3"
regex = "1.9.4"
reqwest-middleware = "0.2.3"
reqwest-retry = "0.2.2"
reqwest-tracing = "0.4.6"
rmp-serde = "1.1.2"
serde_qs = "0.12.0"
sha2 = "0.10.7"
sysinfo = "0.29.8"
sysinfo = "0.29.9"
task-local-extensions = "0.1.4"
toml = "0.7.6"
tracing = "0.1.37"
tracing-appender = "0.2.2"
url = "2.4.0"
url = "2.4.1"

[dependencies.argon2]
version = "0.5.1"
Expand All @@ -127,19 +127,19 @@ version = "0.14.0"
optional = true

[dependencies.chrono]
version = "0.4.26"
version = "0.4.27"
features = ["serde"]

[dependencies.datafusion]
version = "28.0.0"
version = "30.0.0"
optional = true

[dependencies.lru]
version = "0.11.0"
optional = true

[dependencies.minijinja]
version = "1.0.6"
version = "1.0.7"
optional = true
features = ["debug", "loader"]

Expand Down
2 changes: 1 addition & 1 deletion zino-core/src/connector/connector_arrow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use super::{Connector, DataSource, DataSourceConnector::Arrow};
use crate::{application::http_client, error::Error, extension::TomlTableExt, helper, Map, Record};
use datafusion::{
arrow::{datatypes::Schema, record_batch::RecordBatch},
common::FileCompressionType,
dataframe::DataFrame,
datasource::file_format::file_type::FileCompressionType,
execution::{
context::{SessionConfig, SessionContext, SessionState},
options::{AvroReadOptions, CsvReadOptions, NdJsonReadOptions, ParquetReadOptions},
Expand Down
4 changes: 2 additions & 2 deletions zino-core/src/database/accessor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ where
/// Constructs the mutation updates for the model of the next version.
fn next_version_updates(&self) -> Map {
let mut updates = Map::with_capacity(2);
updates.upsert("updated_at", DateTime::now().to_string());
updates.upsert("updated_at", DateTime::now().to_utc_timestamp());
updates.upsert("version", self.next_version());
updates
}
Expand Down Expand Up @@ -298,7 +298,7 @@ where
/// Constructs the mutation updates for the model of the next edition.
fn next_edition_updates(&self) -> Map {
let mut updates = Map::with_capacity(2);
updates.upsert("updated_at", DateTime::now().to_string());
updates.upsert("updated_at", DateTime::now().to_utc_timestamp());
updates.upsert("version", self.next_version());
updates.upsert("edition", self.next_edition());
updates
Expand Down
45 changes: 26 additions & 19 deletions zino-core/src/database/mutation.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
/// Generates SQL `SET` expressions.
use super::{query::QueryExt, DatabaseDriver, Schema};
use crate::{
extension::JsonObjectExt,
model::{EncodeColumn, Mutation, Query},
Map,
};
use crate::model::{EncodeColumn, Mutation, Query};

/// Extension trait for [`Mutation`](crate::model::Mutation).
pub(super) trait MutationExt<DB> {
Expand Down Expand Up @@ -36,9 +32,19 @@ impl MutationExt<DatabaseDriver> for Mutation {
continue;
};

let mut updates = Map::new();
let mut set_json_object = true;
for (operator, value) in map {
match operator.as_str() {
"$inc" => {
let value = col.encode_value(Some(value));
let mutation = format!(r#"{key} = {key} + {value}"#);
mutations.push(mutation);
}
"$mul" => {
let value = col.encode_value(Some(value));
let mutation = format!(r#"{key} = {key} * {value}"#);
mutations.push(mutation);
}
"$add" => {
if let Some(values) = value.as_array() && values.len() >= 2 {
let value = values.iter()
Expand All @@ -55,8 +61,8 @@ impl MutationExt<DatabaseDriver> for Mutation {
mutations.push(mutation);
}
}
"$sub" => {
if let Some(values) = value.as_array() && values.len() == 2 {
"$multiply" => {
if let Some(values) = value.as_array() && values.len() >= 2 {
let value = values.iter()
.map(|v| {
if let Some(s) = v.as_str() && M::has_column(s) {
Expand All @@ -66,13 +72,13 @@ impl MutationExt<DatabaseDriver> for Mutation {
}
})
.collect::<Vec<_>>()
.join(" - ");
.join(" * ");
let mutation = format!(r#"{key} = {value}"#);
mutations.push(mutation);
}
}
"$mul" => {
if let Some(values) = value.as_array() && values.len() >= 2 {
"$subtract" => {
if let Some(values) = value.as_array() && values.len() == 2 {
let value = values.iter()
.map(|v| {
if let Some(s) = v.as_str() && M::has_column(s) {
Expand All @@ -82,12 +88,12 @@ impl MutationExt<DatabaseDriver> for Mutation {
}
})
.collect::<Vec<_>>()
.join(" * ");
.join(" - ");
let mutation = format!(r#"{key} = {value}"#);
mutations.push(mutation);
}
}
"$div" => {
"$divide" => {
if let Some(values) = value.as_array() && values.len() == 2 {
let value = values.iter()
.map(|v| {
Expand Down Expand Up @@ -135,14 +141,15 @@ impl MutationExt<DatabaseDriver> for Mutation {
mutations.push(mutation);
}
}
_ => {
updates.upsert(operator, value.clone());
}
_ => ()
}
if operator.starts_with('$') {
set_json_object = false;
break;
}
}
if !updates.is_empty() {
let updates = updates.into();
let value = col.encode_value(Some(&updates));
if set_json_object {
let value = col.encode_value(Some(&value));
let mutation = format!(r#"{key} = {value}"#);
mutations.push(mutation);
}
Expand Down
Loading

0 comments on commit d75ecee

Please sign in to comment.