fabaccess-bffh/src/connection.rs

73 lines
2.0 KiB
Rust
Raw Normal View History

2020-11-17 14:28:04 +01:00
use std::sync::Arc;
2020-11-30 15:05:25 +01:00
use std::future::Future;
use futures::FutureExt;
2020-11-17 14:28:04 +01:00
2020-05-11 18:21:45 +02:00
use slog::Logger;
2020-09-07 17:23:42 +02:00
use smol::net::TcpStream;
2020-05-11 18:21:45 +02:00
2020-10-29 13:04:20 +01:00
use crate::error::{Error, Result};
2020-11-17 14:35:16 +01:00
use crate::api::auth;
use crate::api::Bootstrap;
2020-10-29 13:04:20 +01:00
use capnp_rpc::{twoparty, rpc_twoparty_capnp};
2020-11-17 14:35:16 +01:00
use crate::schema::connection_capnp;
2020-05-11 18:21:45 +02:00
2020-11-20 13:06:55 +01:00
use crate::db::Databases;
2020-11-24 14:16:22 +01:00
use crate::db::access::{AccessControl, Permission};
2020-11-24 15:57:23 +01:00
use crate::db::user::User;
2020-11-24 14:16:22 +01:00
use crate::builtin;
2020-11-20 13:06:55 +01:00
#[derive(Debug, Clone)]
2020-10-23 15:29:32 +02:00
/// Connection context
2020-11-17 14:28:04 +01:00
// TODO this should track over several connections
pub struct Session {
2020-11-24 14:16:22 +01:00
// Session-spezific log
pub log: Logger,
2020-11-24 15:57:23 +01:00
user: Option<User>,
2020-11-24 14:16:22 +01:00
accessdb: Arc<AccessControl>,
2020-10-23 15:29:32 +02:00
}
2020-05-11 18:21:45 +02:00
2020-11-17 14:28:04 +01:00
impl Session {
2020-11-24 14:16:22 +01:00
pub fn new(log: Logger, accessdb: Arc<AccessControl>) -> Self {
2020-11-24 15:57:23 +01:00
let user = None;
2020-10-29 13:04:20 +01:00
2020-11-24 15:57:23 +01:00
Session { log, user, accessdb }
2020-11-24 14:16:22 +01:00
}
/// Check if the current session has a certain permission
pub async fn check_permission<P: AsRef<Permission>>(&self, perm: &P) -> Result<bool> {
2020-11-24 15:57:23 +01:00
if let Some(user) = self.user.as_ref() {
self.accessdb.check(&user.data, perm).await
2020-11-24 14:16:22 +01:00
} else {
2020-11-24 15:57:23 +01:00
Ok(false)
2020-11-24 14:16:22 +01:00
}
2020-10-29 13:04:20 +01:00
}
}
2020-11-30 15:05:25 +01:00
pub struct ConnectionHandler {
log: Logger,
db: Databases,
}
impl ConnectionHandler {
pub fn new(log: Logger, db: Databases) -> Self {
Self { log, db }
}
2020-10-29 13:04:20 +01:00
2020-11-30 15:05:25 +01:00
pub fn handle(&mut self, mut stream: TcpStream) -> impl Future<Output=Result<()>> {
info!(self.log, "New connection from on {:?}", stream);
let session = Arc::new(Session::new(self.log.new(o!()), self.db.access.clone()));
let boots = Bootstrap::new(session, self.db.clone());
let rpc: connection_capnp::bootstrap::Client = capnp_rpc::new_client(boots);
2020-10-29 13:04:20 +01:00
2020-11-30 15:05:25 +01:00
let network = twoparty::VatNetwork::new(stream.clone(), stream,
rpc_twoparty_capnp::Side::Server, Default::default());
let rpc_system = capnp_rpc::RpcSystem::new(Box::new(network), Some(rpc.client));
// Convert the error type to one of our errors
rpc_system.map(|r| r.map_err(Into::into))
}
2020-05-11 18:21:45 +02:00
}