-
Notifications
You must be signed in to change notification settings - Fork 609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a basic user admin backend #10245
Open
LawnGnome
wants to merge
5
commits into
rust-lang:main
Choose a base branch
from
LawnGnome:user-admin-backend
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a478176
auth: add an `AuthCheck` variant to check for admin rights
LawnGnome 064536e
TestApp: add a method to get an admin user
LawnGnome 64ee2c4
controllers: add new `/api/v1/users/:user_id/admin` route
LawnGnome bc5d6a4
controllers/user/admin: add a lock route
LawnGnome 2f06ce1
controllers/user/admin: add an unlock route
LawnGnome File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
pub mod admin; | ||
pub mod email_notifications; | ||
pub mod email_verification; | ||
pub mod me; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,185 @@ | ||
use axum::{extract::Path, Json}; | ||
use chrono::{NaiveDateTime, Utc}; | ||
use crates_io_database::schema::{emails, users}; | ||
use diesel::{pg::Pg, prelude::*}; | ||
use diesel_async::{scoped_futures::ScopedFutureExt, AsyncConnection, RunQueryDsl}; | ||
use http::request::Parts; | ||
use utoipa::ToSchema; | ||
|
||
use crate::{ | ||
app::AppState, auth::AuthCheck, models::User, sql::lower, util::errors::AppResult, | ||
util::rfc3339, views::EncodableAdminUser, | ||
}; | ||
|
||
/// Find user by login, returning the admin's view of the user. | ||
/// | ||
/// Only site admins can use this endpoint. | ||
#[utoipa::path( | ||
get, | ||
path = "/api/v1/users/{user}/admin", | ||
params( | ||
("user" = String, Path, description = "Login name of the user"), | ||
), | ||
tags = ["admin", "users"], | ||
responses((status = 200, description = "Successful Response")), | ||
)] | ||
pub async fn get( | ||
state: AppState, | ||
Path(user_name): Path<String>, | ||
req: Parts, | ||
) -> AppResult<Json<EncodableAdminUser>> { | ||
let mut conn = state.db_read_prefer_primary().await?; | ||
AuthCheck::only_cookie() | ||
.require_admin() | ||
.check(&req, &mut conn) | ||
.await?; | ||
|
||
get_user( | ||
|query| query.filter(lower(users::gh_login).eq(lower(user_name))), | ||
&mut conn, | ||
) | ||
.await | ||
.map(Json) | ||
} | ||
|
||
#[derive(Deserialize, ToSchema)] | ||
pub struct LockRequest { | ||
/// The reason for locking the account. This is visible to the user. | ||
reason: String, | ||
|
||
/// When to lock the account until. If omitted, the lock will be indefinite. | ||
#[serde(default, with = "rfc3339::option")] | ||
until: Option<NaiveDateTime>, | ||
} | ||
|
||
/// Lock the given user. | ||
/// | ||
/// Only site admins can use this endpoint. | ||
#[utoipa::path( | ||
put, | ||
path = "/api/v1/users/{user}/lock", | ||
params( | ||
("user" = String, Path, description = "Login name of the user"), | ||
), | ||
request_body = LockRequest, | ||
tags = ["admin", "users"], | ||
responses((status = 200, description = "Successful Response")), | ||
)] | ||
pub async fn lock( | ||
state: AppState, | ||
Path(user_name): Path<String>, | ||
req: Parts, | ||
Json(LockRequest { reason, until }): Json<LockRequest>, | ||
) -> AppResult<Json<EncodableAdminUser>> { | ||
let mut conn = state.db_read_prefer_primary().await?; | ||
AuthCheck::only_cookie() | ||
.require_admin() | ||
.check(&req, &mut conn) | ||
.await?; | ||
|
||
// In theory, we could cook up a complicated update query that returns | ||
// everything we need to build an `EncodableAdminUser`, but that feels hard. | ||
// Instead, let's use a small transaction to get the same effect. | ||
let user = conn | ||
.transaction(|conn| { | ||
async move { | ||
let id = diesel::update(users::table) | ||
.filter(lower(users::gh_login).eq(lower(user_name))) | ||
.set(( | ||
users::account_lock_reason.eq(reason), | ||
users::account_lock_until.eq(until), | ||
)) | ||
.returning(users::id) | ||
.get_result::<i32>(conn) | ||
.await?; | ||
|
||
get_user(|query| query.filter(users::id.eq(id)), conn).await | ||
} | ||
.scope_boxed() | ||
}) | ||
.await?; | ||
|
||
Ok(Json(user)) | ||
} | ||
|
||
/// Unlock the given user. | ||
/// | ||
/// Only site admins can use this endpoint. | ||
#[utoipa::path( | ||
delete, | ||
path = "/api/v1/users/{user}/lock", | ||
params( | ||
("user" = String, Path, description = "Login name of the user"), | ||
), | ||
tags = ["admin", "users"], | ||
responses((status = 200, description = "Successful Response")), | ||
)] | ||
pub async fn unlock( | ||
state: AppState, | ||
Path(user_name): Path<String>, | ||
req: Parts, | ||
) -> AppResult<Json<EncodableAdminUser>> { | ||
let mut conn = state.db_read_prefer_primary().await?; | ||
AuthCheck::only_cookie() | ||
.require_admin() | ||
.check(&req, &mut conn) | ||
.await?; | ||
|
||
// Again, let's do this in a transaction, even though we _technically_ don't | ||
// need to. | ||
let user = conn | ||
.transaction(|conn| { | ||
// Although this is called via the `DELETE` method, this is | ||
// implemented as a soft deletion by setting the lock until time to | ||
// now, thereby allowing us to have some sense of history of whether | ||
// an account has been locked in the past. | ||
async move { | ||
let id = diesel::update(users::table) | ||
.filter(lower(users::gh_login).eq(lower(user_name))) | ||
.set(users::account_lock_until.eq(Utc::now().naive_utc())) | ||
.returning(users::id) | ||
.get_result::<i32>(conn) | ||
.await?; | ||
|
||
get_user(|query| query.filter(users::id.eq(id)), conn).await | ||
} | ||
.scope_boxed() | ||
}) | ||
.await?; | ||
|
||
Ok(Json(user)) | ||
} | ||
|
||
/// A helper to get an [`EncodableAdminUser`] based on whatever filter predicate | ||
/// is provided in the callback. | ||
/// | ||
/// It would be ill advised to do anything in `filter` other than calling | ||
/// [`QueryDsl::filter`] on the given query, but I'm not the boss of you. | ||
async fn get_user<Conn, F>(filter: F, conn: &mut Conn) -> AppResult<EncodableAdminUser> | ||
where | ||
Conn: AsyncConnection<Backend = Pg>, | ||
F: FnOnce(users::BoxedQuery<'_, Pg>) -> users::BoxedQuery<'_, Pg>, | ||
{ | ||
let query = filter(users::table.into_boxed()); | ||
|
||
let (user, verified, email, verification_sent): (User, Option<bool>, Option<String>, bool) = | ||
query | ||
.left_join(emails::table) | ||
.select(( | ||
User::as_select(), | ||
emails::verified.nullable(), | ||
emails::email.nullable(), | ||
emails::token_generated_at.nullable().is_not_null(), | ||
)) | ||
.first(conn) | ||
.await?; | ||
|
||
let verified = verified.unwrap_or(false); | ||
let verification_sent = verified || verification_sent; | ||
Ok(EncodableAdminUser::from( | ||
user, | ||
email, | ||
verified, | ||
verification_sent, | ||
)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,32 @@ | ||
--- | ||
source: src/openapi.rs | ||
expression: response.json() | ||
snapshot_kind: text | ||
--- | ||
{ | ||
"components": {}, | ||
"components": { | ||
"schemas": { | ||
"LockRequest": { | ||
"properties": { | ||
"reason": { | ||
"description": "The reason for locking the account. This is visible to the user.", | ||
"type": "string" | ||
}, | ||
"until": { | ||
"description": "When to lock the account until. If omitted, the lock will be indefinite.", | ||
"format": "date-time", | ||
"type": [ | ||
"string", | ||
"null" | ||
] | ||
} | ||
}, | ||
"required": [ | ||
"reason" | ||
], | ||
"type": "object" | ||
} | ||
} | ||
}, | ||
"info": { | ||
"contact": { | ||
"email": "[email protected]", | ||
|
@@ -1650,6 +1672,95 @@ snapshot_kind: text | |
"users" | ||
] | ||
} | ||
}, | ||
"/api/v1/users/{user}/admin": { | ||
"get": { | ||
"description": "Only site admins can use this endpoint.", | ||
"operationId": "get", | ||
"parameters": [ | ||
{ | ||
"description": "Login name of the user", | ||
"in": "path", | ||
"name": "user", | ||
"required": true, | ||
"schema": { | ||
"type": "string" | ||
} | ||
} | ||
], | ||
"responses": { | ||
"200": { | ||
"description": "Successful Response" | ||
} | ||
}, | ||
"summary": "Find user by login, returning the admin's view of the user.", | ||
"tags": [ | ||
"admin", | ||
"users" | ||
] | ||
} | ||
}, | ||
"/api/v1/users/{user}/lock": { | ||
"delete": { | ||
"description": "Only site admins can use this endpoint.", | ||
"operationId": "unlock", | ||
"parameters": [ | ||
{ | ||
"description": "Login name of the user", | ||
"in": "path", | ||
"name": "user", | ||
"required": true, | ||
"schema": { | ||
"type": "string" | ||
} | ||
} | ||
], | ||
"responses": { | ||
"200": { | ||
"description": "Successful Response" | ||
} | ||
}, | ||
"summary": "Unlock the given user.", | ||
"tags": [ | ||
"admin", | ||
"users" | ||
] | ||
}, | ||
"put": { | ||
"description": "Only site admins can use this endpoint.", | ||
"operationId": "lock", | ||
"parameters": [ | ||
{ | ||
"description": "Login name of the user", | ||
"in": "path", | ||
"name": "user", | ||
"required": true, | ||
"schema": { | ||
"type": "string" | ||
} | ||
} | ||
], | ||
"requestBody": { | ||
"content": { | ||
"application/json": { | ||
"schema": { | ||
"$ref": "#/components/schemas/LockRequest" | ||
} | ||
} | ||
}, | ||
"required": true | ||
}, | ||
"responses": { | ||
"200": { | ||
"description": "Successful Response" | ||
} | ||
}, | ||
"summary": "Lock the given user.", | ||
"tags": [ | ||
"admin", | ||
"users" | ||
] | ||
} | ||
} | ||
}, | ||
"servers": [ | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for new APIs I would prefer to avoid such "custom action" API endpoints and use a
PATCH
API instead (PATCH /api/v1/users/{user}/admin
?) like we started for versions too and also to some degree already have for users (usingPUT
unfortunately...).this will allow us to "easily" extend the functionality of this endpoint in the future instead of having to add new endpoints for basically every field we want to change.