Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Wulf committed Sep 29, 2023
1 parent f34c863 commit f96da36
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 81 deletions.
4 changes: 2 additions & 2 deletions create-rust-app/src/auth/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,14 +332,14 @@ pub fn create_user_session(
&access_token_claims,
&EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
)
.unwrap();
.unwrap();

let refresh_token = encode(
&Header::default(),
&refresh_token_claims,
&EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
)
.unwrap();
.unwrap();

let user_session = UserSession::create(
db,
Expand Down
90 changes: 50 additions & 40 deletions create-rust-app/src/auth/endpoints/service_actixweb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::auth::{
AuthMessageResponse, AuthTokenResponse, JwtSecurityAddon, UserSessionJson, UserSessionResponse,
};
use actix_http::StatusCode;
use actix_web::{cookie::{Cookie, SameSite}};
use actix_web::cookie::{Cookie, SameSite};
use actix_web::{delete, get, post, web, Error as AWError, Result};
use actix_web::{
web::{Data, Json, Path, Query},
Expand Down Expand Up @@ -182,7 +182,13 @@ async fn oidc_login_redirect(
) -> Result<HttpResponse, AWError> {
use actix_web::http::header::{HeaderValue, LOCATION};

let result = crate::auth::oidc::controller::oidc_login_url(&db, app_config.as_ref(), auth_config.as_ref(), provider.to_string()).await;
let result = crate::auth::oidc::controller::oidc_login_url(
&db,
app_config.as_ref(),
auth_config.as_ref(),
provider.to_string(),
)
.await;

if result.is_err() {
return Ok(HttpResponse::InternalServerError().finish());
Expand All @@ -193,11 +199,13 @@ async fn oidc_login_redirect(
match result {
Some(url) => {
let mut response = HttpResponse::SeeOther().body(());
response.headers_mut().append(LOCATION, HeaderValue::from_str(url.as_str()).unwrap());
response
.headers_mut()
.append(LOCATION, HeaderValue::from_str(url.as_str()).unwrap());

Ok(response)
},
None => Ok(HttpResponse::NotImplemented().finish())
}
None => Ok(HttpResponse::NotImplemented().finish()),
}
}

Expand All @@ -216,21 +224,25 @@ async fn oidc_login(
app_config: Data<AppConfig>,
auth_config: Data<AuthConfig>,
path_params: Path<String>,
query_params: Query<OIDCLoginQueryParams>
query_params: Query<OIDCLoginQueryParams>,
) -> HttpResponse {
use actix_web::http::header::{HeaderValue, LOCATION};
let provider_name = path_params.to_string();

let provider = auth_config.oidc_providers
let provider = auth_config
.oidc_providers
.iter()
.find(|p| p.name.eq(&provider_name));

if provider.is_none() {
return HttpResponse::InternalServerError().json(json!({
"success": false,
"message": "Provider not configured",
"provider": &provider_name
}).to_string());
return HttpResponse::InternalServerError().json(
json!({
"success": false,
"message": "Provider not configured",
"provider": &provider_name
})
.to_string(),
);
}

let provider = provider.unwrap();
Expand All @@ -247,44 +259,42 @@ async fn oidc_login(
provider_name,
query_param_code,
query_param_error,
query_param_state
).await;
query_param_state,
)
.await;

let mut response = HttpResponse::SeeOther().body(());

match resp {
Ok((access_token, refresh_token)) => {
response.headers_mut().append(
LOCATION,
HeaderValue::from_str(
&format!(
"{}?access_token={}",
provider.success_uri,
access_token
)
).expect("Invalid URL")
HeaderValue::from_str(&format!(
"{}?access_token={}",
provider.success_uri, access_token
))
.expect("Invalid URL"),
);

response.add_cookie(
&Cookie::build(COOKIE_NAME, refresh_token)
.secure(true)
.http_only(true)
.same_site(SameSite::Strict)
.path("/")
.finish()
).expect("Could not add refresh_token cookie");
},
Err((status_code, message)) => {
response.headers_mut().append(
LOCATION,
HeaderValue::from_str(&format!(
"{}?status_code={}&message={}",
provider.error_uri,
status_code,
message
)).expect("Invalid URL"),
)
response
.add_cookie(
&Cookie::build(COOKIE_NAME, refresh_token)
.secure(true)
.http_only(true)
.same_site(SameSite::Strict)
.path("/")
.finish(),
)
.expect("Could not add refresh_token cookie");
}
Err((status_code, message)) => response.headers_mut().append(
LOCATION,
HeaderValue::from_str(&format!(
"{}?status_code={}&message={}",
provider.error_uri, status_code, message
))
.expect("Invalid URL"),
),
}

response
Expand Down
2 changes: 1 addition & 1 deletion create-rust-app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,4 @@ pub struct AuthTokenResponse {
pub struct AuthConfig {
#[cfg(feature = "plugin_auth-oidc")]
pub oidc_providers: Vec<crate::auth::oidc::OIDCProvider>,
}
}
12 changes: 6 additions & 6 deletions create-rust-app/src/auth/oidc/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ async fn create_oidc_client(provider: &OIDCProvider, app_url: String) -> Result<
IssuerUrl::new(provider.clone().issuer_url)?,
async_http_client,
)
.await?;
.await?;

Ok(CoreClient::from_provider_metadata(
provider_metadata,
ClientId::new(provider.clone().client_id),
Some(ClientSecret::new(provider.clone().client_secret)),
)
.set_redirect_uri(RedirectUrl::new(provider.redirect_uri(app_url))?))
.set_redirect_uri(RedirectUrl::new(provider.redirect_uri(app_url))?))
}

pub async fn oidc_login_url(
Expand Down Expand Up @@ -285,15 +285,15 @@ pub async fn oauth_login(
updated_at: None,
},
)
.unwrap();
.unwrap();

let (access_token, refresh_token) = create_user_session(
db,
Some(format!("Oauth2 - {}", &provider_name)),
None,
user.id,
)
.map_err(|error| (error.0, error.1.to_string()))?;
.map_err(|error| (error.0, error.1.to_string()))?;

return Ok((access_token, refresh_token));
}
Expand Down Expand Up @@ -361,13 +361,13 @@ pub async fn oauth_login(
updated_at: None,
},
)
.unwrap();
.unwrap();

Ok(create_user_session(
db,
Some(format!("Oauth2 - {}", &provider_name)),
None,
new_user.id,
)
.map_err(|error| (error.0, error.1.to_string())))?
.map_err(|error| (error.0, error.1.to_string())))?
}
5 changes: 4 additions & 1 deletion create-rust-app/src/auth/oidc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ type ProviderFactory = fn(ClientId, ClientSecret, SuccessURI, ErrorURI) -> OIDCP

impl OIDCProvider {
pub const GOOGLE: ProviderFactory =
|client_id: ClientId, client_secret: ClientSecret, success_uri: SuccessURI, error_uri: ErrorURI| OIDCProvider {
|client_id: ClientId,
client_secret: ClientSecret,
success_uri: SuccessURI,
error_uri: ErrorURI| OIDCProvider {
name: "google".to_string(),
scope: vec!["email".to_string()],
issuer_url: "https://accounts.google.com".to_string(),
Expand Down
20 changes: 10 additions & 10 deletions create-rust-app/src/auth/oidc/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ type Connection = crate::Connection;

#[tsync::tsync]
#[derive(
Debug,
Serialize,
Deserialize,
Clone,
Queryable,
Insertable,
AsChangeset,
Identifiable,
Associations,
Selectable,
Debug,
Serialize,
Deserialize,
Clone,
Queryable,
Insertable,
AsChangeset,
Identifiable,
Associations,
Selectable,
)]
#[diesel(table_name=user_oauth2_links, primary_key(id), belongs_to(User, foreign_key=user_id))]
pub struct UserOauth2Link {
Expand Down
2 changes: 1 addition & 1 deletion create-rust-app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub use mailer::{DefaultMailTemplates, EmailTemplates};
#[derive(Clone)]
pub struct AppConfig {
// where the app is hosted; for example: create-rust-app.dev:3000
pub app_url: String
pub app_url: String,
}

#[derive(Clone)]
Expand Down
Loading

0 comments on commit f96da36

Please sign in to comment.