From ddcd9ce3171b1feb49edc3675db14b9a83eb0747 Mon Sep 17 00:00:00 2001 From: CODEVO Date: Sat, 11 Feb 2023 06:22:51 +0000 Subject: [PATCH 1/3] updated --- .env | 6 +-- src/github_oauth.rs | 71 -------------------------------- src/handler.rs | 98 +-------------------------------------------- src/main.rs | 1 - 4 files changed, 2 insertions(+), 174 deletions(-) delete mode 100644 src/github_oauth.rs diff --git a/.env b/.env index 21169dc..5a2647d 100644 --- a/.env +++ b/.env @@ -6,8 +6,4 @@ TOKEN_MAXAGE=60 GOOGLE_OAUTH_CLIENT_ID=176116788100-cv8354tkaqlpf69qmi3d8hkv4t5osm9e.apps.googleusercontent.com GOOGLE_OAUTH_CLIENT_SECRET=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 -GOOGLE_OAUTH_REDIRECT_URL=http://localhost:8000/api/sessions/oauth/google - -GITHUB_OAUTH_CLIENT_ID=27e779e9877f02cb75ed -GITHUB_OAUTH_CLIENT_SECRET=f41bff01b821b471ff163e938364a7586b0180c6 -GITHUB_OAUTH_REDIRECT_URL=http://localhost:8000/api/sessions/oauth/github \ No newline at end of file +GOOGLE_OAUTH_REDIRECT_URL=http://localhost:8000/api/sessions/oauth/google \ No newline at end of file diff --git a/src/github_oauth.rs b/src/github_oauth.rs deleted file mode 100644 index 3bf5b88..0000000 --- a/src/github_oauth.rs +++ /dev/null @@ -1,71 +0,0 @@ -use actix_web::web; -use reqwest::Client; -use serde::Deserialize; -use std::error::Error; - -use crate::model::AppState; - -#[derive(Deserialize)] -pub struct GitHubOauthToken { - pub access_token: String, -} - -#[derive(Deserialize)] -pub struct GitHubUserResult { - pub login: String, - pub avatar_url: String, - pub email: String, -} - -pub async fn get_github_oauth_token( - authorization_code: &str, - data: &web::Data, -) -> Result> { - let client_secret = data.env.github_oauth_client_id.to_owned(); - let client_id = data.env.github_oauth_client_secret.to_owned(); - - let root_url = "https://github.com/login/oauth/access_token"; - - let client = Client::new(); - - let params = [ - ("client_id", client_id.as_str()), - ("code", authorization_code), - ("client_secret", client_secret.as_str()), - ]; - - let response = client - .post(root_url) - .header("Accept", "application/json") - .form(¶ms) - .send() - .await?; - - if response.status().is_success() { - let oauth_response = response.json::().await?; - Ok(oauth_response) - } else { - let message = "An error occurred while trying to retrieve the access token."; - Err(From::from(message)) - } -} - -pub async fn get_github_user(access_token: &str) -> Result> { - let root_url = "https://api.github.com/user"; - - let client = Client::new(); - - let response = client - .get(root_url) - .bearer_auth(access_token) - .send() - .await?; - - if response.status().is_success() { - let user_info = response.json::().await?; - Ok(user_info) - } else { - let message = "An error occurred while trying to retrieve user information."; - Err(From::from(message)) - } -} diff --git a/src/handler.rs b/src/handler.rs index e386bdb..f0a90a9 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -1,6 +1,5 @@ use crate::{ authenticate_token::AuthenticationGuard, - github_oauth::{get_github_oauth_token, get_github_user}, google_oauth::{get_google_user, request_token}, model::{AppState, LoginUserSchema, QueryCode, RegisterUserSchema, TokenClaims, User}, response::{FilteredUser, UserData, UserResponse}, @@ -16,7 +15,7 @@ use uuid::Uuid; #[get("/healthchecker")] async fn health_checker_handler() -> impl Responder { - const MESSAGE: &str = "Implement Google and GitHub OAuth2 in Rust"; + const MESSAGE: &str = "How to Implement Google OAuth2 in Rust"; HttpResponse::Ok().json(serde_json::json!({"status": "success", "message": MESSAGE})) } @@ -209,100 +208,6 @@ async fn google_oauth_handler( response.finish() } -#[get("/sessions/oauth/github")] -async fn github_oauth_handler( - query: web::Query, - data: web::Data, -) -> impl Responder { - let code = &query.code; - let state = &query.state; - - if code.is_empty() { - return HttpResponse::Unauthorized().json( - serde_json::json!({"status": "fail", "message": "Authorization code not provided!"}), - ); - } - - let token_response = get_github_oauth_token(code.as_str(), &data).await; - if token_response.is_err() { - let message = token_response.err().unwrap().to_string(); - return HttpResponse::BadGateway() - .json(serde_json::json!({"status": "fail", "message": message})); - } - - let token_response = token_response.unwrap(); - println!("Bearer {}", token_response.access_token); - let github_user = get_github_user(&token_response.access_token).await; - if github_user.is_err() { - let message = github_user.err().unwrap().to_string(); - return HttpResponse::BadGateway() - .json(serde_json::json!({"status": "fail", "message": message})); - } - - let github_user = github_user.unwrap(); - - let mut vec = data.db.lock().unwrap(); - let email = github_user.email.to_lowercase(); - let user = vec.iter_mut().find(|user| user.email == email); - - let user_id: String; - - if user.is_some() { - let user = user.unwrap(); - user_id = user.id.to_owned().unwrap(); - user.email = email.to_owned(); - user.photo = github_user.avatar_url; - user.updatedAt = Some(Utc::now()); - } else { - let datetime = Utc::now(); - let id = Uuid::new_v4(); - user_id = id.to_owned().to_string(); - let user_data = User { - id: Some(id.to_string()), - name: github_user.login, - verified: true, - email, - provider: "GitHub".to_string(), - role: "user".to_string(), - password: "".to_string(), - photo: github_user.avatar_url, - createdAt: Some(datetime), - updatedAt: Some(datetime), - }; - - vec.push(user_data.to_owned()); - } - - let jwt_secret = data.env.jwt_secret.to_owned(); - let now = Utc::now(); - let iat = now.timestamp() as usize; - let exp = (now + Duration::minutes(data.env.jwt_max_age)).timestamp() as usize; - let claims: TokenClaims = TokenClaims { - sub: user_id, - exp, - iat, - }; - - let token = encode( - &Header::default(), - &claims, - &EncodingKey::from_secret(jwt_secret.as_ref()), - ) - .unwrap(); - - let cookie = Cookie::build("token", token) - .path("/") - .max_age(ActixWebDuration::new(60 * data.env.jwt_max_age, 0)) - .http_only(true) - .finish(); - - let frontend_origin = data.env.client_origin.to_owned(); - let mut response = HttpResponse::Found(); - response.append_header((LOCATION, format!("{}{}", frontend_origin, state))); - response.cookie(cookie); - response.finish() -} - #[get("/auth/logout")] async fn logout_handler(_: AuthenticationGuard) -> impl Responder { let cookie = Cookie::build("token", "") @@ -357,7 +262,6 @@ pub fn config(conf: &mut web::ServiceConfig) { .service(register_user_handler) .service(login_user_handler) .service(google_oauth_handler) - .service(github_oauth_handler) .service(logout_handler) .service(get_me_handler); diff --git a/src/main.rs b/src/main.rs index 741904c..5a929ee 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,5 @@ mod authenticate_token; mod config; -mod github_oauth; mod google_oauth; mod handler; mod model; From 329e49522a7caf138286227c31d29cc94975350f Mon Sep 17 00:00:00 2001 From: CODEVO Date: Sat, 11 Feb 2023 06:25:47 +0000 Subject: [PATCH 2/3] updated --- .env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.env b/.env index 5a2647d..0f54185 100644 --- a/.env +++ b/.env @@ -4,6 +4,6 @@ JWT_SECRET=my_ultra_secure_secret TOKEN_EXPIRED_IN=60m TOKEN_MAXAGE=60 -GOOGLE_OAUTH_CLIENT_ID=176116788100-cv8354tkaqlpf69qmi3d8hkv4t5osm9e.apps.googleusercontent.com -GOOGLE_OAUTH_CLIENT_SECRET=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 +GOOGLE_OAUTH_CLIENT_ID= +GOOGLE_OAUTH_CLIENT_SECRET= GOOGLE_OAUTH_REDIRECT_URL=http://localhost:8000/api/sessions/oauth/google \ No newline at end of file From e969d0b8e473c8bfc4d7e01cb2bd56d0351d834d Mon Sep 17 00:00:00 2001 From: CODEVO Date: Mon, 13 Feb 2023 10:23:50 +0000 Subject: [PATCH 3/3] updated --- src/config.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/config.rs b/src/config.rs index a249a6b..2cccfbe 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,9 +7,6 @@ pub struct Config { pub google_oauth_client_id: String, pub google_oauth_client_secret: String, pub google_oauth_redirect_url: String, - pub github_oauth_client_id: String, - pub github_oauth_client_secret: String, - pub github_oauth_redirect_url: String, } impl Config { @@ -25,12 +22,6 @@ impl Config { .expect("GOOGLE_OAUTH_CLIENT_SECRET must be set"); let google_oauth_redirect_url = std::env::var("GOOGLE_OAUTH_REDIRECT_URL") .expect("GOOGLE_OAUTH_REDIRECT_URL must be set"); - let github_oauth_client_id = - std::env::var("GITHUB_OAUTH_CLIENT_ID").expect("GITHUB_OAUTH_CLIENT_ID must be set"); - let github_oauth_client_secret = std::env::var("GITHUB_OAUTH_CLIENT_SECRET") - .expect("GITHUB_OAUTH_CLIENT_SECRET must be set"); - let github_oauth_redirect_url = std::env::var("GITHUB_OAUTH_REDIRECT_URL") - .expect("GITHUB_OAUTH_REDIRECT_URL must be set"); Config { client_origin, @@ -40,9 +31,6 @@ impl Config { google_oauth_client_id, google_oauth_client_secret, google_oauth_redirect_url, - github_oauth_client_id, - github_oauth_client_secret, - github_oauth_redirect_url, } } }