From c768aa93be5c66388f43954e7371b9b061cf2e2a Mon Sep 17 00:00:00 2001 From: Dominik George <dominik.george@teckids.org> Date: Mon, 10 May 2021 00:54:58 +0200 Subject: [PATCH] [OAuth] Implement base for REST retrieval --- Cargo.toml | 2 +- src/nss.rs | 2 -- src/oauth.rs | 26 ++++++++++++++++++++++---- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f32095c..cc64117 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ paste = "^0.1" libc = "^0.2.0" lazy_static = "^1.3.0" oauth2 = "^4.0.0" -reqwest = "^0.11.3" +reqwest = { version = "^0.11.3", features = ["json"] } config = "^0.11.0" serde = "^1.0.125" log = "^0.4.11" diff --git a/src/nss.rs b/src/nss.rs index 8b147d2..dc66ed2 100644 --- a/src/nss.rs +++ b/src/nss.rs @@ -21,8 +21,6 @@ use config::Config; use crate::logging::setup_log; -use crate::oauth::get_access_token; - use libnss::interop::Response; use libnss::passwd::{PasswdHooks, Passwd}; diff --git a/src/oauth.rs b/src/oauth.rs index ebdd5f3..3696640 100644 --- a/src/oauth.rs +++ b/src/oauth.rs @@ -28,6 +28,7 @@ use oauth2::{ ResourceOwnerUsername, ResourceOwnerPassword, Scope, + TokenResponse, TokenUrl }; use oauth2::basic::{ @@ -36,6 +37,9 @@ use oauth2::basic::{ }; use oauth2::reqwest::http_client; +use serde::Deserialize; +use reqwest; + fn full_key(prefix: &str, key: &str) -> String { let parts = vec![prefix.to_string(), key.to_string()]; let full_key = parts.join("."); @@ -70,7 +74,7 @@ fn get_client<E: Copy>(conf: Config, prefix: &str, error_value: E) -> Result<Bas return Ok(client); } -pub fn get_access_token<E: Copy>(conf: Config, prefix: &str, error_value: E, unauth_value: E) -> Result<BasicTokenResponse, E> { +pub fn get_access_token_client<E: Copy>(conf: Config, prefix: &str, error_value: E, unauth_value: E) -> Result<BasicTokenResponse, E> { let scopes: Vec<String> = match get_optional(&conf, &full_key(prefix, "scopes")) { Some(v) => v, None => vec![] @@ -129,7 +133,21 @@ pub fn get_access_token_password<E: Copy>(conf: Config, prefix: &str, username: } } -fn do_json_request<E: Copy>(conf: Config, url: String, error_value: E, unauth_value: E) -> Result<String, E> { - let token = get_access_token(conf, "nss", error_value, unauth_value)?; - Ok("".to_string()) +fn get_data<T: for<'de> Deserialize<'de>, E>(conf: Config, token: BasicTokenResponse, endpoint: String, error_value: E) -> Result<T, E> { + let access_token = token.access_token().secret(); + + let client = reqwest::blocking::Client::new(); + let res = match client + .get(endpoint) + .header(reqwest::header::AUTHORIZATION, format!("Bearer {}", access_token)) + .send() { + Ok(r) => r, + Err(_) => return Err(error_value) + }; + + let data = match res.json() { + Ok(d) => d, + Err(_) => return Err(error_value) + }; + return Ok(data); } -- GitLab