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 bingolib::structs::OauthToken;
2use chrono::{DateTime, Utc};
3use serde::{Deserialize, Serialize};
4
5use super::DbContext;
6
7#[derive(sqlx::FromRow, Deserialize, Serialize, Debug)]
8pub struct PgOauthToken {
9 pub id: String,
10 pub user_id: i32,
11 pub service: String,
12 pub access_token: String,
13 pub expires_at: DateTime<Utc>,
14 pub refresh_token: String,
15 pub token_type: String,
16}
17
18impl Into<OauthToken> for PgOauthToken {
19 fn into(self) -> OauthToken {
20 let PgOauthToken {
21 id,
22 user_id,
23 service,
24 access_token,
25 expires_at,
26 refresh_token,
27 token_type,
28 } = self;
29 OauthToken {
30 id,
31 user_id,
32 service,
33 access_token,
34 expires_at,
35 refresh_token,
36 token_type,
37 }
38 }
39}
40
41impl From<OauthToken> for PgOauthToken {
42 fn from(value: OauthToken) -> Self {
43 let OauthToken {
44 id,
45 user_id,
46 service,
47 access_token,
48 expires_at,
49 refresh_token,
50 token_type,
51 } = value;
52 PgOauthToken {
53 id,
54 user_id,
55 service,
56 access_token,
57 expires_at,
58 refresh_token,
59 token_type,
60 }
61 }
62}
63
64impl DbContext {
65 pub async fn set_oauth_token(&mut self, token: PgOauthToken) -> Result<PgOauthToken, ()> {
66 let PgOauthToken {
67 id,
68 user_id,
69 service,
70 access_token,
71 expires_at,
72 refresh_token,
73 token_type,
74 } = token;
75
76 let pool = match self.get_pg_connection().await {
77 Some(x) => x,
78 None => return Err(()),
79 };
80
81 let tkn_check: Vec<PgOauthToken> =
82 match sqlx::query_as("SELECT * FROM oauth_token WHERE user_id = $1 AND service = $2;")
83 .bind(&user_id)
84 .bind(&service)
85 .fetch_all(pool)
86 .await
87 {
88 Ok(x) => x,
89 Err(e) => {
90 log::error!("Failed to fetch Oauth Tokens: {e}");
91 return Err(());
92 }
93 };
94
95 if tkn_check.len() == 0 {
96 match sqlx::query_as("INSERT INTO oauth_token (id, user_id, service, access_token, expires_at, refresh_token, token_type) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *;")
97 .bind(&id)
98 .bind(&user_id)
99 .bind(&service)
100 .bind(&access_token)
101 .bind(&expires_at)
102 .bind(&refresh_token)
103 .bind(&token_type)
104 .fetch_one(pool).await {
105 Ok(x) => Ok(x),
106 Err(e) => {
107 log::error!("Insert oauth_token request failed: {e}");
108 Err(())
109 }
110 }
111 } else {
112 match sqlx::query_as("UPDATE oauth_token SET id = $1, user_id = $2, service = $3, access_token = $4, expires_at = $5, refresh_token = $6, token_type = $7 WHERE user_id = $2 AND service = $3 RETURNING *;")
113 .bind(&id)
114 .bind(&user_id)
115 .bind(&service)
116 .bind(&access_token)
117 .bind(&expires_at)
118 .bind(&refresh_token)
119 .bind(&token_type)
120 .fetch_one(pool).await {
121 Ok(x) => Ok(x),
122 Err(e) => {
123 log::error!("Update oauth_token request failed: {e}");
124 Err(())
125 }
126 }
127 }
128 }
129}