| 344 | } |
| 345 | |
| 346 | pub async fn add_user( |
| 347 | tu: TenantUser, |
| 348 | device_profiles: &[TenantUserDeviceProfile], |
| 349 | applications: &[TenantUserApplication], |
| 350 | ) -> Result<TenantUser, Error> { |
| 351 | let mut c = get_async_db_conn().await?; |
| 352 | let tu: TenantUser = c |
| 353 | .transaction::<TenantUser, Error, _>(async |c| { |
| 354 | let tu: TenantUser = diesel::insert_into(tenant_user::table) |
| 355 | .values(&tu) |
| 356 | .get_result(c) |
| 357 | .await |
| 358 | .map_err(|e| Error::from_diesel(e, tu.user_id.to_string()))?; |
| 359 | |
| 360 | for dp in device_profiles { |
| 361 | // make sure dp exists under same tenant |
| 362 | let _: storage::device_profile::DeviceProfile = device_profile::table |
| 363 | .filter( |
| 364 | device_profile::id |
| 365 | .eq(dp.device_profile_id) |
| 366 | .and(device_profile::tenant_id.eq(&tu.tenant_id)), |
| 367 | ) |
| 368 | .first(c) |
| 369 | .await |
| 370 | .map_err(|e| Error::from_diesel(e, dp.device_profile_id.to_string()))?; |
| 371 | |
| 372 | diesel::insert_into(tenant_user_device_profile::table) |
| 373 | .values(dp) |
| 374 | .execute(c) |
| 375 | .await |
| 376 | .map_err(|e| Error::from_diesel(e, tu.user_id.to_string()))?; |
| 377 | } |
| 378 | |
| 379 | for app in applications { |
| 380 | // make sure dp exists under same tenant |
| 381 | let _: storage::application::Application = application::table |
| 382 | .filter( |
| 383 | application::id |
| 384 | .eq(app.application_id) |
| 385 | .and(application::tenant_id.eq(&tu.tenant_id)), |
| 386 | ) |
| 387 | .first(c) |
| 388 | .await |
| 389 | .map_err(|e| Error::from_diesel(e, app.application_id.to_string()))?; |
| 390 | |
| 391 | diesel::insert_into(tenant_user_application::table) |
| 392 | .values(app) |
| 393 | .execute(c) |
| 394 | .await |
| 395 | .map_err(|e| Error::from_diesel(e, tu.user_id.to_string()))?; |
| 396 | } |
| 397 | |
| 398 | Ok(tu) |
| 399 | }) |
| 400 | .await?; |
| 401 | |
| 402 | info!( |
| 403 | tenant_id = %tu.tenant_id, |