Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ticket validation request to be synchronous #16

Merged
merged 5 commits into from
Aug 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ The format is based on [Keep a Changelog], and this project adheres to [Semantic

## [Unreleased]

No changes have been made.
### Changed
- Make ticket validation request to be synchronous ([#16](https://github.com/ristekoss/rust-sso-ui-jwt/pull/16)) ([@nayyara-airlangga])
- Rename `ReqwestError` to `RequestError` ([#16](https://github.com/ristekoss/rust-sso-ui-jwt/pull/16)) ([@nayyara-airlangga])

### Removed
- Remove `tokio` and replace `reqwest` with `http_req` ([#16](https://github.com/ristekoss/rust-sso-ui-jwt/pull/16)) ([@nayyara-airlangga])


## [v0.3.1] - 2022-07-31
Expand Down
9 changes: 1 addition & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ members = ["examples/*"]
log = ["dep:log"]

[dependencies]
http_req = "0.8.1"
jsonwebtoken = "8.1.1"
serde_json = "1.0.82"
strong-xml = "0.6.3"
Expand All @@ -31,14 +32,6 @@ features = ["serde"]
version = "0.4.17"
optional = true

[dependencies.reqwest]
version = "0.11.11"
features = ["json"]

[dependencies.serde]
version = "1.0.140"
features = ["derive"]

[dependencies.tokio]
version = "1.20.1"
features = ["rt-multi-thread", "macros"]
2 changes: 1 addition & 1 deletion examples/actix-web/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "actix-web-example"
version = "0.2.0"
version = "0.3.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
2 changes: 1 addition & 1 deletion examples/actix-web/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ struct TokenRes {

async fn login(config: web::Data<SSOJWTConfig>, query: web::Query<LoginQuery>) -> HttpResponse {
if let Some(ticket) = &query.ticket {
let res = validate_ticket(&**config, ticket).await;
let res = validate_ticket(&**config, ticket);

match res {
Ok(res) => {
Expand Down
2 changes: 1 addition & 1 deletion src/ticket/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub enum ValidateTicketError {
/// Failed ticket authentication.
AuthenticationFailed,
/// Errors regarding the validation request.
ReqwestError,
RequestError,
/// Error parsing the XML response.
XMLParsingError,
}
62 changes: 31 additions & 31 deletions src/ticket/handler.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Ticket validation handlers.

use reqwest::Client;
use http_req::{
request::{Method, Request},
uri::Uri,
};
use strong_xml::XmlRead;

use crate::SSOJWTConfig;
Expand All @@ -12,7 +15,7 @@ use super::{ServiceResponse, ValidateTicketError};
/// # Errors
///
/// - [`AuthenticationFailed`][validate_ticket_error]: Failed ticket authentication
/// - [`ReqwestError`][validate_ticket_error]: Validation request caused an error
/// - [`RequestError`][validate_ticket_error]: Validation request caused an error
/// - [`XMLParsingError`][validate_ticket_error]: Error parsing XML response
///
/// [validate_ticket_error]: crate::ticket::error::ValidateTicketError
Expand All @@ -24,56 +27,53 @@ use super::{ServiceResponse, ValidateTicketError};
/// ticket::{validate_ticket, ValidateTicketError},
/// SSOJWTConfig,
/// };
/// use tokio;
///
/// #[tokio::main]
/// async fn main() {
/// let config = SSOJWTConfig::new(
/// 120,
/// 120,
/// String::from("access secret"),
/// String::from("refresh secret"),
/// String::from("http://some-service/login"),
/// String::from("http://some-service"),
/// );
/// let config = SSOJWTConfig::new(
/// 120,
/// 120,
/// String::from("access secret"),
/// String::from("refresh secret"),
/// String::from("http://some-service/login"),
/// String::from("http://some-service"),
/// );
///
/// let response = validate_ticket(&config, "a ticket").await;
/// let status = if let Err(ValidateTicketError::AuthenticationFailed) = response {
/// "failed"
/// } else {
/// "success"
/// };
/// let response = validate_ticket(&config, "a ticket");
/// let status = if let Err(ValidateTicketError::XMLParsingError) = response {
/// "failed"
/// } else {
/// "success"
/// };
///
/// assert_eq!(status, "failed");
/// }
/// assert_eq!(status, "failed");
/// ```
pub async fn validate_ticket(
pub fn validate_ticket(
config: &SSOJWTConfig,
ticket: &str,
) -> Result<ServiceResponse, ValidateTicketError> {
let client = Client::new();
let mut writer = Vec::new();
let url = format!(
"{}/serviceValidate?ticket={}&service={}",
config.cas_url, ticket, config.service_url
);
let uri = Uri::try_from(url.as_str()).unwrap();
let mut request = Request::new(&uri);

let response = match client
.get(&url)
let request = request
.method(Method::GET)
.header("Host", "sso.ui.ac.id")
.header("User-Agent", "Node-Fetch")
.send()
.await
{
.header("User-Agent", "Node-Fetch");

match request.send(&mut writer) {
Ok(res) => res,
Err(_err) => {
#[cfg(feature = "log")]
log::error!("{}", _err);

return Err(ValidateTicketError::ReqwestError);
return Err(ValidateTicketError::RequestError);
}
};

let content = response.text().await.unwrap();
let content = String::from_utf8_lossy(&writer);

let response = match ServiceResponse::from_str(&content) {
Ok(response) => response,
Expand Down