forge
Explore
Log in

Don't you dare go Hollow

Blank search query lists the whole role

Browse files at this commit

f658a4e04ab47e6256ec6ffe0a0228e41b939ee4Ahmet Kaan GümüşParent: 7864d0a
  • fix
    • blank search query lists the whole role
Show full message
🐛 fix(users): blank search query lists the whole role

/users/search?q=&role=student was a 400, but the frontend pickers use
exactly that shape as their initial unfiltered listing. A blank q now
skips the fragment clause, so blank + role lists everyone in that role
(still ordered by username, still paged). Blank q without a role stays
a 400 — an unscoped full dump was never a search.
src/domain/user.rsmodified+20 -12
@@ -303,28 +303,36 @@ impl User {
303 303
304 /// Case-insensitive fragment search over username, name, and surname —304 /// Case-insensitive fragment search over username, name, and surname —
305 /// backs the user pickers. `role` narrows to one role (e.g. only students305 /// backs the user pickers. `role` narrows to one role (e.g. only students
306- /// for an enroll picker); `None` searches everyone. Returns every match,306+ /// for an enroll picker); `None` searches everyone. A blank `query`
307- /// ordered by username; the HTTP layer pages the result like any other list307+ /// matches everyone, so blank + `role` is a role-scoped listing. Returns
308- /// (no built-in cap — an over-broad fragment is windowed by `?limit`).308+ /// every match, ordered by username; the HTTP layer pages the result like
309+ /// any other list (no built-in cap — an over-broad fragment is windowed
310+ /// by `?limit`).
309 pub async fn search(311 pub async fn search(
310 query: &str,312 query: &str,
311 role: Option<Role>,313 role: Option<Role>,
312 db: &Database,314 db: &Database,
313 ) -> Result<Vec<User>, AppError> {315 ) -> Result<Vec<User>, AppError> {
314 let needle = query.trim().to_lowercase();316 let needle = query.trim().to_lowercase();
315- let role_clause = if role.is_some() {317+ let mut clauses = Vec::new();
316- "AND role = $role"318+ if !needle.is_empty() {
319+ clauses.push(
320+ "(string::lowercase(username) CONTAINS $q \
321+ OR string::lowercase(name ?? '') CONTAINS $q \
322+ OR string::lowercase(surname ?? '') CONTAINS $q)",
323+ );
324+ }
325+ if role.is_some() {
326+ clauses.push("role = $role");
327+ }
328+ let where_clause = if clauses.is_empty() {
329+ "true".to_string()
317 } else {330 } else {
318- ""331+ clauses.join(" AND ")
319 };332 };
320 let mut query = db333 let mut query = db
321 .query(format!(334 .query(format!(
322- "SELECT * FROM user WHERE \335+ "SELECT * FROM user WHERE {where_clause} ORDER BY username"
323- (string::lowercase(username) CONTAINS $q \
324- OR string::lowercase(name ?? '') CONTAINS $q \
325- OR string::lowercase(surname ?? '') CONTAINS $q) \
326- {role_clause} \
327- ORDER BY username"
328 ))336 ))
329 .bind(("q", needle));337 .bind(("q", needle));
330 if let Some(role) = role {338 if let Some(role) = role {
src/web/users.rsmodified+9 -8
@@ -133,7 +133,8 @@ async fn apply_preferences(
133 133
134 #[derive(Deserialize, IntoParams)]134 #[derive(Deserialize, IntoParams)]
135 struct SearchUsers {135 struct SearchUsers {
136- /// Case-insensitive fragment of a username, name, or surname.136+ /// Case-insensitive fragment of a username, name, or surname. May be
137+ /// blank when `role` is given — that lists the whole role.
137 q: String,138 q: String,
138 /// Restrict matches to one role: `student`, `teacher`, `manager`, or139 /// Restrict matches to one role: `student`, `teacher`, `manager`, or
139 /// `admin`. Omit to search every role.140 /// `admin`. Omit to search every role.
@@ -148,10 +149,10 @@ struct SearchUsers {
148 149
149 /// Find users by username or name — backs the pickers (enroll, grade, mark150 /// Find users by username or name — backs the pickers (enroll, grade, mark
150 /// attendance). Requires teacher+. `role` narrows to one role (e.g.151 /// attendance). Requires teacher+. `role` narrows to one role (e.g.
151-/// `role=student` for an enroll picker). Paged via `?limit=&offset=` like the152+/// `role=student` for an enroll picker); a blank `q` with a `role` lists
152-/// other lists (omit `limit` for every match); returns a153+/// everyone in that role. Paged via `?limit=&offset=` like the other lists
153-/// `{items, total, limit, offset}` envelope carrying only id/username/display154+/// (omit `limit` for every match); returns a `{items, total, limit, offset}`
154-/// name — no contact details.155+/// envelope carrying only id/username/display name — no contact details.
155 #[utoipa::path(156 #[utoipa::path(
156 get,157 get,
157 path = "/search",158 path = "/search",
@@ -160,7 +161,7 @@ struct SearchUsers {
160 params(SearchUsers),161 params(SearchUsers),
161 responses(162 responses(
162 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),163 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
163- (status = 400, description = "Empty query, unknown role, or invalid limit/offset", body = ErrorResponse),164+ (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse),
164 (status = 401, description = "Not authenticated", body = ErrorResponse),165 (status = 401, description = "Not authenticated", body = ErrorResponse),
165 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),166 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
166 ),167 ),
@@ -170,10 +171,10 @@ async fn search_users(
170 _teacher: RequireTeacher,171 _teacher: RequireTeacher,
171 Query(req): Query<SearchUsers>,172 Query(req): Query<SearchUsers>,
172 ) -> Result<Json<Page<PersonRef>>, AppError> {173 ) -> Result<Json<Page<PersonRef>>, AppError> {
173- if req.q.trim().is_empty() {174+ if req.q.trim().is_empty() && req.role.is_none() {
174 return Err(AppError::Validation(ValidationError::Invalid {175 return Err(AppError::Validation(ValidationError::Invalid {
175 field: "q",176 field: "q",
176- reason: "must not be empty",177+ reason: "must not be empty unless role is given",
177 }));178 }));
178 }179 }
179 let (limit, offset) = PageParams {180 let (limit, offset) = PageParams {
tests/pagination.rsmodified+23 -1
@@ -180,6 +180,28 @@ async fn user_search_is_paged_not_capped() {
180 assert_eq!(180 assert_eq!(
181 res.status,181 res.status,
182 StatusCode::BAD_REQUEST,182 StatusCode::BAD_REQUEST,
183- "blank q is still a 400"183+ "blank q without a role is still a 400"
184 );184 );
185+
186+ // Blank q scoped to a role is a listing, not an error.
187+ let res = send(
188+ &app,
189+ "GET",
190+ "/users/search?q=&role=student",
191+ Some(&teacher),
192+ None,
193+ )
194+ .await;
195+ assert_eq!(res.status, StatusCode::OK);
196+ assert_eq!(total(&res.body), 12, "blank q + role lists the whole role");
197+ let res = send(
198+ &app,
199+ "GET",
200+ "/users/search?q=&role=teacher",
201+ Some(&teacher),
202+ None,
203+ )
204+ .await;
205+ assert_eq!(res.status, StatusCode::OK);
206+ assert_eq!(total(&res.body), 1, "role scope excludes the students");
185 }207 }