Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/frontend/src/layouts/default.vue
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@
label: 'User lookup',
icon: UserSearchIcon,
type: 'link',
to: '/admin/user_email',
to: '/admin/user_lookup',
shown: isAdmin(auth.user),
},
{
Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/src/pages/admin.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
icon: FileSearchCornerIcon,
},
{
link: '/admin/user_email',
link: '/admin/user_lookup',
label: 'User lookup',
icon: UserSearchIcon,
shown: admin,
Expand Down
58 changes: 0 additions & 58 deletions apps/frontend/src/pages/admin/user_email.vue

This file was deleted.

134 changes: 134 additions & 0 deletions apps/frontend/src/pages/admin/user_lookup.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
<template>
<div>
<h2 class="m-0 mb-4 text-2xl font-semibold">User lookup</h2>
<form
v-if="isAdmin(auth.user)"
class="card flex flex-col gap-3"
@submit.prevent="lookupUser('email')"
>
<div class="flex flex-col gap-2">
<label for="user-email">
<span class="text-lg font-semibold text-contrast">
User email
<span class="text-brand-red">*</span>
</span>
</label>
<Input
id="user-email"
v-model="userEmail"
type="email"
:maxlength="64"
placeholder="Enter user email..."
:disabled="isLookingUp"
autocomplete="off"
required
/>
</div>
<div class="flex gap-2">
<Button
type="colored"
color="brand"
native-type="submit"
:disabled="!userEmail.trim() || isLookingUp"
:loading="isFetchingEmail"
>
<MailIcon aria-hidden="true" />
Get user account
</Button>
</div>
</form>
<form class="card flex flex-col gap-3" @submit.prevent="lookupUser('discord')">
<div class="flex flex-col gap-2">
<label for="discord-id">
<span class="text-lg font-semibold text-contrast">
Discord ID
<span class="text-brand-red">*</span>
</span>
</label>
<Input
id="discord-id"
v-model="discordId"
type="text"
inputmode="numeric"
pattern="[0-9]+"
:maxlength="19"
placeholder="Enter Discord ID..."
:disabled="isLookingUp"
autocomplete="off"
required
/>
</div>
<div class="flex gap-2">
<Button
type="colored"
color="brand"
native-type="submit"
:disabled="!discordId.trim() || isLookingUp"
:loading="isFetchingDiscord"
>
<DiscordIcon aria-hidden="true" />
Get user account
</Button>
</div>
</form>
</div>
</template>
<script setup lang="ts">
import type { Labrinth } from '@modrinth/api-client'
import { DiscordIcon, MailIcon } from '@modrinth/assets'
import { Button, injectNotificationManager, Input } from '@modrinth/ui'
import { isAdmin } from '@modrinth/utils'
import { useQuery } from '@tanstack/vue-query'

const { addNotification } = injectNotificationManager()
const auth = await useAuth()

const userEmail = ref('')
const discordId = ref('')

const { refetch: lookupEmail, isFetching: isFetchingEmail } = useQuery({
queryKey: computed(() => ['users', 'lookup', 'email', userEmail.value.trim()]),
queryFn: async () =>
(await useBaseFetch('user_email', {
apiVersion: 3,
query: { email: userEmail.value.trim() },
})) as Labrinth.Users.v3.User,
enabled: false,
retry: false,
})

const { refetch: lookupDiscord, isFetching: isFetchingDiscord } = useQuery({
queryKey: computed(() => ['users', 'lookup', 'discord', discordId.value.trim()]),
queryFn: async () =>
(await useBaseFetch('user_discord', {
apiVersion: 3,
query: { discord_id: discordId.value.trim() },
})) as Labrinth.Users.v3.User,
enabled: false,
retry: false,
})

const isLookingUp = computed(() => isFetchingEmail.value || isFetchingDiscord.value)

async function lookupUser(kind: 'email' | 'discord') {
if (isLookingUp.value || (kind === 'email' && !isAdmin(auth.value.user))) return

startLoading()

try {
const lookup = kind === 'email' ? lookupEmail : lookupDiscord
const { data } = await lookup({ throwOnError: true })

if (data) await navigateTo(`/user/${encodeURIComponent(data.username)}`)
} catch (err) {
console.error(err)
addNotification({
title: 'User lookup failed',
text: err instanceof Error ? err.message : 'User lookup failed',
type: 'error',
})
} finally {
stopLoading()
}
}
</script>
20 changes: 20 additions & 0 deletions apps/labrinth/src/database/models/user_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,26 @@ impl DBUser {
Ok(users)
}

pub async fn get_by_discord_id<'a, E>(
discord_id: u64,
exec: E,
) -> Result<Option<DBUserId>, sqlx::Error>
where
E: crate::database::Executor<'a, Database = sqlx::Postgres>,
{
let Ok(discord_id) = i64::try_from(discord_id) else {
return Ok(None);
};

sqlx::query_scalar!(
r#"SELECT id FROM users WHERE discord_id = $1"#,
discord_id
)
.fetch_optional(exec)
.await
.map(|id| id.map(DBUserId))
}

