Advertisement
Guest User

Untitled

a guest
Jul 21st, 2021
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 3.45 KB | None | 0 0
  1. let oauth = warp::path!("oauth")
  2.     .and(warp::query::<OAuthResponse>())
  3.     .and(with_pool(pool.clone()))
  4.     .and(with_settings(settings.clone()))
  5.     .map_async(|param: OAuthResponse, pool: Pool, settings: Settings| async move {
  6.         match param {
  7.             OAuthResponse::Ok {code, state} => {
  8.                 let client = reqwest::Client::new();
  9.                 let res = client.post("https://oauth2.googleapis.com/token")
  10.                     .form(&[("client_id", settings.client_id), ("client_secret", settings.client_secret), ("code", code), ("grant_type", "authorization_code".to_string()), ("redirect_uri", settings.redirect_uri)])
  11.                     .send()
  12.                     .await?;
  13.                 let token = res.json::<TokenResponse>().await?;
  14.                 let res = client.get("https://www.googleapis.com/youtube/v3/channels")
  15.                     .bearer_auth(token.access_token)
  16.                     .query(&[("part", "snippet"), ("mine", "true")])
  17.                     .send()
  18.                     .await?;
  19.                 let channel_list_response = res.json::<ChannelListResponse>().await?;
  20.                 let items = match channel_list_response {
  21.                     ChannelListResponse::Ok {items} => items,
  22.                     ChannelListResponse::Err {code, message} => bail!("Channel List Error {}: {}", code, message),
  23.                 };
  24.                 if items.is_empty() {
  25.                     bail!("No channel found");
  26.                 }
  27.                 let channel = &items[0];
  28.                 let snippet = &channel.snippet;
  29.                 let default_thumbnail = &snippet.thumbnails.default;
  30.                 let id = &channel.id;
  31.                 let title = &snippet.title;
  32.                 let icon_url = &default_thumbnail.url;
  33.                 let icon_width = default_thumbnail.height;
  34.                 let icon_height = default_thumbnail.height;
  35.                 let session: String = rand::thread_rng()
  36.                     .sample_iter(&Alphanumeric)
  37.                     .take(50) // log2(36^50) > 256
  38.                     .map(char::from)
  39.                     .collect();
  40.                 let database = pool.get().await?;
  41.                 database
  42.                     .query("INSERT INTO channels (id, session, name, iconURL, iconWidth, iconHeight) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO UPDATE SET session = $2, name = $3, iconURL = $4, iconWidth = $5, iconHeight = $6", &[&id, &session, &title, &icon_url, &icon_width, &icon_height])
  43.                     .await?;
  44.                 let response = Response::builder()
  45.                     .status(StatusCode::FOUND)
  46.                     .header("Location", settings.base_uri + "/" + &state)
  47.                     .header("Set-Cookie", "session=".to_string() + &session + "; Secure; HttpOnly; SameSite=Strict")
  48.                     .body("")?;
  49.                 Ok(response)
  50.             },
  51.             OAuthResponse::Err {error, error_message, error_uri, state} => {
  52.                 bail!("OAuth Error: {{error: {}, error_message: {:?}, error_uri: {:?}, state: {}}}", error, error_message, error_uri, state);
  53.             },
  54.         }
  55.     })
  56.     .map(|result: Result<Response<&'static str>>| result.unwrap_or_else(|error| {
  57.        eprintln!("{:?}", error);
  58.        Response::builder()
  59.            .status(StatusCode::INTERNAL_SERVER_ERROR)
  60.            .body("There was an error with authenticating your YouTube account. Please try again later.")
  61.            .unwrap()
  62.    }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement