From 84e64f1fdf564267b15b514be5c8e217a35b7a16 Mon Sep 17 00:00:00 2001 From: tolumide-ng Date: Mon, 21 Feb 2022 18:41:02 +0100 Subject: [PATCH 1/5] Add twitar_derive and twitar_macro_derive as dependencies --- Cargo.lock | 2 ++ twitar/Cargo.toml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 4a5c385..2eea431 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1840,6 +1840,8 @@ dependencies = [ "thiserror", "tokio", "tower", + "twitar_macro", + "twitar_macro_derive", "url", "urlencoding", "uuid", diff --git a/twitar/Cargo.toml b/twitar/Cargo.toml index afa9087..b682ba6 100644 --- a/twitar/Cargo.toml +++ b/twitar/Cargo.toml @@ -37,6 +37,8 @@ tower = { version = "0.4.12", features=["retry", "limit", "timeout"] } url = { version = "2.2.2", features = ["serde"] } urlencoding = "2.1.0" uuid = { version = "0.8.2", features = ["v4"] } +twitar_macro = { path = "../twitar_macro" } +twitar_macro_derive = { path = "../twitar_macro_derive" } [dependencies.sqlx] From e557e28ec8d1c5ecc6f80f1e3ae437350c804702 Mon Sep 17 00:00:00 2001 From: tolumide-ng Date: Mon, 21 Feb 2022 23:00:05 +0100 Subject: [PATCH 2/5] Update GrantType enum to use derive_more for display --- twitar/src/helpers/commons.rs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/twitar/src/helpers/commons.rs b/twitar/src/helpers/commons.rs index ecdba80..970df9a 100644 --- a/twitar/src/helpers/commons.rs +++ b/twitar/src/helpers/commons.rs @@ -1,15 +1,9 @@ +#[derive(Debug, derive_more::Display)] pub enum GrantType { + #[display(fmt = "bearer")] Bearer, + #[display(fmt = "authorization_code")] Authorization, + #[display(fmt = "refresh_token")] Refresh, } - -impl std::fmt::Display for GrantType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Authorization => write!(f, "authorization_code"), - Self::Bearer => write!(f, "bearer"), - Self::Refresh => write!(f, "refresh_token"), - } - } -} \ No newline at end of file From b5d342f3b60f117ef2f4830dc4960754d7065f13 Mon Sep 17 00:00:00 2001 From: tolumide-ng Date: Mon, 21 Feb 2022 23:16:05 +0100 Subject: [PATCH 3/5] Empty makefile --- Makefile | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e69de29 From ae096d569563625ba8b7e7236e248b0b193c0144 Mon Sep 17 00:00:00 2001 From: tolumide-ng Date: Tue, 22 Feb 2022 03:05:12 +0100 Subject: [PATCH 4/5] Abstracts db interaction into base_repository --- twitar/README.md | 2 - twitar/src/base_repository/base_repository.rs | 43 ++++++++++++++ twitar/src/configurations/db_settings.rs | 6 +- twitar/src/configurations/variables.rs | 18 +----- twitar/src/controllers/authorize_bot.rs | 13 +++-- twitar/src/helpers/commons.rs | 56 +++++++++++++++++++ twitar/src/startup/server.rs | 14 +++++ 7 files changed, 127 insertions(+), 25 deletions(-) diff --git a/twitar/README.md b/twitar/README.md index c9b725a..5f37284 100644 --- a/twitar/README.md +++ b/twitar/README.md @@ -1,8 +1,6 @@ # play_twitter -Big Credit to [Egg-mode](https://github.com/egg-mode-rs/egg-mode) as a lot of my implementations was inspired by their design - TODOS! - [ ] All current redis implementations to be migrated Postgres - [ ] Only Save post ids on redis diff --git a/twitar/src/base_repository/base_repository.rs b/twitar/src/base_repository/base_repository.rs index e69de29..6846de0 100644 --- a/twitar/src/base_repository/base_repository.rs +++ b/twitar/src/base_repository/base_repository.rs @@ -0,0 +1,43 @@ +use futures::{stream, StreamExt}; +use redis::{AsyncCommands, ToRedisArgs, RedisError}; +use std::{fmt::Display}; + +use crate::{startup::server::{AppState, LocalAppState}, helpers::commons::AppEnv, configurations::variables::SettingsVars}; + +pub type ColsAndVals = Vec<(&'static str, V)>; + + +pub struct DBInsert { + table: String, + cols_vals: ColsAndVals, + returning: bool, +} + + +impl DBInsert { + pub fn create(table: String, cols_vals: ColsAndVals, returning: bool) -> Self { + // println!("") + Self {table, cols_vals, returning} + } + + pub async fn execute(self, app_state: LocalAppState) { + let LocalAppState { redis , app_env, db_pool, .. } = app_state; + + let querry = String::from(""); + println!("HERE NOW IN THE EXECUTE!"); + + match app_env { + AppEnv::Local => { + println!("BAD MAN ON THE LOCAL ENV"); + let mut con = redis.get_async_connection().await.unwrap(); + + for (key, val) in &self.cols_vals { + // this isn't the appropriate return type in this use case but ok + let d: String = con.set(key, val).await.unwrap(); + println!("THIUS SHOULD WORK {:#?} {}", key, val); + } + }, + AppEnv::Test | AppEnv::Staging | AppEnv::Production => {}, + } + } +} \ No newline at end of file diff --git a/twitar/src/configurations/db_settings.rs b/twitar/src/configurations/db_settings.rs index 8d6e126..fcc4732 100644 --- a/twitar/src/configurations/db_settings.rs +++ b/twitar/src/configurations/db_settings.rs @@ -1,6 +1,8 @@ use sqlx::postgres::{PgConnectOptions, PgSslMode}; -use super::variables::{SettingsVars, AppEnv}; +use crate::helpers::commons::AppEnv; + +use super::variables::{SettingsVars}; // sqlx::migrate!().run(<&your_pool OR &mut your_connection>).await?; @@ -18,7 +20,7 @@ impl DatabaseSettings { pub fn new(vars: SettingsVars) -> Self { let mut require_ssl = true; - if [AppEnv::Local.to_string(), AppEnv::Test.to_string()].contains(&vars.app_env) { + if [AppEnv::Local, AppEnv::Test].contains(&vars.app_env) { require_ssl = false; } diff --git a/twitar/src/configurations/variables.rs b/twitar/src/configurations/variables.rs index 28dd91f..1f11221 100644 --- a/twitar/src/configurations/variables.rs +++ b/twitar/src/configurations/variables.rs @@ -2,19 +2,7 @@ use dotenv::dotenv; use serde::Deserialize; use std::env; -use crate::helpers::gen_pkce::Pkce; - -#[derive(Debug, Clone, Deserialize, derive_more::Display)] -pub enum AppEnv { - #[display(fmt = "local")] - Local, - #[display(fmt = "test")] - Test, - #[display(fmt = "staging")] - Staging, - #[display(fmt = "production")] - Production, -} +use crate::helpers::{gen_pkce::Pkce, commons::AppEnv}; #[derive(Debug, Clone, Deserialize)] @@ -30,7 +18,7 @@ pub struct SettingsVars { pub api_key_secret: String, pub client_secret: String, pub twitter_url: String, - pub app_env: String, + pub app_env: AppEnv, pub db_host: String, pub db_port: u16, pub db_username: String, @@ -69,7 +57,7 @@ impl SettingsVars { api_key_secret: Self::get_var("API_KEY_SECRET"), client_secret: Self::get_var("CLIENT_SECRET"), twitter_url: Self::get_var("TWITTER_API"), - app_env: Self::get_var("APP_ENV"), + app_env: AppEnv::new(Self::get_var("APP_ENV")), db_host: Self::get_var("DB_HOST"), db_port: Self::get_var("DB_PORT").parse::().unwrap(), db_username: Self::get_var("DB_USERNAME"), diff --git a/twitar/src/controllers/authorize_bot.rs b/twitar/src/controllers/authorize_bot.rs index 8e9a6e4..79eb1ed 100644 --- a/twitar/src/controllers/authorize_bot.rs +++ b/twitar/src/controllers/authorize_bot.rs @@ -1,6 +1,7 @@ use hyper::{Method, Body, Response}; use redis::{AsyncCommands}; +use crate::base_repository::base_repository::DBInsert; use crate::startup::server::AppState; use crate::helpers::response::ApiBody; use crate::helpers::{ @@ -14,21 +15,21 @@ use crate::middlewares::request_builder::RequestBuilder; pub async fn authorize_bot(app_state: AppState) -> TResult { - let SettingsVars {client_id, callback_url, state, ..} = app_state.env_vars; + let SettingsVars {client_id, callback_url, state, ..} = app_state.env_vars.clone(); // store this pkce value in redis for the specific user associated by email - let mut con = app_state.redis.get_async_connection().await.unwrap(); - - + // let mut con = app_state.redis.clone().get_async_connection().await.unwrap(); let pkce: String = Pkce::new().to_string(); let scopes = vec![Scope::ReadTweet, Scope::ReadUsers, Scope::ReadFollows, Scope::WriteFollows, Scope::OfflineAccess, Scope::WriteTweet, Scope::WriteLike, Scope::ReadLike]; - + // - todo()! need macros to write the sqlx query in a prod env and use redis in a local env // take classes on rust macros - https://veykril.github.io/tlborm/syntax-extensions.html // sqlx::query!(r#"INSERT INTO auth_two (pkce) VALUES ($1)"#, pkce) // .execute(&app_state.db_pool).await.map_err(|e| {eprintln!("ERROR ADDING PKCE {:#?}", e)}).unwrap(); - con.set("pkce", &pkce).await?; + // con.set("pkce", &pkce).await?; + let local_state = app_state.to_local(); + DBInsert::create("auth_two".into(), vec![("pkce", &pkce)], false).execute(local_state).await; let query_params = KeyVal::new() .add_list_keyval(vec![ diff --git a/twitar/src/helpers/commons.rs b/twitar/src/helpers/commons.rs index 970df9a..050850c 100644 --- a/twitar/src/helpers/commons.rs +++ b/twitar/src/helpers/commons.rs @@ -1,3 +1,9 @@ +use std::borrow::Cow; + +use redis::Client as RedisClient; +use serde::Deserialize; +use sqlx::{Pool, Postgres}; + #[derive(Debug, derive_more::Display)] pub enum GrantType { #[display(fmt = "bearer")] @@ -7,3 +13,53 @@ pub enum GrantType { #[display(fmt = "refresh_token")] Refresh, } + +#[derive(Debug, PartialEq, Clone, Deserialize, derive_more::Display)] +pub enum AppEnv { + #[display(fmt = "local")] + Local, + #[display(fmt = "test")] + Test, + #[display(fmt = "staging")] + Staging, + #[display(fmt = "production")] + Production, +} + +impl AppEnv { + pub fn new(env: String) -> AppEnv { + let env = env.as_str(); + + match env { + "test" => AppEnv::Test, + "staging" => AppEnv::Staging, + "production" => AppEnv::Production, + _ => AppEnv::Local + } + } +} + + + +#[derive(Debug)] +pub enum DBClient { + Redis(RedisClient), + Postgres(Pool), +} + + +impl DBClient { + fn with_postgres(self) -> Option> { + match self { + DBClient::Postgres(p) => Some(p), + _ => None + } + } + + fn with_redis (self) -> Option { + match self { + DBClient::Redis(r) => Some(r), + _ => None, + } + } +} \ No newline at end of file diff --git a/twitar/src/startup/server.rs b/twitar/src/startup/server.rs index 488fa2f..9bf0464 100644 --- a/twitar/src/startup/server.rs +++ b/twitar/src/startup/server.rs @@ -11,6 +11,7 @@ use dotenv::dotenv; use redis::{Client as RedisClient}; use crate::configurations::db_settings::DatabaseSettings; +use crate::helpers::commons::AppEnv; use crate::helpers::request::HyperClient; use crate::routes::server::routes; use crate::configurations::variables::SettingsVars; @@ -20,6 +21,7 @@ use crate::configurations::variables::SettingsVars; type GenericError = hyper::Error; +#[derive(Debug)] pub struct AppState { pub redis: RedisClient, pub hyper: HyperClient, @@ -28,10 +30,22 @@ pub struct AppState { pub db_pool: Pool, } +#[derive(Debug, Clone)] +pub struct LocalAppState { + pub redis: RedisClient, + pub app_env: AppEnv, + pub db_pool: Pool, +} + impl AppState { fn new(env_vars: SettingsVars, req: Request, hyper: HyperClient, redis: RedisClient, db_pool: Pool) -> Self { Self { redis, hyper, req, env_vars, db_pool} } + + pub fn to_local(&self) -> LocalAppState { + let app_env = self.env_vars.app_env.clone(); + LocalAppState { redis: self.redis.clone(), app_env: app_env, db_pool: self.db_pool.clone() } + } } From 93167ccfbab7e3fe74ee9fe3c616569a9905c813 Mon Sep 17 00:00:00 2001 From: tolumide-ng Date: Tue, 22 Feb 2022 21:08:56 +0100 Subject: [PATCH 5/5] Incomplete sqlx --- twitar/sqlx-data.json | 14 +++++ twitar/src/base_repository/base_repository.rs | 26 +++++++-- twitar/src/controllers.rs | 1 + twitar/src/controllers/authorize_bot.rs | 26 +++++---- twitar/src/controllers/commons.rs | 1 + twitar/src/controllers/handle_redirect.rs | 54 +++++++++++-------- ...fe3ad16b72230967de01f640b7e4729b49fce.json | 15 ++++++ 7 files changed, 101 insertions(+), 36 deletions(-) create mode 100644 twitar/src/controllers/commons.rs create mode 100644 twitar/target/sqlx/query-4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.json diff --git a/twitar/sqlx-data.json b/twitar/sqlx-data.json index cb61ff7..9e35713 100644 --- a/twitar/sqlx-data.json +++ b/twitar/sqlx-data.json @@ -11,5 +11,19 @@ } }, "query": "INSERT INTO auth_two (pkce) VALUES ($1)" + }, + "31a5da9b895390da875ff36e4cebd34125f3382a01f9ff523fd47a0b5463b610": { + "describe": { + "columns": [], + "nullable": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Text" + ] + } + }, + "query": "UPDATE auth_two SET access_token=$1, refresh_token=$2\n WHERE pkce=$3" } } \ No newline at end of file diff --git a/twitar/src/base_repository/base_repository.rs b/twitar/src/base_repository/base_repository.rs index 6846de0..e7123ab 100644 --- a/twitar/src/base_repository/base_repository.rs +++ b/twitar/src/base_repository/base_repository.rs @@ -23,21 +23,37 @@ impl DBInsert { pub async fn execute(self, app_state: LocalAppState) { let LocalAppState { redis , app_env, db_pool, .. } = app_state; - let querry = String::from(""); println!("HERE NOW IN THE EXECUTE!"); match app_env { AppEnv::Local => { - println!("BAD MAN ON THE LOCAL ENV"); let mut con = redis.get_async_connection().await.unwrap(); for (key, val) in &self.cols_vals { // this isn't the appropriate return type in this use case but ok - let d: String = con.set(key, val).await.unwrap(); - println!("THIUS SHOULD WORK {:#?} {}", key, val); + let _d: String = con.set(key, val).await.unwrap(); } }, - AppEnv::Test | AppEnv::Staging | AppEnv::Production => {}, + AppEnv::Test | AppEnv::Staging | AppEnv::Production => { + let mut col_names: Vec<&'static str> = vec![]; + let mut positions: Vec = vec![]; + let mut vals: Vec<&V> = vec![]; + + for (index, (key, val)) in self.cols_vals.iter().enumerate() { + col_names.push(key); + positions.push(format!("${}", index)); + vals.push(val); + } + + let querry_str = format!( + r#"INSERT INTO {} ({}) VALUES ({})"#, + self.table, + col_names.join(", "), + positions.join(", "), + ); + + // sqlx::query!(querry_str).execute(&db_pool).await.unwrap(); + }, } } } \ No newline at end of file diff --git a/twitar/src/controllers.rs b/twitar/src/controllers.rs index bb5285d..97a7409 100644 --- a/twitar/src/controllers.rs +++ b/twitar/src/controllers.rs @@ -8,6 +8,7 @@ mod refresh_token; mod user_lookup; mod destroy; mod oauth_flow; +mod commons; pub use not_found::not_found; diff --git a/twitar/src/controllers/authorize_bot.rs b/twitar/src/controllers/authorize_bot.rs index 79eb1ed..9efa9f5 100644 --- a/twitar/src/controllers/authorize_bot.rs +++ b/twitar/src/controllers/authorize_bot.rs @@ -1,7 +1,7 @@ use hyper::{Method, Body, Response}; use redis::{AsyncCommands}; -use crate::base_repository::base_repository::DBInsert; +use crate::helpers::commons::AppEnv; use crate::startup::server::AppState; use crate::helpers::response::ApiBody; use crate::helpers::{ @@ -15,21 +15,27 @@ use crate::middlewares::request_builder::RequestBuilder; pub async fn authorize_bot(app_state: AppState) -> TResult { - let SettingsVars {client_id, callback_url, state, ..} = app_state.env_vars.clone(); + let SettingsVars {client_id, callback_url, state, app_env, ..} = app_state.env_vars.clone(); // store this pkce value in redis for the specific user associated by email - // let mut con = app_state.redis.clone().get_async_connection().await.unwrap(); + let mut con = app_state.redis.get_async_connection().await.unwrap(); let pkce: String = Pkce::new().to_string(); let scopes = vec![Scope::ReadTweet, Scope::ReadUsers, Scope::ReadFollows, Scope::WriteFollows, Scope::OfflineAccess, Scope::WriteTweet, Scope::WriteLike, Scope::ReadLike]; - // - todo()! need macros to write the sqlx query in a prod env and use redis in a local env + // - todo()! need macros to write the sqlx query in a prod env and use redis in a local env : Won't work :eyes // take classes on rust macros - https://veykril.github.io/tlborm/syntax-extensions.html - // sqlx::query!(r#"INSERT INTO auth_two (pkce) VALUES ($1)"#, pkce) - // .execute(&app_state.db_pool).await.map_err(|e| {eprintln!("ERROR ADDING PKCE {:#?}", e)}).unwrap(); + match app_env { + AppEnv::Local | AppEnv::Test => { + con.set("pkce", &pkce).await?; + } + AppEnv::Production | AppEnv::Staging => { + sqlx::query!(r#"INSERT INTO auth_two (pkce) VALUES ($1)"#, pkce) + .execute(&app_state.db_pool).await.map_err(|e| {eprintln!("ERROR ADDING PKCE {:#?}", e)}).unwrap(); + } + } - // con.set("pkce", &pkce).await?; - let local_state = app_state.to_local(); - DBInsert::create("auth_two".into(), vec![("pkce", &pkce)], false).execute(local_state).await; + // let local_state = app_state.to_local(); + // DBInsert::create("auth_two".into(), vec![("pkce", &pkce)], false).execute(local_state).await; let query_params = KeyVal::new() .add_list_keyval(vec![ @@ -53,4 +59,4 @@ pub async fn authorize_bot(app_state: AppState) -> TResult { .body(Body::from(request.uri().to_string())).unwrap(); Ok(response_body) -} \ No newline at end of file +} diff --git a/twitar/src/controllers/commons.rs b/twitar/src/controllers/commons.rs new file mode 100644 index 0000000..a574f54 --- /dev/null +++ b/twitar/src/controllers/commons.rs @@ -0,0 +1 @@ +pub struct Controller; \ No newline at end of file diff --git a/twitar/src/controllers/handle_redirect.rs b/twitar/src/controllers/handle_redirect.rs index d168dff..2ba3bc6 100644 --- a/twitar/src/controllers/handle_redirect.rs +++ b/twitar/src/controllers/handle_redirect.rs @@ -4,13 +4,13 @@ use redis::{Client as RedisClient}; use sqlx::{Pool, Postgres}; use crate::{helpers::{ response::{TResult, ApiBody, make_request, ResponseBuilder}, - request::{HyperClient}, keyval::KeyVal, commons::GrantType}, + request::{HyperClient}, keyval::KeyVal, commons::{GrantType, AppEnv}}, configurations::variables::SettingsVars, errors::response::{TError}, middlewares::request_builder::{RequestBuilder, AuthType}, interceptors::handle_request::{Interceptor, V2TokensType}, startup::server::AppState }; -async fn access_token(hyper_client: HyperClient, db_client: Pool, redis_client: RedisClient, auth_code: String) -> Result<(), TError> { +async fn access_token(hyper_client: HyperClient, db_client: Pool, redis_client: RedisClient, auth_code: String, app_env: AppEnv) -> Result<(), TError> { let SettingsVars{client_id, callback_url, client_secret, twitter_url, ..} = SettingsVars::new(); let mut con = redis_client.get_async_connection().await.unwrap(); @@ -36,16 +36,23 @@ async fn access_token(hyper_client: HyperClient, db_client: Pool, redi // authentication service user_id would be used to insert here // - todo()! need macros to write the sqlx query in a prod env and use redis in a local env // take classes on rust macros - https://veykril.github.io/tlborm/syntax-extensions.html - // sqlx::query!(r#"UPDATE auth_two - // SET access_token=$1, refresh_token=$2 - // WHERE pkce=$3"#, - // &map.get(V2TokensType::Access), &map.get(V2TokensType::Refresh), pkce) - // .execute(&db_client).await.map_err(|e| { - // // tracing here later - // eprintln!("ERROR ADDING ACCESS TOKEN {:#?}", e)}).unwrap(); - - redis::cmd("SET").arg(&["access_token", &map.get(V2TokensType::Access)]).query_async(&mut con).await?; - redis::cmd("SET").arg(&["refresh_token", &map.get(V2TokensType::Refresh)]).query_async(&mut con).await?; + + + match app_env { + AppEnv::Local | AppEnv::Test => { + redis::cmd("SET").arg(&["access_token", &map.get(V2TokensType::Access)]).query_async(&mut con).await?; + redis::cmd("SET").arg(&["refresh_token", &map.get(V2TokensType::Refresh)]).query_async(&mut con).await?; + } + AppEnv::Production | AppEnv::Staging => { + sqlx::query!(r#"UPDATE auth_two SET access_token=$1, refresh_token=$2 + WHERE pkce=$3"#, + &map.get(V2TokensType::Access), &map.get(V2TokensType::Refresh), pkce) + .execute(&db_client).await.map_err(|e| { + // tracing here later + eprintln!("ERROR ADDING ACCESS TOKEN {:#?}", e)}).unwrap(); + } + } + return Ok(()) } @@ -56,7 +63,7 @@ async fn access_token(hyper_client: HyperClient, db_client: Pool, redi // req: Request, hyper_client: HyperClient, redis_client: RedisClient pub async fn handle_redirect(app_state: AppState) -> TResult { let AppState {redis, hyper, req, env_vars, ..} = app_state; - let SettingsVars{state, api_key, twitter_url, ..} = env_vars; + let SettingsVars{state, api_key, twitter_url, app_env, ..} = env_vars; @@ -70,10 +77,9 @@ pub async fn handle_redirect(app_state: AppState) -> TResult { let oauth_token: String = redis::cmd("GET").arg(&["oauth_token"]).query_async(&mut con).await?; if k.validate("oauth_token".into(),oauth_token.clone()) { let verifier = k.get("oauth_verifier").unwrap(); - redis::cmd("SET").arg(&["oauth_verifier", verifier]).query_async(&mut con).await?; - let target = format!("{}/oauth/access_token", twitter_url); + let target = format!("{}/oauth/access_token", twitter_url); let req = RequestBuilder::new(Method::POST, target) .with_query("oauth_consumer_key", &api_key) .with_query("oauth_token", &oauth_token) @@ -87,9 +93,17 @@ pub async fn handle_redirect(app_state: AppState) -> TResult { let params = KeyVal::string_to_keyval(body_string); if let Some(map) = params { - redis::cmd("SET").arg(&["oauth_token", map.get("oauth_token").unwrap()]).query_async(&mut con).await?; - redis::cmd("SET").arg(&["oauth_token_secret", map.get("oauth_token_secret").unwrap()]).query_async(&mut con).await?; - redis::cmd("SET").arg(&["userid", map.get("user_id").unwrap()]).query_async(&mut con).await?; + match app_env { + AppEnv::Local | AppEnv::Test => { + redis::cmd("SET").arg(&["oauth_verifier", verifier]).query_async(&mut con).await?; + redis::cmd("SET").arg(&["oauth_token", map.get("oauth_token").unwrap()]).query_async(&mut con).await?; + redis::cmd("SET").arg(&["oauth_token_secret", map.get("oauth_token_secret").unwrap()]).query_async(&mut con).await?; + redis::cmd("SET").arg(&["userid", map.get("user_id").unwrap()]).query_async(&mut con).await?; + } + AppEnv::Production | AppEnv::Staging => { + // + } + } return ResponseBuilder::new("Access Granted".into(), Some(""), StatusCode::OK.as_u16()).reply(); } @@ -105,7 +119,7 @@ pub async fn handle_redirect(app_state: AppState) -> TResult { if let Some(dict) = is_v2_callback { if query_params.validate("state".into(), state) { let code = dict.get("code").unwrap().to_string(); - access_token(hyper.clone(), app_state.db_pool, redis, code).await?; + access_token(hyper.clone(), app_state.db_pool, redis, code, app_env).await?; return ResponseBuilder::new("Access Granted".into(), Some(""), StatusCode::OK.as_u16()).reply(); } @@ -119,6 +133,4 @@ pub async fn handle_redirect(app_state: AppState) -> TResult { ResponseBuilder::new("Bad request".into(), Some(""), StatusCode::BAD_REQUEST.as_u16()).reply() - - } diff --git a/twitar/target/sqlx/query-4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.json b/twitar/target/sqlx/query-4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.json new file mode 100644 index 0000000..7647cb7 --- /dev/null +++ b/twitar/target/sqlx/query-4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.json @@ -0,0 +1,15 @@ +{ + "query": "UPDATE auth_two SET access_token=$1, refresh_token=$2\n WHERE pkce=$3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "9428fd947c6323ab737cddb76eeb1bd4badaf46cb65317eed87fc87b4eeb7e7a" +} \ No newline at end of file