summaryrefslogtreecommitdiff
path: root/server/src/main.rs
blob: d6fc222348f4272794b07785c4862ef0271b3915 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use serde_json::json;
use std::{collections::HashMap, env, str::FromStr, sync::Arc};
use uuid::Uuid;

use server::auth::AuthenticatedSession;
use axum::{
    extract::{Path, Query, State},
    response::{Html, Redirect},
    routing::{delete, get, post},
    Json, Router,
};
use protocol::{
    bridge_engine::TableStatePlayerView,
    card::Card,
    actions::Bid, core::Player
};
use protocol::{Table, UserInfo};
use server::server::ServerState;
use tower_cookies::{Cookie, CookieManagerLayer, Cookies};
use tower_http::trace::TraceLayer;
use tracing::{info, log::warn};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use server::{
    auth::{OauthAuthenticator, SessionId, Authenticator},
    play::advance_play,
    server::ServerContext,
    error::BridgeError,
    play::{DbJournal, Journal},
};
use sqlx::{postgres::PgPoolOptions, PgPool};

async fn create_default_authenticator(
    db_pool: &PgPool,
) -> Box<dyn Authenticator + Send + Sync> {
    Box::new(OauthAuthenticator::from_env(db_pool.clone()).await)
}

#[cfg(debug_assertions)]
async fn create_authenticator(
    db_pool: &PgPool,
) -> Box<dyn Authenticator + Send + Sync> {
    const FAKE_AUTHENTICATOR: &str = "fake";
    if std::env::var("AUTHENTICATOR").unwrap_or("".to_string())
        == FAKE_AUTHENTICATOR
    {
        Box::new(server::fake_auth::FakeAuthenticator::new())
    } else {
        create_default_authenticator(db_pool).await
    }
}

#[cfg(not(debug_assertions))]
async fn create_authenticator(
    db_pool: &PgPool,
) -> Box<dyn Authenticator + Send + Sync> {
    create_default_authenticator(db_pool).await
}

#[tokio::main]
async fn main() {
    dotenv::dotenv().ok();

    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "".into()),
        ))
        .with(tracing_subscriber::fmt::layer())
        .init();

    info!("Opening database connection");
    let db_url = env::var("DATABASE_URL").expect("DATABASE_URL");
    let db_pool: PgPool = PgPoolOptions::new()
        .max_connections(10)
        .connect(&db_url)
        .await
        .expect("db connection");

    info!("Running db migrations");
    sqlx::migrate!().run(&db_pool).await.expect("db migration");

    let mut jnl = DbJournal::new(db_pool.clone(), Uuid::new_v4());
    jnl.append(0, json!("starting server"))
        .await
        .expect("new object");

    let bind_address = env::var("BIND_ADDRESS").expect("BIND_ADDRESS");
    info!("Starting server on {}", bind_address);

    let app_url = env::var("APP_URL").expect("APP_URL");

    #[cfg(debug_assertions)]
    warn!("Running a debug build.");

    let state = Arc::new(ServerContext {
        app_url,
        authenticator: create_authenticator(&db_pool).await,
        db: db_pool,
    });

    let app = Router::new();

    #[cfg(debug_assertions)]
    let app = app.route("/api/fake_login", get(fake_login));

    let app = app
        .route("/api/user/info", get(user_info))
        .route("/api/table", post(create_table))
        .route("/api/table", delete(leave_table))
        .route("/api/table/:id", get(get_table_view))
        .route("/api/table/:id/bid", post(post_bid))
        .route("/api/table/:id/play", post(post_play))
        .route("/api/table/:id/admin/deal", post(table_new_deal))
        .route("/api/login", get(login))
        .route(server::auth::LOGIN_CALLBACK, get(login_callback))
        .layer(CookieManagerLayer::new())
        .layer(TraceLayer::new_for_http())
        .with_state(state);

    axum::Server::bind(&bind_address.parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

#[cfg(debug_assertions)]
async fn fake_login() -> Html<&'static str> {
    Html(
        r#"
      <!DOCTYPE html>
      <html lang="en">
      <body>
        <p>Log in as:</p>
        <ul>
          <li><a href="/api/login_callback?user=alice">alice</a></li>
        </ul>
      </body>
      </html>
    "#,
    )
}

