Skip to content
65 changes: 30 additions & 35 deletions src/api/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,10 @@ async fn get_user_or_404(user_id: &UserId, conn: &DbConn) -> ApiResult<User> {
}
}

async fn get_sso_user(user_id: &UserId, conn: &DbConn) -> Option<SsoUser> {
SsoUser::find_by_uuid(user_id, conn).await.and_then(|user_and_sso| user_and_sso.1)
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function would become obsolete if SsoUser::find_by_uuid were to return an Option<SsoUser>.

#[post("/invite", format = "application/json", data = "<data>")]
async fn invite_user(data: Json<InviteData>, _token: AdminToken, conn: DbConn) -> JsonResult {
let data: InviteData = data.into_inner();
Expand Down Expand Up @@ -347,68 +351,59 @@ fn logout(cookies: &CookieJar<'_>) -> Redirect {
Redirect::to(admin_path())
}

#[get("/users")]
async fn get_users_json(_token: AdminToken, conn: DbConn) -> Json<Value> {
let users = User::get_all(&conn).await;
async fn get_users_property(users: Vec<(User, Option<SsoUser>)>, conn: &DbConn) -> Vec<Value> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just as an idea but maybe we could rename the function so it's clearer what it does? E.g. enrich_users_json or something like that.

let mut users_json = Vec::with_capacity(users.len());
for (u, _) in users {
let mut usr = u.to_json(&conn).await;
for (u, sso_u) in users {
let mut usr = u.to_json(conn).await;
usr["cipherCount"] = json!(Cipher::count_owned_by_user(&u.uuid, conn).await);
usr["attachmentCount"] = json!(Attachment::count_by_user(&u.uuid, conn).await);
usr["attachmentSize"] = json!(get_display_size(Attachment::size_by_user(&u.uuid, conn).await));
usr["userEnabled"] = json!(u.enabled);
usr["createdAt"] = json!(format_naive_datetime_local(&u.created_at, DT_FMT));
usr["lastActive"] = match u.last_active(&conn).await {
usr["lastActive"] = match u.last_active(conn).await {
Some(dt) => json!(format_naive_datetime_local(&dt, DT_FMT)),
None => json!(None::<String>),
None => json!("Never"),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that it would probably be cleaner to return nothing here and have the template render Never if that is possible. That way the Admin template can also be translated.

};

usr["ssoIdentifier"] = json!(sso_u.map(|u| u.identifier.to_string()).unwrap_or(String::new()));

users_json.push(usr);
}
users_json
}

#[get("/users")]
async fn get_users_json(_token: AdminToken, conn: DbConn) -> Json<Value> {
let users = User::get_all(&conn).await;
let users_json = get_users_property(users, &conn).await;
Json(Value::Array(users_json))
}

#[get("/users/overview")]
async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<String>> {
let users = User::get_all(&conn).await;
let mut users_json = Vec::with_capacity(users.len());
for (u, sso_u) in users {
let mut usr = u.to_json(&conn).await;
usr["cipher_count"] = json!(Cipher::count_owned_by_user(&u.uuid, &conn).await);
usr["attachment_count"] = json!(Attachment::count_by_user(&u.uuid, &conn).await);
usr["attachment_size"] = json!(get_display_size(Attachment::size_by_user(&u.uuid, &conn).await));
usr["user_enabled"] = json!(u.enabled);
usr["created_at"] = json!(format_naive_datetime_local(&u.created_at, DT_FMT));
usr["last_active"] = match u.last_active(&conn).await {
Some(dt) => json!(format_naive_datetime_local(&dt, DT_FMT)),
None => json!("Never"),
};

usr["sso_identifier"] = json!(sso_u.map(|u| u.identifier.to_string()).unwrap_or(String::new()));

users_json.push(usr);
}

let users_json = get_users_property(users, &conn).await;
let text = AdminTemplateData::new("admin/users", json!(users_json)).render()?;
Ok(Html(text))
}

#[get("/users/by-mail/<mail>")]
async fn get_user_by_mail_json(mail: &str, _token: AdminToken, conn: DbConn) -> JsonResult {
if let Some(u) = User::find_by_mail(mail, &conn).await {
let mut usr = u.to_json(&conn).await;
usr["userEnabled"] = json!(u.enabled);
usr["createdAt"] = json!(format_naive_datetime_local(&u.created_at, DT_FMT));
Ok(Json(usr))
if let Some((u, sso)) = SsoUser::find_by_mail(mail, &conn).await {
let user_json = get_users_property(vec![(u, sso)], &conn).await[0].clone();
Ok(Json(user_json))
} else {
err_code!("User doesn't exist", Status::NotFound.code);
}
}

#[get("/users/<user_id>")]
async fn get_user_json(user_id: UserId, _token: AdminToken, conn: DbConn) -> JsonResult {
let u = get_user_or_404(&user_id, &conn).await?;
let mut usr = u.to_json(&conn).await;
usr["userEnabled"] = json!(u.enabled);
usr["createdAt"] = json!(format_naive_datetime_local(&u.created_at, DT_FMT));
Ok(Json(usr))
let user = get_user_or_404(&user_id, &conn).await?;
let sso_user = get_sso_user(&user_id, &conn).await;
let user_json = get_users_property(vec![(user, sso_user)], &conn).await[0].clone();

Ok(Json(user_json))
}

#[post("/users/<user_id>/delete", format = "application/json")]
Expand Down
11 changes: 11 additions & 0 deletions src/db/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,17 @@ impl SsoUser {
}}
}

pub async fn find_by_uuid(uuid: &UserId, conn: &DbConn) -> Option<(User, Option<Self>)> {
db_run! { conn: {
users::table
.left_join(sso_users::table)
.select(<(User, Option<Self>)>::as_select())
.filter(users::uuid.eq(uuid))
.first::<(User, Option<Self>)>(conn)
.ok()
}}
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can now be simplified to just return the SsoUser entry?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I originally had it keep returning User for all other find_by_XXX calls of SsoUser returned it, so I thought it might be beneficial for future use.

pub async fn delete(user_uuid: &UserId, conn: &DbConn) -> EmptyResult {
db_run! { conn: {
diesel::delete(sso_users::table.filter(sso_users::user_uuid.eq(user_uuid)))
Expand Down
16 changes: 8 additions & 8 deletions src/static/templates/admin/users.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
<strong>{{name}}</strong>
<span class="d-block">{{email}}</span>
<span class="d-block">
{{#unless user_enabled}}
{{#unless userEnabled}}
<span class="badge bg-danger me-2" title="User is disabled">Disabled</span>
{{/unless}}
{{#if twoFactorEnabled}}
Expand All @@ -43,22 +43,22 @@
</td>
{{#if ../sso_enabled}}
<td>
<span class="d-block">{{sso_identifier}}</span>
<span class="d-block">{{ssoIdentifier}}</span>
</td>
{{/if}}
<td>
<span class="d-block">{{created_at}}</span>
<span class="d-block">{{createdAt}}</span>
</td>
<td>
<span class="d-block">{{last_active}}</span>
<span class="d-block">{{lastActive}}</span>
</td>
<td>
<span class="d-block">{{cipher_count}}</span>
<span class="d-block">{{cipherCount}}</span>
</td>
<td>
<span class="d-block"><strong>Amount:</strong> {{attachment_count}}</span>
<span class="d-block"><strong>Amount:</strong> {{attachmentCount}}</span>
{{#if attachment_count}}
<span class="d-block"><strong>Size:</strong> {{attachment_size}}</span>
<span class="d-block"><strong>Size:</strong> {{attachmentSize}}</span>
{{/if}}
</td>
<td>
Expand All @@ -78,7 +78,7 @@
{{#if ../sso_enabled}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-delete-sso-user>Delete SSO Association</button><br>
{{/if}}
{{#if user_enabled}}
{{#if userEnabled}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-disable-user>Disable User</button><br>
{{else}}
<button type="button" class="btn btn-sm btn-link p-0 border-0 float-right" vw-enable-user>Enable User</button><br>
Expand Down