2022-07-14 00:49:57 +03:00
// So the API needs to show for any given user:
// - show balance in USD
// - show deposits history (currency, amounts, transaction id)
// - show number of requests used (so we can calculate average spending over a month, burn rate for a user etc, something like "Your balance will be depleted in xx days)
// - the email address of a user if he opted in to get contacted via email
// - all the monitoring and stats but that will come from someplace else if I understand corectly?
// I wonder how we handle payment
// probably have to do manual withdrawals
2022-08-17 00:43:39 +03:00
use super ::{
errors ::{ anyhow_error_into_response , FrontendResult } ,
rate_limit ::RateLimitResult ,
} ;
2022-08-16 22:29:00 +03:00
use crate ::app ::Web3ProxyApp ;
2022-08-11 04:53:27 +03:00
use axum ::{
2022-08-21 11:18:57 +03:00
extract ::{ Path , Query } ,
2022-08-17 00:43:39 +03:00
response ::{ IntoResponse , Response } ,
2022-08-11 04:53:27 +03:00
Extension , Json ,
} ;
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 ;
2022-08-17 02:03:50 +03:00
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-08-17 01:52:12 +03:00
use redis_rate_limit ::redis ::AsyncCommands ;
2022-08-11 04:53:27 +03:00
use reqwest ::StatusCode ;
2022-08-04 04:10:27 +03:00
use sea_orm ::ActiveModelTrait ;
use serde ::Deserialize ;
2022-08-17 01:52:12 +03:00
use siwe ::Message ;
use std ::ops ::Add ;
2022-08-04 04:10:27 +03:00
use std ::sync ::Arc ;
2022-08-17 01:52:12 +03:00
use time ::{ Duration , OffsetDateTime } ;
2022-08-21 11:18:57 +03:00
use ulid ::Ulid ;
#[ allow(unused) ]
use super ::axum_ext ::empty_string_as_none ;
2022-08-04 02:17:02 +03:00
2022-08-17 00:10:09 +03:00
// TODO: how do we customize axum's error response? I think we probably want an enum that implements IntoResponse instead
2022-08-16 22:29:00 +03:00
#[ debug_handler ]
2022-08-17 00:10:09 +03:00
pub async fn get_login (
Extension ( app ) : Extension < Arc < Web3ProxyApp > > ,
2022-08-17 00:43:39 +03:00
ClientIp ( ip ) : ClientIp ,
2022-08-17 01:52:12 +03:00
// TODO: what does axum's error handling look like if the path fails to parse?
// TODO: allow ENS names here?
2022-08-19 23:18:12 +03:00
Path ( mut params ) : Path < HashMap < String , String > > ,
2022-08-17 00:43:39 +03:00
) -> FrontendResult {
// TODO: refactor this to use the try operator
let _ip = match app . rate_limit_by_ip ( ip ) . await {
Ok ( x ) = > match x . try_into_response ( ) . await {
Ok ( RateLimitResult ::AllowedIp ( x ) ) = > x ,
Err ( err_response ) = > return Ok ( err_response ) ,
_ = > unimplemented! ( ) ,
} ,
Err ( err ) = > return Ok ( anyhow_error_into_response ( None , None , err ) ) ,
} ;
// 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
2022-08-17 01:52:12 +03:00
// TODO: how many seconds? get from config?
let expire_seconds : usize = 300 ;
2022-08-21 11:18:57 +03:00
let nonce = Ulid ::new ( ) ;
2022-08-17 01:52:12 +03:00
let issued_at = OffsetDateTime ::now_utc ( ) ;
let expiration_time = issued_at . add ( Duration ::new ( expire_seconds as i64 , 0 ) ) ;
2022-08-19 23:18:12 +03:00
// TODO: proper errors. the first unwrap should be impossible, but the second will happen with bad input
let user_address : Address = params . remove ( " user_address " ) . unwrap ( ) . parse ( ) . unwrap ( ) ;
2022-08-17 00:43:39 +03:00
2022-08-17 01:52:12 +03:00
// TODO: get most of these from the app config
let message = Message {
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 ) ;
// TODO: if no redis server, store in local cache?
2022-08-21 11:18:57 +03:00
let mut redis_conn = app
2022-08-17 00:43:39 +03:00
. redis_pool
. as_ref ( )
2022-08-21 11:18:57 +03:00
. expect ( " login requires a redis server " )
. get ( )
. await ? ;
2022-08-17 00:43:39 +03:00
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_string
2022-08-17 01:52:12 +03:00
redis_conn
. set_ex ( session_key , message . to_string ( ) , expire_seconds )
. await ? ;
2022-08-21 11:18:57 +03:00
drop ( redis_conn ) ;
2022-08-19 23:18:12 +03:00
// there are multiple ways to sign messages and not all wallets support them
let message_eip = params
. remove ( " message_eip " )
. unwrap_or_else ( | | " eip4361 " . to_string ( ) ) ;
let message : String = match message_eip . as_str ( ) {
" eip4361 " = > message . to_string ( ) ,
// https://github.com/spruceid/siwe/issues/98
" eip191_string " = > Bytes ::from ( message . eip191_string ( ) . unwrap ( ) ) . to_string ( ) ,
" eip191_hash " = > Bytes ::from ( & message . eip191_hash ( ) . unwrap ( ) ) . to_string ( ) ,
2022-08-21 11:18:57 +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-08-21 11:18:57 +03:00
/// Query params to our `post_login` handler.
#[ derive(Debug, Deserialize) ]
pub struct PostLoginQuery {
invite_code : Option < String > ,
}
/// JSON body to our `post_login` handler.
#[ derive(Deserialize) ]
pub struct PostLogin {
address : Address ,
msg : String ,
sig : Bytes ,
version : String ,
signer : String ,
}
2022-08-17 00:10:09 +03:00
#[ debug_handler ]
2022-08-21 11:18:57 +03:00
/// Post to the user endpoint to register or login.
pub async fn post_login (
2022-08-04 04:10:27 +03:00
ClientIp ( ip ) : ClientIp ,
2022-08-21 11:18:57 +03:00
Extension ( app ) : Extension < Arc < Web3ProxyApp > > ,
Json ( payload ) : Json < PostLogin > ,
Query ( query ) : Query < PostLoginQuery > ,
2022-08-11 04:53:27 +03:00
) -> Response {
2022-08-16 22:29:00 +03:00
// TODO: return a Result instead
2022-08-21 11:18:57 +03:00
// TODO: dry this up ip checking up
2022-08-11 04:53:27 +03:00
let _ip = match app . rate_limit_by_ip ( ip ) . await {
Ok ( x ) = > match x . try_into_response ( ) . await {
Ok ( RateLimitResult ::AllowedIp ( x ) ) = > x ,
Err ( err_response ) = > return err_response ,
_ = > unimplemented! ( ) ,
} ,
2022-08-16 22:29:00 +03:00
Err ( err ) = > return anyhow_error_into_response ( None , None , err ) ,
2022-08-11 04:53:27 +03:00
} ;
2022-08-04 04:10:27 +03:00
2022-08-21 11:18:57 +03:00
let mut new_user = true ; // TODO: check the database
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
let redis_pool = app
. redis_pool
. as_ref ( )
. expect ( " login requires a redis server " ) ;
let mut redis_conn = redis_pool . get ( ) . await . unwrap ( ) ;
// TODO: use getdel
// TODO: do not unwrap. make this function return a FrontendResult
2022-08-21 11:18:57 +03:00
let our_msg : String = redis_conn . get ( & their_msg . nonce ) . await . unwrap ( ) ;
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
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 , Some ( & our_msg . domain ) , Some ( & our_msg . nonce ) , None ) {
2022-08-04 04:10:27 +03:00
// message cannot be correctly authenticated
todo! ( " proper error message: {} " , e )
}
2022-08-21 11:18:57 +03:00
if new_user {
// the only thing we need from them is an address
// everything else is optional
let user = user ::ActiveModel {
address : sea_orm ::Set ( payload . address . to_fixed_bytes ( ) . into ( ) ) ,
.. Default ::default ( )
} ;
2022-07-14 00:49:57 +03:00
2022-08-21 11:18:57 +03:00
let db = app . db_conn . as_ref ( ) . unwrap ( ) ;
2022-08-04 02:17:02 +03:00
2022-08-21 11:18:57 +03:00
let user = user . insert ( db ) . await . unwrap ( ) ;
2022-08-04 02:17:02 +03:00
2022-08-21 11:18:57 +03:00
let api_key = todo! ( " create an api key " ) ;
2022-08-17 02:03:50 +03:00
2022-08-21 11:18:57 +03:00
/*
let rpm = app . config . something ;
2022-08-17 02:03:50 +03:00
2022-08-21 11:18:57 +03:00
// create a key for the new user
// TODO: requests_per_minute should be configurable
let uk = user_keys ::ActiveModel {
user_id : u . id ,
api_key : sea_orm ::Set ( api_key ) ,
requests_per_minute : sea_orm ::Set ( rpm ) ,
.. Default ::default ( )
} ;
// TODO: if this fails, rever adding the user, too
let uk = uk . save ( & txn ) . await . context ( " Failed saving new user key " ) ? ;
2022-08-17 02:03:50 +03:00
2022-08-21 11:18:57 +03:00
// TODO: set a cookie?
2022-08-16 20:47:04 +03:00
2022-08-21 11:18:57 +03:00
// TODO: do not expose user ids
( StatusCode ::CREATED , Json ( user ) ) . into_response ( )
* /
} else {
todo! ( " load existing user from the database " ) ;
}
2022-07-14 00:49:57 +03:00
}
2022-08-21 11:18:57 +03:00
/// the JSON input to the `post_user` handler
2022-07-14 00:49:57 +03:00
#[ derive(Deserialize) ]
2022-08-21 11:18:57 +03:00
pub struct PostUser {
2022-08-04 02:17:02 +03:00
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
}
#[ debug_handler ]
/// post to the user endpoint to modify your account
pub async fn post_user (
Json ( payload ) : Json < PostUser > ,
Extension ( app ) : Extension < Arc < Web3ProxyApp > > ,
ClientIp ( ip ) : ClientIp ,
) -> FrontendResult {
todo! ( " finish post_login " ) ;
// let user = user::ActiveModel {
// address: sea_orm::Set(payload.address.to_fixed_bytes().into()),
// email: sea_orm::Set(payload.email),
// ..Default::default()
// };
2022-07-14 00:49:57 +03:00
}