async fn get_table_view(
    _session: AuthenticatedSession,
    State(state): ServerState,
    Path(id): Path<Uuid>,
) -> Result<Json<TableStatePlayerView>, BridgeError> {
    info!("Getting table state for {id:}");
    let player_position = Player::South;
    let jnl = DbJournal::new(state.db.clone(), id);
    let mut table = server::play::Table::new_or_replay(jnl).await?;
    info!("Advancing play");
    while table.game_in_progress()
        && table.game()?.current_player() != player_position
        // TODO: Support other player configurations.
        && table.game()?.current_player() != player_position.many_next(2)
    {
        advance_play(&mut table).await?;
    }
    let response = Json(TableStatePlayerView::from_table_state(
        &table.state,
        player_position,
    ));
    info!("Response: {response:#?}");
    Ok(response)
}

async fn table_new_deal(
    _session: AuthenticatedSession,
    State(state): ServerState,
    Path(id): Path<Uuid>,
) -> Result<Json<()>, BridgeError> {
    info!("Getting table state for {id:}");
    let jnl = DbJournal::new(state.db.clone(), id);
    let mut table = server::play::Table::replay(jnl).await?;
    table.new_deal().await?;
    Ok(Json(()))
}

async fn post_bid(
    _session: AuthenticatedSession,
    State(state): ServerState,
    Path(id): Path<Uuid>,
    Json(bid): Json<Bid>,
) -> Result<Json<()>, BridgeError> {
    info!("Getting table state for {id:}");
    let jnl = DbJournal::new(state.db.clone(), id);
    let mut table = server::play::Table::replay(jnl).await?;
    table.bid(bid).await?;
    Ok(Json(()))
}

async fn post_play(
    _session: AuthenticatedSession,
    State(state): ServerState,
    Path(id): Path<Uuid>,
    Json(card): Json<Card>,
) -> Result<Json<()>, BridgeError> {
    info!("Getting table state for {id:}");
    let jnl = DbJournal::new(state.db.clone(), id);
    let mut table = server::play::Table::replay(jnl).await?;
    table.play(card).await?;
    Ok(Json(()))
}

async fn leave_table(
    session: AuthenticatedSession,
    State(state): ServerState,
) -> Result<(), BridgeError> {
    sqlx::query!(
        r#"
          delete from table_players where player_id = $1
        "#,
        session.player_id
    )
    .execute(&state.db)
    .await?;
    Ok(())
}

async fn create_table(
    session: AuthenticatedSession,
    State(state): ServerState,
) -> Result<Json<Uuid>, BridgeError> {
    let txn = state.db.begin().await?;
    let table_id = sqlx::query!(
        r#"
            insert into bridge_table (id)
            values ($1)
            returning id
        "#,
        Uuid::new_v4()
    )
    .fetch_one(&state.db)
    .await?
    .id;

    sqlx::query!(
        r#"
            insert into table_players (table_id,
                                       player_id,
                                       position)
            values ($1, $2, 'south')
        "#,
        table_id,
        session.player_id
    )
    .execute(&state.db)
    .await?;

    txn.commit().await?;
    Ok(Json(table_id))
}

async fn user_info(
    session: Option<AuthenticatedSession>,
    State(state): ServerState,
) -> Result<Json<Option<UserInfo>>, BridgeError> {
    let mut session = match session {
        None => return Ok(Json(None)),
        Some(s) => s,
    };
    Ok(Json(Some(UserInfo {
        username: state.authenticator.user_info(&mut session).await?,
        table: user_table(&*state, &session).await?,
    })))
}

async fn user_table(
    state: &ServerContext,
    session: &AuthenticatedSession,
) -> Result<Option<Table>, BridgeError> {
    Ok(sqlx::query_as!(
        Table,
        r#"
        select tables.id
        from table_players players
        natural join bridge_table tables
        where player_id = $1
    "#,
        session.player_id
    )
    .fetch_optional(&state.db)
    .await?)
}

async fn login_callback(
    cookies: Cookies,
    Query(params): Query<HashMap<String, String>>,
    State(state): ServerState,
) -> Result<Redirect, BridgeError> {
    let cookie = cookies.get("user-id").unwrap();
    let user_id: SessionId = SessionId::from_str(cookie.value())?;
    let session = state
        .authenticator
        .authenticate(&state.db, user_id, params)
        .await?;
    info!("Logged in session: {session:?}");
    Ok(Redirect::temporary(&state.app_url))
}

async fn login(cookies: Cookies, State(state): ServerState) -> Redirect {
    let (user_id, auth_url) = state.authenticator.get_login_url().await;
    info!("Creating auth url for {user_id:?}");
    let user_id = serde_json::to_string(&user_id).unwrap();
    let mut cookie = Cookie::new("user-id", user_id.to_string());
    cookie.set_http_only(true);
    cookie.set_secure(true);
    cookie.set_same_site(cookie::SameSite::Lax);
    cookies.add(cookie);
    Redirect::temporary(auth_url.as_str())
}