Skip to content

Commit

Permalink
add gen-token command for db service, refactoring to SessionToken
Browse files Browse the repository at this point in the history
  • Loading branch information
Kirill-K-1 committed Jul 22, 2024
1 parent 12ba51e commit c878030
Show file tree
Hide file tree
Showing 9 changed files with 321 additions and 57 deletions.
126 changes: 123 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,4 @@ rand = "0"
anyhow = "1"
dotenv = "0"
sendgrid = "0"
clap = { version = "4", features = ["derive"] }
2 changes: 1 addition & 1 deletion config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@
"url": "https://network.ambrosus.io",
"requestTimeout": 10000
},
"serverNodesManagerAddress": "0x"
"serverNodesManagerAddress": "0x55C402b5F9C2c3DfE3d866B36598f0Fd53e03B89"
}
1 change: 1 addition & 0 deletions gov-portal-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ base64 = { workspace = true }
anyhow = { workspace = true }
dotenv = { workspace = true }
rand = { workspace = true }
clap = { workspace = true }

[dev-dependencies]
assert_matches = { workspace = true }
Expand Down
46 changes: 44 additions & 2 deletions gov-portal-db/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ mod server;
mod session_token;
mod users_manager;

use std::sync::Arc;
use clap::{Args, Parser, Subcommand};
use std::{sync::Arc, time::Duration};

use session_token::SessionManager;
use shared::{logger, utils};
use users_manager::UsersManager;

const ONE_YEAR: u64 = 86_400 * 365; // one year in seconds

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
logger::init();
Expand All @@ -20,10 +24,48 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

let config = utils::load_config::<config::AppConfig>("./gov-portal-db").await?;

let session_manager = SessionManager::new(config.session.clone());

let cli = Cli::parse();
match &cli.command {
Some(Commands::GenToken(arg)) => {
let lifetime = arg.lifetime.unwrap_or(ONE_YEAR);

println!(
"{}",
session_manager
.acquire_internal_token_with_lifetime(Duration::from_secs(lifetime))?
);
return Ok(());
}
None => (),
};

let users_manager =
Arc::new(UsersManager::new(&config.mongo, config.users_manager.clone()).await?);

server::start(config, users_manager.clone()).await?;
server::start(config, users_manager, session_manager).await?;

Ok(())
}

#[derive(Parser)]
#[command(version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
/// Generates token to access /status endpoint (use -l or --lifetime for custom lifetime set, defaults to 1 year)
GenToken(GetTokenArgs),
}

#[derive(Args)]
struct GetTokenArgs {
/// Lifetime in seconds for an access token (defaults to 1 year)
#[arg(short, long)]
lifetime: Option<u64>,
}
45 changes: 24 additions & 21 deletions gov-portal-db/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,13 @@ impl AppState {
pub async fn new(
config: AppConfig,
users_manager: Arc<UsersManager>,
session_manager: SessionManager,
) -> Result<Self, AppError> {
Ok(Self {
quiz: Quiz {
config: config.quiz.clone(),
},
session_manager: SessionManager::new(config.session.clone()),
session_manager,
users_manager,
config,
})
Expand Down Expand Up @@ -144,13 +145,17 @@ impl VerifyEmailRequest {
}
}

pub async fn start(config: AppConfig, users_manager: Arc<UsersManager>) -> Result<(), AppError> {
pub async fn start(
config: AppConfig,
users_manager: Arc<UsersManager>,
session_manager: SessionManager,
) -> Result<(), AppError> {
let addr = config
.listen_address
.parse::<std::net::SocketAddr>()
.expect("Can't parse socket address");

let state = AppState::new(config, users_manager).await?;
let state = AppState::new(config, users_manager, session_manager).await?;

let app = Router::new()
.route("/token", post(token_route))
Expand Down Expand Up @@ -200,13 +205,17 @@ async fn status_route(
) -> Result<Json<()>, String> {
tracing::debug!("[/status] Request {token:?}");

let res = state
.users_manager
.mongo_client
.server_status()
.await
.map(|_| ())
.map_err(|e| e.to_string());
let res = match state.session_manager.verify_internal_token(&token) {
Ok(_) => state
.users_manager
.mongo_client
.server_status()
.await
.map(|_| ())
.map_err(|e| e.to_string()),

Err(e) => Err(format!("Request failure. Error: {e}")),
};

tracing::debug!("[/status] Response {res:?}");

Expand Down Expand Up @@ -587,7 +596,7 @@ mod tests {
.map(|quiz_response| VerifyQuizRequest {
answers: vec![QuizAnswer::new("Q1", "V2")],
quiz_token: quiz_response.quiz_token,
session: default_session_token(),
session: SessionToken::default(),
})
.unwrap(),
expected: true,
Expand Down Expand Up @@ -628,7 +637,7 @@ mod tests {
QuizAnswer::new("Q1", "V2"),
],
quiz_token: quiz_response.quiz_token,
session: default_session_token(),
session: SessionToken::default(),
})
.unwrap(),
expected: true,
Expand Down Expand Up @@ -669,7 +678,7 @@ mod tests {
QuizAnswer::new("Q2", "V2"),
],
quiz_token: quiz_response.quiz_token,
session: default_session_token(),
session: SessionToken::default(),
})
.unwrap(),
expected: false,
Expand All @@ -688,7 +697,7 @@ mod tests {
.map(|quiz_response| VerifyQuizRequest {
answers: vec![QuizAnswer::new("Q1", "V2")],
quiz_token: quiz_response.quiz_token,
session: default_session_token(),
session: SessionToken::default(),
})
.unwrap(),
expected: false,
Expand All @@ -707,7 +716,7 @@ mod tests {
.map(|quiz_response| VerifyQuizRequest {
answers: vec![QuizAnswer::new("Q1", "V2")],
quiz_token: quiz_response.quiz_token,
session: default_session_token(),
session: SessionToken::default(),
})
.unwrap(),
expected: false,
Expand Down Expand Up @@ -762,10 +771,4 @@ mod tests {
}
}
}

fn default_session_token() -> SessionToken {
SessionToken {
token: "".to_string(),
}
}
}
Loading

0 comments on commit c878030

Please sign in to comment.