web3-proxy/web3_proxy/src/frontend/users.rs

712 lines
24 KiB
Rust
Raw Normal View History

2022-10-18 00:47:58 +03:00
//! Handle registration, logins, and managing account data.
2022-07-14 00:49:57 +03:00
2022-09-24 08:53:45 +03:00
use super::authorization::{login_is_authorized, UserKey};
use super::errors::FrontendResult;
2022-09-24 08:53:45 +03:00
use crate::app::Web3ProxyApp;
2022-10-20 02:02:34 +03:00
use crate::user_stats::{get_aggregate_rpc_stats, get_detailed_stats};
2022-08-27 08:42:25 +03:00
use anyhow::Context;
2022-08-11 04:53:27 +03:00
use axum::{
2022-08-21 11:18:57 +03:00
extract::{Path, Query},
headers::{authorization::Bearer, Authorization},
response::IntoResponse,
Extension, Json, TypedHeader,
2022-08-11 04:53:27 +03:00
};
2022-08-04 04:10:27 +03:00
use axum_client_ip::ClientIp;
2022-08-16 22:29:00 +03:00
use axum_macros::debug_handler;
use chrono::NaiveDateTime;
use entities::{user, user_keys};
2022-08-04 04:10:27 +03:00
use ethers::{prelude::Address, types::Bytes};
2022-08-19 23:18:12 +03:00
use hashbrown::HashMap;
2022-09-15 20:57:24 +03:00
use http::StatusCode;
use redis_rate_limiter::redis::AsyncCommands;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, TransactionTrait};
2022-08-27 08:42:25 +03:00
use serde::{Deserialize, Serialize};
use siwe::{Message, VerificationOpts};
2022-08-27 05:13:36 +03:00
use std::ops::Add;
2022-08-04 04:10:27 +03:00
use std::sync::Arc;
use time::{Duration, OffsetDateTime};
2022-10-20 07:44:33 +03:00
use tracing::{info, warn};
2022-08-21 11:18:57 +03:00
use ulid::Ulid;
2022-10-18 00:47:58 +03:00
/// `GET /user/login/:user_address` or `GET /user/login/:user_address/:message_eip` -- Start the "Sign In with Ethereum" (siwe) login flow.
///
/// `message_eip`s accepted:
/// - eip191_bytes
/// - eip191_hash
/// - eip4361 (default)
///
/// Coming soon: eip1271
///
/// This is the initial entrypoint for logging in. Take the response from this endpoint and give it to your user's wallet for singing. POST the response to `/user/login`.
///
/// Rate limited by IP address.
2022-08-16 22:29:00 +03:00
#[debug_handler]
2022-10-18 00:47:58 +03:00
pub async fn user_login_get(
Extension(app): Extension<Arc<Web3ProxyApp>>,
2022-08-17 00:43:39 +03:00
ClientIp(ip): ClientIp,
// TODO: what does axum's error handling look like if the path fails to parse?
// TODO: allow ENS names here?
Path(mut params): Path<HashMap<String, String>>,
2022-08-17 00:43:39 +03:00
) -> FrontendResult {
2022-09-28 06:35:55 +03:00
// give these named variables so that we drop them at the very end of this function
let (_, _semaphore) = login_is_authorized(&app, ip).await?;
2022-08-17 00:43:39 +03:00
// at first i thought about checking that user_address is in our db
2022-08-21 11:18:57 +03:00
// but theres no need to separate the registration and login flows
2022-08-17 00:43:39 +03:00
// its a better UX to just click "login with ethereum" and have the account created if it doesn't exist
// we can prompt for an email and and payment after they log in
2022-08-21 11:18:57 +03:00
// create a message and save it in redis
// TODO: how many seconds? get from config?
// TODO: while developing, we put a giant number here
let expire_seconds: usize = 28800;
2022-08-21 11:18:57 +03:00
let nonce = Ulid::new();
let issued_at = OffsetDateTime::now_utc();
let expiration_time = issued_at.add(Duration::new(expire_seconds as i64, 0));
let user_address: Address = params
.remove("user_address")
// TODO: map_err so this becomes a 500. routing must be bad
.context("impossible")?
.parse()
// TODO: map_err so this becomes a 401
.context("bad input")?;
// TODO: get most of these from the app config
let message = Message {
// TODO: should domain be llamanodes, or llamarpc, or the subdomain of llamarpc?
domain: "staging.llamanodes.com".parse().unwrap(),
address: user_address.to_fixed_bytes(),
statement: Some("🦙🦙🦙🦙🦙".to_string()),
uri: "https://staging.llamanodes.com/".parse().unwrap(),
version: siwe::Version::V1,
chain_id: 1,
expiration_time: Some(expiration_time.into()),
issued_at: issued_at.into(),
nonce: nonce.to_string(),
not_before: None,
request_id: None,
resources: vec![],
};
let session_key = format!("pending:{}", nonce);
2022-10-19 03:56:57 +03:00
// TODO: if no redis server, store in local cache? at least give a better error. right now this seems to be a 502
2022-08-21 11:18:57 +03:00
// the address isn't enough. we need to save the actual message so we can read the nonce
// TODO: what message format is the most efficient to store in redis? probably eip191_bytes
// we add 1 to expire_seconds just to be sure redis has the key for the full expiration_time
// TODO: store a maximum number of attempted logins? anyone can request so we don't want to allow DOS attacks
app.redis_conn()
.await?
.set_ex(session_key, message.to_string(), expire_seconds + 1)
.await?;
2022-08-19 23:18:12 +03:00
// there are multiple ways to sign messages and not all wallets support them
2022-10-18 00:47:58 +03:00
// TODO: default message eip from config?
let message_eip = params
.remove("message_eip")
.unwrap_or_else(|| "eip4361".to_string());
2022-08-19 23:18:12 +03:00
let message: String = match message_eip.as_str() {
"eip191_bytes" => Bytes::from(message.eip191_bytes().unwrap()).to_string(),
2022-08-19 23:18:12 +03:00
"eip191_hash" => Bytes::from(&message.eip191_hash().unwrap()).to_string(),
2022-09-14 09:18:13 +03:00
"eip4361" => message.to_string(),
2022-09-10 03:58:33 +03:00
_ => {
2022-10-19 03:56:57 +03:00
// TODO: custom error that is handled a 401
2022-09-10 03:58:33 +03:00
return Err(anyhow::anyhow!("invalid message eip given").into());
}
2022-08-19 23:18:12 +03:00
};
Ok(message.into_response())
2022-08-16 22:29:00 +03:00
}
2022-08-04 02:17:02 +03:00
2022-10-18 00:47:58 +03:00
/// Query params for our `post_login` handler.
2022-08-21 11:18:57 +03:00
#[derive(Debug, Deserialize)]
pub struct PostLoginQuery {
2022-10-18 00:47:58 +03:00
/// While we are in alpha/beta, we require users to supply an invite code.
/// The invite code (if any) is set in the application's config.
/// This may eventually provide some sort of referral bonus.
pub invite_code: Option<String>,
2022-08-21 11:18:57 +03:00
}
/// JSON body to our `post_login` handler.
2022-10-18 00:47:58 +03:00
/// Currently only siwe logins that send an address, msg, and sig are allowed.
2022-10-19 03:56:57 +03:00
/// Email/password and other login methods are planned.
2022-08-21 11:18:57 +03:00
#[derive(Deserialize)]
pub struct PostLogin {
2022-10-18 00:47:58 +03:00
pub address: Address,
pub msg: String,
pub sig: Bytes,
2022-08-21 12:39:38 +03:00
// TODO: do we care about these? we should probably check the version is something we expect
// version: String,
// signer: String,
2022-08-21 11:18:57 +03:00
}
2022-10-18 00:47:58 +03:00
/// Successful logins receive a bearer_token and all of the user's api keys.
2022-08-27 08:42:25 +03:00
#[derive(Serialize)]
pub struct PostLoginResponse {
2022-10-18 00:47:58 +03:00
/// Used for authenticating additonal requests.
2022-08-27 08:42:25 +03:00
bearer_token: Ulid,
2022-10-18 00:47:58 +03:00
/// Used for authenticating with the RPC endpoints.
2022-09-24 08:53:45 +03:00
api_keys: Vec<UserKey>,
2022-10-19 03:56:57 +03:00
// TODO: what else?
2022-08-27 08:42:25 +03:00
}
2022-10-18 00:47:58 +03:00
/// `POST /user/login` - Register or login by posting a signed "siwe" message.
/// It is recommended to save the returned bearer token in a cookie.
/// The bearer token can be used to authenticate other requests, such as getting the user's stats or modifying the user's profile.
#[debug_handler]
2022-10-18 00:47:58 +03:00
pub async fn user_login_post(
2022-08-21 11:18:57 +03:00
Extension(app): Extension<Arc<Web3ProxyApp>>,
ClientIp(ip): ClientIp,
2022-08-21 11:18:57 +03:00
Json(payload): Json<PostLogin>,
Query(query): Query<PostLoginQuery>,
2022-08-21 12:39:38 +03:00
) -> FrontendResult {
2022-09-28 06:35:55 +03:00
// give these named variables so that we drop them at the very end of this function
let (_, _semaphore) = login_is_authorized(&app, ip).await?;
2022-08-04 04:10:27 +03:00
2022-08-21 11:18:57 +03:00
if let Some(invite_code) = &app.config.invite_code {
// we don't do per-user referral codes because we shouldn't collect what we don't need.
// we don't need to build a social graph between addresses like that.
if query.invite_code.as_ref() != Some(invite_code) {
todo!("if address is already registered, allow login! else, error")
}
2022-08-04 04:10:27 +03:00
}
2022-08-21 11:18:57 +03:00
// we can't trust that they didn't tamper with the message in some way
let their_msg: siwe::Message = payload.msg.parse().unwrap();
let their_sig: [u8; 65] = payload.sig.as_ref().try_into().unwrap();
// fetch the message we gave them from our redis
2022-08-17 02:03:50 +03:00
// TODO: use getdel
let our_msg: String = app.redis_conn().await?.get(&their_msg.nonce).await?;
2022-08-17 02:03:50 +03:00
2022-08-21 11:18:57 +03:00
let our_msg: siwe::Message = our_msg.parse().unwrap();
2022-08-17 02:03:50 +03:00
let verify_config = VerificationOpts {
domain: Some(our_msg.domain),
nonce: Some(our_msg.nonce),
..Default::default()
};
2022-08-21 11:18:57 +03:00
// check the domain and a nonce. let timestamp be automatic
if let Err(e) = their_msg.verify(&their_sig, &verify_config).await {
2022-08-04 04:10:27 +03:00
// message cannot be correctly authenticated
todo!("proper error message: {}", e)
}
2022-08-27 08:42:25 +03:00
let bearer_token = Ulid::new();
2022-09-24 07:31:06 +03:00
let db = app.db_conn().context("Getting database connection")?;
2022-07-14 00:49:57 +03:00
2022-08-27 08:42:25 +03:00
// TODO: limit columns or load whole user?
let u = user::Entity::find()
.filter(user::Column::Address.eq(our_msg.address.as_ref()))
2022-10-19 03:56:57 +03:00
.one(&db)
2022-08-27 08:42:25 +03:00
.await
.unwrap();
2022-08-04 02:17:02 +03:00
let (u, _uks, response) = match u {
2022-08-27 08:42:25 +03:00
None => {
let txn = db.begin().await?;
2022-08-04 02:17:02 +03:00
2022-08-27 08:42:25 +03:00
// the only thing we need from them is an address
// everything else is optional
let u = user::ActiveModel {
address: sea_orm::Set(payload.address.to_fixed_bytes().into()),
..Default::default()
};
2022-08-17 02:03:50 +03:00
2022-08-27 08:42:25 +03:00
let u = u.insert(&txn).await?;
2022-08-17 02:03:50 +03:00
2022-09-24 08:53:45 +03:00
let user_key = UserKey::new();
2022-08-27 08:42:25 +03:00
let uk = user_keys::ActiveModel {
user_id: sea_orm::Set(u.id),
2022-09-24 08:53:45 +03:00
api_key: sea_orm::Set(user_key.into()),
2022-10-19 02:27:33 +03:00
requests_per_minute: sea_orm::Set(app.config.default_user_requests_per_minute),
2022-08-27 08:42:25 +03:00
..Default::default()
};
2022-08-21 11:18:57 +03:00
2022-08-27 08:42:25 +03:00
// TODO: if this fails, revert adding the user, too
let uk = uk
.insert(&txn)
.await
.context("Failed saving new user key")?;
2022-08-17 02:03:50 +03:00
let uks = vec![uk];
2022-08-27 08:42:25 +03:00
txn.commit().await?;
2022-08-16 20:47:04 +03:00
2022-08-27 08:42:25 +03:00
let response_json = PostLoginResponse {
bearer_token,
2022-09-24 08:53:45 +03:00
api_keys: uks.iter().map(|uk| uk.api_key.into()).collect(),
2022-08-27 08:42:25 +03:00
};
let response = (StatusCode::CREATED, Json(response_json)).into_response();
(u, uks, response)
2022-08-27 08:42:25 +03:00
}
Some(u) => {
// the user is already registered
let uks = user_keys::Entity::find()
2022-08-27 08:42:25 +03:00
.filter(user_keys::Column::UserId.eq(u.id))
2022-10-19 03:56:57 +03:00
.all(&db)
2022-08-27 08:42:25 +03:00
.await
.context("failed loading user's key")?;
2022-08-27 08:42:25 +03:00
let response_json = PostLoginResponse {
bearer_token,
2022-09-24 08:53:45 +03:00
api_keys: uks.iter().map(|uk| uk.api_key.into()).collect(),
2022-08-27 08:42:25 +03:00
};
let response = (StatusCode::OK, Json(response_json)).into_response();
(u, uks, response)
2022-08-27 08:42:25 +03:00
}
2022-08-23 21:51:42 +03:00
};
// add bearer to redis
2022-08-27 08:42:25 +03:00
let mut redis_conn = app.redis_conn().await?;
let bearer_redis_key = format!("bearer:{}", bearer_token);
2022-09-03 22:43:19 +03:00
// expire in 4 weeks
// TODO: get expiration time from app config
// TODO: do we use this?
redis_conn
.set_ex(bearer_redis_key, u.id.to_string(), 2_419_200)
.await?;
2022-08-23 21:51:42 +03:00
Ok(response)
2022-07-14 00:49:57 +03:00
}
2022-10-18 00:47:58 +03:00
/// `POST /user/logout` - Forget the bearer token in the `Authentication` header.
#[debug_handler]
2022-10-18 00:47:58 +03:00
pub async fn user_logout_post(
Extension(app): Extension<Arc<Web3ProxyApp>>,
TypedHeader(Authorization(bearer)): TypedHeader<Authorization<Bearer>>,
) -> FrontendResult {
2022-09-24 07:31:06 +03:00
let mut redis_conn = app.redis_conn().await?;
// TODO: i don't like this. move this to a helper function so it is less fragile
let bearer_cache_key = format!("bearer:{}", bearer.token());
redis_conn.del(bearer_cache_key).await?;
// TODO: what should the response be? probably json something
Ok("goodbye".into_response())
}
2022-08-21 11:18:57 +03:00
/// the JSON input to the `post_user` handler
2022-09-05 04:52:59 +03:00
/// This handles updating
2022-07-14 00:49:57 +03:00
#[derive(Deserialize)]
2022-08-21 11:18:57 +03:00
pub struct PostUser {
2022-08-23 22:08:47 +03:00
primary_address: Address,
2022-08-21 11:18:57 +03:00
// TODO: make sure the email address is valid. probably have a "verified" column in the database
2022-07-14 00:49:57 +03:00
email: Option<String>,
2022-08-21 11:18:57 +03:00
// TODO: make them sign this JSON? cookie in session id is hard because its on a different domain
}
2022-10-18 00:47:58 +03:00
/// `POST /user/profile` -- modify the account connected to the bearer token in the `Authentication` header.
2022-08-21 11:18:57 +03:00
#[debug_handler]
2022-10-18 00:47:58 +03:00
pub async fn user_profile_post(
TypedHeader(Authorization(bearer_token)): TypedHeader<Authorization<Bearer>>,
2022-08-23 21:51:42 +03:00
ClientIp(ip): ClientIp,
Extension(app): Extension<Arc<Web3ProxyApp>>,
Json(payload): Json<PostUser>,
2022-08-21 11:18:57 +03:00
) -> FrontendResult {
2022-09-28 06:35:55 +03:00
// give these named variables so that we drop them at the very end of this function
let (_, _semaphore) = login_is_authorized(&app, ip).await?;
2022-08-21 11:18:57 +03:00
2022-10-20 00:34:05 +03:00
let user = ProtectedAction::PostUser(payload.primary_address)
.verify(app.as_ref(), bearer_token)
.await?;
2022-09-05 04:52:59 +03:00
let mut user: user::ActiveModel = user.into();
// TODO: rate limit by user, too?
2022-09-28 06:35:55 +03:00
// TODO: allow changing the primary address, too. require a message from the new address to finish the change
2022-09-05 04:52:59 +03:00
if let Some(x) = payload.email {
2022-09-28 06:35:55 +03:00
// TODO: only Set if no change
2022-09-05 04:52:59 +03:00
if x.is_empty() {
user.email = sea_orm::Set(None);
} else {
user.email = sea_orm::Set(Some(x));
}
}
2022-09-24 07:31:06 +03:00
let db = app.db_conn().context("Getting database connection")?;
2022-09-05 04:52:59 +03:00
2022-10-19 03:56:57 +03:00
user.save(&db).await?;
2022-09-05 04:52:59 +03:00
2022-08-23 21:51:42 +03:00
todo!("finish post_user");
2022-07-14 00:49:57 +03:00
}
2022-08-23 22:08:47 +03:00
2022-10-18 00:47:58 +03:00
/// `GET /user/balance` -- Use a bearer token to get the user's balance and spend.
///
/// - show balance in USD
/// - show deposits history (currency, amounts, transaction id)
///
/// TODO: one key per request? maybe /user/balance/:api_key?
/// TODO: this will change as we add better support for secondary users.
#[debug_handler]
pub async fn user_balance_get(
TypedHeader(Authorization(bearer_token)): TypedHeader<Authorization<Bearer>>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
) -> FrontendResult {
todo!("user_balance_get");
}
/// `POST /user/balance` -- Manually process a confirmed txid to update a user's balance.
///
/// We will subscribe to events to watch for any user deposits, but sometimes events can be missed.
///
/// TODO: rate limit by user
/// TODO: one key per request? maybe /user/balance/:api_key?
/// TODO: this will change as we add better support for secondary users.
#[debug_handler]
pub async fn user_balance_post(
TypedHeader(Authorization(bearer_token)): TypedHeader<Authorization<Bearer>>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
) -> FrontendResult {
todo!("user_balance_post");
}
/// `GET /user/keys` -- Use a bearer token to get the user's api keys and their settings.
///
/// TODO: one key per request? maybe /user/keys/:api_key?
#[debug_handler]
pub async fn user_keys_get(
TypedHeader(Authorization(bearer_token)): TypedHeader<Authorization<Bearer>>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
) -> FrontendResult {
todo!("user_keys_get");
}
/// `POST /user/keys` -- Use a bearer token to create a new key or modify an existing key.
///
/// TODO: read json from the request body
/// TODO: one key per request? maybe /user/keys/:api_key?
#[debug_handler]
pub async fn user_keys_post(
TypedHeader(Authorization(bearer_token)): TypedHeader<Authorization<Bearer>>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
) -> FrontendResult {
todo!("user_keys_post");
}
/// `GET /user/profile` -- Use a bearer token to get the user's profile.
///
/// - the email address of a user if they opted in to get contacted via email
///
/// TODO: this will change as we add better support for secondary users.
#[debug_handler]
pub async fn user_profile_get(
TypedHeader(Authorization(bearer_token)): TypedHeader<Authorization<Bearer>>,
Extension(app): Extension<Arc<Web3ProxyApp>>,
) -> FrontendResult {
2022-10-18 02:16:09 +03:00
todo!("user_profile_get");
2022-10-18 00:47:58 +03:00
}
2022-10-20 02:02:34 +03:00
/// `GET /user/stats/detailed` -- Use a bearer token to get the user's key stats such as bandwidth used and methods requested.
///
2022-10-20 07:44:33 +03:00
/// If no bearer is provided, detailed stats for all users will be shown.
/// View a single user with `?user_id=$x`.
/// View a single chain with `?chain_id=$x`.
2022-10-18 00:47:58 +03:00
///
2022-10-20 07:44:33 +03:00
/// Set `$x` to zero to see all.
2022-10-18 00:47:58 +03:00
///
/// TODO: this will change as we add better support for secondary users.
#[debug_handler]
2022-10-20 02:02:34 +03:00
pub async fn user_stats_detailed_get(
2022-10-20 00:34:05 +03:00
// TODO: turn this back on when done debugging. maybe add a path field for this
// TypedHeader(Authorization(bearer)): TypedHeader<Authorization<Bearer>>,
2022-10-20 02:02:34 +03:00
bearer: Option<TypedHeader<Authorization<Bearer>>>,
2022-10-18 00:47:58 +03:00
Extension(app): Extension<Arc<Web3ProxyApp>>,
2022-10-20 00:34:05 +03:00
Query(params): Query<HashMap<String, String>>,
2022-10-18 00:47:58 +03:00
) -> FrontendResult {
2022-10-20 02:02:34 +03:00
// TODO: how is db_conn supposed to be used?
let db = app.db_conn.clone().context("connecting to db")?;
2022-10-20 00:34:05 +03:00
2022-10-20 02:02:34 +03:00
// get the attached address from redis for the given auth_token.
let mut redis_conn = app.redis_conn().await.context("connecting to redis")?;
2022-10-20 00:34:05 +03:00
2022-10-20 02:02:34 +03:00
// TODO: DRY
let user_id = match (bearer, params.get("user_id")) {
(Some(bearer), Some(params)) => {
// check for the bearer cache key
// TODO: move this to a helper function
let bearer_cache_key = format!("bearer:{}", bearer.token());
2022-10-20 00:34:05 +03:00
2022-10-20 02:02:34 +03:00
// get the user id that is attached to this bearer token
redis_conn
.get::<_, u64>(bearer_cache_key)
.await
// TODO: this should be a 403
.context("fetching user_key_id from redis with bearer_cache_key")?
}
(_, None) => {
// they have a bearer token. we don't care about it on public pages
// 0 means all
0
}
(None, Some(x)) => {
// they do not have a bearer token, but requested a specific id. block
// TODO: proper error code
// TODO: maybe instead of this sharp edged warn, we have a config value?
warn!("this should maybe be an access denied");
x.parse().context("Parsing user_id param")?
}
};
2022-10-20 00:34:05 +03:00
2022-10-20 07:44:33 +03:00
// only allow user_key to be set if user_id is also set
// this will keep people from reading someone else's keys
let user_key = if user_id > 0 {
params
.get("user_key")
.map_or_else::<anyhow::Result<u64>, _, _>(
|| Ok(0),
|c| {
let c = c.parse()?;
Ok(c)
},
)?
} else {
0
};
2022-10-20 02:02:34 +03:00
// TODO: DRY
2022-10-20 00:34:05 +03:00
let chain_id = params
.get("chain_id")
.map_or_else::<anyhow::Result<u64>, _, _>(
|| Ok(app.config.chain_id),
|c| {
let c = c.parse()?;
Ok(c)
},
)?;
2022-10-20 02:02:34 +03:00
// TODO: DRY
2022-10-20 00:34:05 +03:00
let query_start = params
.get("timestamp")
.map_or_else::<anyhow::Result<NaiveDateTime>, _, _>(
|| {
// no timestamp in params. set default
let x = chrono::Utc::now() - chrono::Duration::days(30);
Ok(x.naive_utc())
},
|x: &String| {
// parse the given timestamp
let x = x.parse::<i64>().context("parsing timestamp query param")?;
// TODO: error code 401
let x = NaiveDateTime::from_timestamp_opt(x, 0)
.context("parsing timestamp query param")?;
Ok(x)
},
)?;
2022-10-20 07:44:33 +03:00
let page = params
.get("page")
.map_or_else::<anyhow::Result<usize>, _, _>(
|| {
// no page in params. set default
Ok(0)
},
|x: &String| {
// parse the given timestamp
// TODO: error code 401
let x = x.parse::<usize>().context("parsing page query param")?;
Ok(x)
},
)?;
// TODO: page size from config
let page_size = 200;
let x = get_detailed_stats(
chain_id,
&db,
page,
page_size,
query_start,
user_key,
user_id,
)
.await?;
2022-10-20 00:34:05 +03:00
Ok(Json(x).into_response())
2022-10-18 00:47:58 +03:00
}
2022-10-19 03:56:57 +03:00
/// `GET /user/stats/aggregate` -- Public endpoint for aggregate stats such as bandwidth used and methods requested.
#[debug_handler]
pub async fn user_stats_aggregate_get(
bearer: Option<TypedHeader<Authorization<Bearer>>>,
2022-10-19 03:56:57 +03:00
Extension(app): Extension<Arc<Web3ProxyApp>>,
Query(params): Query<HashMap<String, String>>,
2022-10-19 03:56:57 +03:00
) -> FrontendResult {
// TODO: how is db_conn supposed to be used?
2022-10-20 07:44:33 +03:00
let db_conn = app.db_conn.clone().context("connecting to db")?;
// get the attached address from redis for the given auth_token.
let mut redis_conn = app.redis_conn().await.context("connecting to redis")?;
let user_id = match (bearer, params.get("user_id")) {
(Some(bearer), Some(params)) => {
// check for the bearer cache key
// TODO: move this to a helper function
let bearer_cache_key = format!("bearer:{}", bearer.token());
// get the user id that is attached to this bearer token
redis_conn
.get::<_, u64>(bearer_cache_key)
.await
// TODO: this should be a 403
.context("fetching user_key_id from redis with bearer_cache_key")?
}
(_, None) => {
// they have a bearer token. we don't care about it on public pages
// 0 means all
0
}
(None, Some(x)) => {
// they do not have a bearer token, but requested a specific id. block
// TODO: proper error code
// TODO: maybe instead of this sharp edged warn, we have a config value?
warn!("this should maybe be an access denied");
x.parse().context("Parsing user_id param")?
}
};
2022-10-19 03:56:57 +03:00
let chain_id = params
.get("chain_id")
.map_or_else::<anyhow::Result<u64>, _, _>(
|| Ok(app.config.chain_id),
|c| {
let c = c.parse()?;
Ok(c)
},
)?;
let query_start = params
2022-10-20 00:34:05 +03:00
.get("timestamp")
.map_or_else::<anyhow::Result<NaiveDateTime>, _, _>(
|| {
// no timestamp in params. set default
let x = chrono::Utc::now() - chrono::Duration::days(30);
Ok(x.naive_utc())
},
|x: &String| {
// parse the given timestamp
let x = x.parse::<i64>().context("parsing timestamp query param")?;
// TODO: error code 401
let x = NaiveDateTime::from_timestamp_opt(x, 0)
.context("parsing timestamp query param")?;
Ok(x)
},
)?;
2022-10-20 07:44:33 +03:00
let query_window_seconds = params
.get("query_window_seconds")
.map_or_else::<anyhow::Result<Option<u64>>, _, _>(
|| {
// no page in params. set default
Ok(None)
},
|x: &String| {
// parse the given timestamp
// TODO: error code 401
let x = x.parse::<u64>().context("parsing page query param")?;
if x == 0 {
Ok(None)
} else {
Ok(Some(x))
}
},
)?;
let page = params
.get("page")
.map_or_else::<anyhow::Result<usize>, _, _>(
|| {
// no page in params. set None
Ok(0)
},
|x: &String| {
// parse the given timestamp
// TODO: error code 401
let x = x.parse().context("parsing page query param")?;
Ok(x)
},
)?;
// TODO: page size from config
let page_size = 200;
// TODO: optionally no chain id?
2022-10-20 07:44:33 +03:00
let x = get_aggregate_rpc_stats(
chain_id,
&db_conn,
page,
page_size,
query_start,
query_window_seconds,
user_id,
)
.await?;
2022-10-19 03:56:57 +03:00
Ok(Json(x).into_response())
}
2022-10-18 00:47:58 +03:00
/// `GET /user/profile` -- Use a bearer token to get the user's profile such as their optional email address.
/// Handle authorization for a given address and bearer token.
// TODO: what roles should exist?
enum ProtectedAction {
2022-10-20 00:34:05 +03:00
PostUser(Address),
}
2022-08-23 22:08:47 +03:00
impl ProtectedAction {
2022-10-18 00:47:58 +03:00
/// Verify that the given bearer token and address are allowed to take the specified action.
async fn verify(
self,
app: &Web3ProxyApp,
2022-09-24 07:31:06 +03:00
// TODO: i don't think we want Bearer here. we want user_key and a helper for bearer -> user_key
bearer: Bearer,
2022-09-05 04:52:59 +03:00
) -> anyhow::Result<user::Model> {
2022-08-27 08:42:25 +03:00
// get the attached address from redis for the given auth_token.
let mut redis_conn = app.redis_conn().await?;
2022-10-20 00:34:05 +03:00
// TODO: move this to a helper function
2022-09-24 07:31:06 +03:00
let bearer_cache_key = format!("bearer:{}", bearer.token());
2022-10-20 00:34:05 +03:00
// TODO: move this to a helper function
let user_id: Option<u64> = redis_conn
2022-09-24 07:31:06 +03:00
.get(bearer_cache_key)
.await
.context("fetching bearer cache key from redis")?;
// TODO: if auth_address == primary_address, allow
// TODO: if auth_address != primary_address, only allow if they are a secondary user with the correct role
todo!("verify token for the given user");
}
2022-08-23 22:08:47 +03:00
}