pub async fn get_by_email<'a, E>(
email: &str,
exec: E,
Expand Down
1 change: 1 addition & 0 deletions apps/labrinth/src/routes/v3/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ pub fn config(cfg: &mut web::ServiceConfig) {
threads::message_delete_route,
users::all_projects,
users::admin_user_email,
users::admin_user_discord,
users::projects_list_route,
users::user_auth_get_route,
users::users_search,
Expand Down
61 changes: 56 additions & 5 deletions apps/labrinth/src/routes/v3/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
use xredis::RedisPool;

use super::{ApiError, oauth_clients::get_user_clients};
use crate::database::PgPool;
use crate::database::{PgPool, ReadOnlyPgPool};
use crate::util::error::Context;
use crate::{
auth::{
Expand All @@ -22,7 +22,7 @@ use crate::{
organizations::Organization,
pats::Scopes,
projects::Project,
users::{Badges, Role},
users::{Badges, Role, User},
},
queue::session::AuthQueue,
util::{img::delete_old_images, routes::read_limited_from_payload},
Expand All @@ -41,6 +41,7 @@ pub fn config(cfg: &mut actix_web::web::ServiceConfig) {
.service(users_get_route)
.service(users_search)
.service(admin_user_email)
.service(admin_user_discord)
.service(all_projects)
.service(projects_list_route)
.service(user_notes_edit)
Expand Down Expand Up @@ -69,6 +70,11 @@ pub struct UserEmailQuery {
pub email: String,
}

#[derive(Deserialize)]
pub struct UserDiscordQuery {
pub discord_id: u64,
}

#[utoipa::path(tag = "users", responses((status = OK)))]
#[get("/user/{user_id}/all-projects")]
pub async fn all_projects(
Expand Down Expand Up @@ -216,7 +222,7 @@ pub async fn all_projects(
#[utoipa::path(
tag = "users",
params(("email" = String, Query)),
responses((status = OK))
responses((status = OK, body = User))
)]
#[get("/user_email")]
pub async fn admin_user_email(
Expand All @@ -225,7 +231,7 @@ pub async fn admin_user_email(
redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>,
email: web::Query<UserEmailQuery>,
) -> Result<HttpResponse, ApiError> {
) -> Result<web::Json<User>, ApiError> {
let user = get_user_from_headers(
&req,
&**pool,
Expand Down Expand Up @@ -267,12 +273,57 @@ pub async fn admin_user_email(
.wrap_internal_err("fetching user from database")?;

if let Some(user) = user {
Ok(HttpResponse::Ok().json(user))
Ok(web::Json(user.into()))
} else {
Err(ApiError::NotFound(eyre::eyre!("resource not found")))
}
}

#[utoipa::path(
tag = "users",
params(("discord_id" = u64, Query)),
responses((status = OK, body = User))
)]
#[get("/user_discord")]
pub async fn admin_user_discord(
req: HttpRequest,
ro_pool: web::Data<ReadOnlyPgPool>,
redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>,
query: web::Query<UserDiscordQuery>,
) -> Result<web::Json<User>, ApiError> {
let user = get_user_from_headers(
&req,
&***ro_pool,
&redis,
&session_queue,
Scopes::SESSION_ACCESS,
)
.await
.map(|x| x.1)
.wrap_auth_err("authenticating API request")?;

if !user.role.is_admin() {
return Err(ApiError::Auth(eyre!(
"you must be an admin to look up users by discord ID"
)));
}

let user_id = DBUser::get_by_discord_id(query.discord_id, &***ro_pool)
.await
.wrap_internal_err("fetching user ID from database")?
.wrap_request_err(
"the discord ID provided is not associated with a user",
)?;

let user = DBUser::get_id(user_id, &***ro_pool, &redis)
.await
.wrap_internal_err("fetching user from database")?
.wrap_not_found_err("resource not found")?;

Ok(web::Json(user.into()))
}

#[utoipa::path(tag = "users", responses((status = OK)))]
#[get("/user/{user_id}/projects")]
pub async fn projects_list_route(
Expand Down
Loading
Loading