Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let oauth = warp::path!("oauth")
- .and(warp::query::<OAuthResponse>())
- .and(with_pool(pool.clone()))
- .and(with_settings(settings.clone()))
- .map_async(|param: OAuthResponse, pool: Pool, settings: Settings| async move {
- match param {
- OAuthResponse::Ok {code, state} => {
- let client = reqwest::Client::new();
- let res = client.post("https://oauth2.googleapis.com/token")
- .form(&[("client_id", settings.client_id), ("client_secret", settings.client_secret), ("code", code), ("grant_type", "authorization_code".to_string()), ("redirect_uri", settings.redirect_uri)])
- .send()
- .await?;
- let token = res.json::<TokenResponse>().await?;
- let res = client.get("https://www.googleapis.com/youtube/v3/channels")
- .bearer_auth(token.access_token)
- .query(&[("part", "snippet"), ("mine", "true")])
- .send()
- .await?;
- let channel_list_response = res.json::<ChannelListResponse>().await?;
- let items = match channel_list_response {
- ChannelListResponse::Ok {items} => items,
- ChannelListResponse::Err {code, message} => bail!("Channel List Error {}: {}", code, message),
- };
- if items.is_empty() {
- bail!("No channel found");
- }
- let channel = &items[0];
- let snippet = &channel.snippet;
- let default_thumbnail = &snippet.thumbnails.default;
- let id = &channel.id;
- let title = &snippet.title;
- let icon_url = &default_thumbnail.url;
- let icon_width = default_thumbnail.height;
- let icon_height = default_thumbnail.height;
- let session: String = rand::thread_rng()
- .sample_iter(&Alphanumeric)
- .take(50) // log2(36^50) > 256
- .map(char::from)
- .collect();
- let database = pool.get().await?;
- database
- .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])
- .await?;
- let response = Response::builder()
- .status(StatusCode::FOUND)
- .header("Location", settings.base_uri + "/" + &state)
- .header("Set-Cookie", "session=".to_string() + &session + "; Secure; HttpOnly; SameSite=Strict")
- .body("")?;
- Ok(response)
- },
- OAuthResponse::Err {error, error_message, error_uri, state} => {
- bail!("OAuth Error: {{error: {}, error_message: {:?}, error_uri: {:?}, state: {}}}", error, error_message, error_uri, state);
- },
- }
- })
- .map(|result: Result<Response<&'static str>>| result.unwrap_or_else(|error| {
- eprintln!("{:?}", error);
- Response::builder()
- .status(StatusCode::INTERNAL_SERVER_ERROR)
- .body("There was an error with authenticating your YouTube account. Please try again later.")
- .unwrap()
- }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement