Skip to content

Commit

Permalink
implement oauth2
Browse files Browse the repository at this point in the history
  • Loading branch information
alexwaeseperlman committed Mar 2, 2023
1 parent 66bfb6c commit 7fb7b77
Show file tree
Hide file tree
Showing 8 changed files with 426 additions and 19 deletions.
341 changes: 341 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ actix-session = {version = "0.7.2", features=["cookie-session"], optional=true}
getrandom = { version = "0.2", features = ["js"] }
lazy_static = "1.4.0"
r2d2 = "0.8.10"
reqwest = { version = "0.11", features = ["json"] }

[features]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
Expand Down
66 changes: 65 additions & 1 deletion src/app/login.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,74 @@
use super::super::app_config::*;
use cfg_if::cfg_if;
use leptos::{ev::MouseEvent, *};
use leptos_meta::*;
use leptos_router::*;
use leptos_server::*;
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::app_config::TENANT_ID;

pub fn microsoft_login_url() -> String {
format!("https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:3000%2Fteam&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Femail", CLIENT_ID)
format!("https://login.microsoftonline.com/{}/oauth2/v2.0/authorize?client_id={}&response_type=code&redirect_uri={}&response_mode=query&scope=User.Read", "common", CLIENT_ID, REDIRECT_URI)
}

#[derive(Serialize, Deserialize, Clone)]
pub struct AzureMeResponse {
displayName: String,
givenName: String,
mail: String,
userPrincipalName: String,
id: String,
}

cfg_if! {
if #[cfg(feature = "ssr")] {
use actix_web::{get, HttpResponse, HttpRequest, web};
use crate::get_azure_secret;

use actix_session::Session;

#[derive(Deserialize)]
pub struct MicrosoftLoginCode {
code: Option<String>,
}

// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
#[derive(Deserialize)]
pub struct AzureAuthTokenResopnse {
access_token: Option<String>,
error: Option<String>
}

// By the end of this method, if given a valid authorization code, the email address field in the session should be set
pub async fn handle_login(req: web::Query<MicrosoftLoginCode>, session: Session) -> Result<HttpResponse, Box<dyn std::error::Error>> {
let code = req.code.clone().unwrap_or_default();
// TODO: Is it bad to make a new client for every login?
let client = reqwest::Client::new();
let secret = get_azure_secret();

let response: AzureAuthTokenResopnse = client.post(format!("https://login.microsoftonline.com/{}/oauth2/v2.0/token", "common")).body(
format!("code={}&client_id={}&redirect_uri={}&grant_type=authorization_code&client_secret={}",
code,
CLIENT_ID,
REDIRECT_URI,
secret
)
).send().await?.json().await?;
if response.access_token.is_some() {
let me: AzureMeResponse = client.get("https://graph.microsoft.com/v1.0/me")
.header("Content-Type", "application/json")
.header("Authorization", response.access_token.unwrap())
.send().await?.json().await?;
session.insert("me", me.clone())?;
Ok(HttpResponse::Found().append_header(("Location", "/team")).finish())
}
else {
Ok(HttpResponse::Found().append_header(("Location", "/login")).finish())
}
//Ok(HttpResponse::Ok().body(response.access_token.unwrap_or(response.error.unwrap_or("wtf".to_string()))))
}
}
}
9 changes: 4 additions & 5 deletions src/app/pages/team.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@ pub async fn get_team(cx: Scope) -> Result<Option<i32>, ServerFnError> {
use crate::DB_CONNECTION;
use diesel::*;
let session = crate::get_session(cx);
teams
.limit(5)
.load::<Team>(&mut (*DB_CONNECTION).get().unwrap())
.expect("Error loading teams");
log!("Called");
/*teams
.limit(5)
.load::<Team>(&mut (*DB_CONNECTION).get().unwrap())
.expect("Error loading teams");*/
Ok(Some(1))
}

Expand Down
5 changes: 4 additions & 1 deletion src/app_config.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
use cfg_if::cfg_if;
pub const TEAM_SIZE: i32 = 5;
pub const CLIENT_ID: &str = "42cb7f3f-e8fc-4e59-9bb6-2422f6dadbb0";
pub const CLIENT_ID: &str = "cc6185f1-7e94-4314-a79e-7d72d8fd68fc";
pub const REDIRECT_URI: &str = "http%3A%2F%2Flocalhost:3000%2Fapi%2Flogin";
pub const TENANT_ID: &str = "f8cdef31-a31e-4b4a-93e4-5f571e91255a";
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ pub fn get_session(cx: leptos::Scope) -> Option<actix_session::Session> {
}
}

pub fn get_azure_secret() -> String {
use std::env;
env::var("AZURE_SECRET").expect("AZURE_SECRET must be set in .env")
}

}

}
2 changes: 2 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use actix_session::{Session, SessionMiddleware, storage::CookieSessionStore};
use dotenvy::dotenv;
use std::env;
use actix_web::*;
use pokerbots::app::login::handle_login;

fn get_secret_key() -> cookie::Key {
let key = env::var("SECRET_KEY").expect("SECRET_KEY must be set in .env");
Expand Down Expand Up @@ -36,6 +37,7 @@ async fn main() -> std::io::Result<()> {
let site_root = &leptos_options.site_root;

App::new()
.route("/api/login", web::get().to(handle_login))
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
.wrap(
SessionMiddleware::new(CookieSessionStore::default(), get_secret_key())
Expand Down
16 changes: 4 additions & 12 deletions style/output.css
Original file line number Diff line number Diff line change
Expand Up @@ -517,20 +517,16 @@ video {
position: static;
}

.mt-auto {
margin-top: auto;
.mt-2 {
margin-top: 0.5rem;
}

.mt-4 {
margin-top: 1rem;
}

.mt-1 {
margin-top: 0.25rem;
}

.mt-2 {
margin-top: 0.5rem;
.mt-auto {
margin-top: auto;
}

.flex {
Expand Down Expand Up @@ -574,10 +570,6 @@ video {
gap: 1rem;
}

.gap-2 {
gap: 0.5rem;
}

.bg-red-600 {
--tw-bg-opacity: 1;
background-color: rgb(220 38 38 / var(--tw-bg-opacity));
Expand Down

0 comments on commit 7fb7b77

Please sign in to comment.