Two teams try and fill in any horizontal, vertical, or diagonal line on a bingo board by playing maps on osu!
osu.bingo
osu
1use super::DbContext;
2
3use rand::Rng;
4use redis::Commands;
5use serde::{Deserialize, Serialize};
6
7#[derive(Deserialize, Serialize)]
8pub struct OauthState {
9 pub state_id: String,
10 pub from_url: String,
11}
12
13const STATE_CHAR_LENGTH: usize = 4;
14const STATE_EXPIRATION_SECONDS: u64 = 10 * 60;
15const SESSION_FOLDER: &'static str = "bingo:sessions";
16
17impl DbContext {
18 pub async fn set_oauth_state(&mut self, from_url: &String) -> Option<OauthState> {
19 let mut conn = match self.get_redis_connection().await {
20 Some(x) => x,
21 None => return None,
22 };
23 let state_id: String = rand::rng()
24 .sample_iter(&rand::distr::Alphabetic)
25 .take(STATE_CHAR_LENGTH)
26 .map(char::from)
27 .collect();
28 let state = OauthState {
29 state_id: state_id.to_uppercase(),
30 from_url: from_url.clone(),
31 };
32
33 let data = match serde_json::to_string(&state) {
34 Ok(x) => x,
35 Err(e) => {
36 log::error!("Given state cannot be serialized to a string: {e}");
37 return None;
38 }
39 };
40
41 let _: () = match conn.set_ex(
42 format!("{SESSION_FOLDER}:{}", state.state_id),
43 data,
44 STATE_EXPIRATION_SECONDS,
45 ) {
46 Ok(x) => x,
47 Err(e) => {
48 log::error!("{e}");
49 return None;
50 }
51 };
52
53 Some(state)
54 }
55 pub async fn fetch_oauth_state(&mut self, id: &str) -> Option<OauthState> {
56 let mut conn = match self.get_redis_connection().await {
57 Some(x) => x,
58 None => return None,
59 };
60
61 let data: String = match conn.get(format!("{SESSION_FOLDER}:{}", id)) {
62 Ok(x) => x,
63 Err(e) => {
64 log::error!("{e}");
65 return None;
66 }
67 };
68
69 let state: OauthState = match serde_json::from_str(&data) {
70 Ok(x) => x,
71 Err(e) => {
72 log::error!("Failed to parse OauthState: {e}");
73 return None;
74 }
75 };
76
77 let _: () = match conn.del(format!("{SESSION_FOLDER}:{}", id)) {
78 Ok(x) => x,
79 Err(e) => {
80 log::warn!("Failed to delete state: {e}")
81 }
82 };
83
84 Some(state)
85 }
86}