use crate::authorization::permissions::Permission; use crate::session::SessionHandle; use crate::users::{db, UserRef}; use api::user_capnp::user::{self, self_service, manage, admin}; use capnp::capability::{Promise, FromClientHook}; use capnp_rpc::pry; use api::role_capnp; use crate::capnp::role::Role; #[derive(Clone)] pub struct User { session: SessionHandle, user: UserRef, } impl User { pub fn new(session: SessionHandle, user: UserRef) -> Self { Self { session, user } } pub fn new_self(session: SessionHandle) -> Self { let user = session.get_user_ref(); Self::new(session, user) } pub fn fill(session: SessionHandle, user: db::User) -> Self { Self { user: UserRef::new(user.id), session, } } } impl user::Server for User { fn roles( &mut self, _: user::RolesParams, mut result: user::RolesResults, ) -> Promise<(), ::capnp::Error> { if let Some(user) = self.session.users.get_user(self.user.get_username()) { let mut builder = result.get().init_roles(user.userdata.roles.len() as u32); for (i, role) in user.userdata.roles.into_iter().enumerate() { let role = Role::new(self.session.clone(), role); let cap: role_capnp::role::Client = capnp_rpc::new_client(role); builder.reborrow().set(i as u32, cap.into_client_hook()); } } Promise::ok(()) } } impl manage::Server for User { } impl admin::Server for User { fn setpw( &mut self, param: admin::SetpwParams, _: admin::SetpwResults, ) -> Promise<(), ::capnp::Error> { let new_pw = pry!(pry!(param.get()).get_new()); let uid = self.user.get_username(); if let Some(mut user) = self.session.users.get_user(uid) { user.set_pw(new_pw.as_bytes()); self.session.users.put_user(uid, &user); } Promise::ok(()) } }