Login with the login name alone (DOMAIN.login still works); shared Pager with first/last buttons and Arabic labels in all grids

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-24 10:45:27 +03:00
parent 0819427bdf
commit 18d74d1b53
9 changed files with 124 additions and 29 deletions

View File

@ -45,7 +45,8 @@ public sealed class AuthService(
{
await loginValidator.ValidateAndThrowAsync(request, ct);
var throttleKey = request.UserName.Trim().ToLowerInvariant();
// one budget per account, however the name is typed (login alone, or with a legacy DOMAIN. prefix, spaces and dots included)
var throttleKey = LoginName.Parse(request.UserName).Login;
if (throttle.BlockedFor(throttleKey, client.IpAddress) is { } wait)
throw new TooManyAttemptsException("TOO_MANY_ATTEMPTS", string.Format(TooManyAttemptsMessage, Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes))));
@ -64,16 +65,23 @@ public sealed class AuthService(
private async Task<LoginResponse> SignInAsync(LoginRequest request, ClientInfo client, CancellationToken ct)
{
var parts = request.UserName.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length != 2)
throw Invalid();
// the user types just the login: its domain is the one of the active user (a typed "DOMAIN.login" is still honoured). The password
// hash depends on the domain, so every active domain of the login is tried until the password matches.
var (typedDomain, login) = LoginName.Parse(request.UserName);
if (login.Length == 0) throw Invalid();
IReadOnlyList<string> domains = typedDomain is not null ? [typedDomain] : await repository.GetActiveDomainsAsync(login, ct);
var domain = parts[0];
var login = parts[1].ToLowerInvariant();
var candidates = PasswordHasher.Candidates(domain, login, request.Password);
var found = await repository.FindActiveUserByPasswordAsync(login, domain, candidates,
requireActiveCompany: PasswordHasher.IsAseza(domain), ct) ?? throw Invalid();
UserLoginRow? found = null;
var domain = string.Empty;
foreach (var candidateDomain in domains)
{
found = await repository.FindActiveUserByPasswordAsync(login, candidateDomain, PasswordHasher.Candidates(candidateDomain, login, request.Password),
requireActiveCompany: PasswordHasher.IsAseza(candidateDomain), ct);
if (found is null) continue;
domain = candidateDomain;
break;
}
if (found is null) throw Invalid();
var roleCode = found.RoleCode ?? string.Empty;

View File

@ -48,6 +48,9 @@ public interface IAuthRepository
Task<UserLoginRow?> FindActiveUserByPasswordAsync(string login, string domain, IReadOnlyList<string> passwordCandidates,
bool requireActiveCompany, CancellationToken ct = default);
/// <summary>The domains (NTPUSERS.DOMAINNAME) of the ACTIVE users with this login: lets a user sign in with the login alone.</summary>
Task<IReadOnlyList<string>> GetActiveDomainsAsync(string login, CancellationToken ct = default);
/// <summary>GateEventsFactory.CheckAuthorization: active UTT (booth) row for the login.</summary>
Task<bool> HasActiveBoothAsync(string login, CancellationToken ct = default);

View File

@ -0,0 +1,19 @@
namespace NTP.Application.Auth;
/// <summary>
/// The user name typed on the sign-in page. Users type just their login; the legacy "DOMAIN.login" spelling (for example ASEZA.50034)
/// is still accepted, in which case the domain is taken from it instead of being looked up.
/// </summary>
public static class LoginName
{
/// <summary>
/// <c>Domain</c> is null when only a login was typed. <c>Login</c> is lower case and trimmed. A name with exactly two dot-separated
/// parts is "DOMAIN.login"; anything else is one login (no login in NTPUSERS contains a dot).
/// </summary>
public static (string? Domain, string Login) Parse(string userName)
{
var text = (userName ?? string.Empty).Trim();
var parts = text.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
return parts.Length == 2 ? (parts[0], parts[1].ToLowerInvariant()) : (null, text.ToLowerInvariant());
}
}

View File

@ -68,6 +68,13 @@ internal sealed class AuthRepository(INtpDbSession session, IDbSession primarySe
return QueryFirstAsync<UserLoginRow>(sql.ToString(), p, ct);
}
public Task<IReadOnlyList<string>> GetActiveDomainsAsync(string login, CancellationToken ct = default) =>
QueryAsync<string>("""
SELECT DISTINCT DOMAINNAME FROM NTPUSERS
WHERE upper(LOGIN) = upper(:Login) AND STATUS = 1 AND DOMAINNAME IS NOT NULL
ORDER BY DOMAINNAME
""", new { Login = login }, ct);
public async Task<bool> HasActiveBoothAsync(string login, CancellationToken ct = default) =>
await Primary.ScalarAsync<long>("""
SELECT COUNT(*) FROM UTT

View File

@ -38,6 +38,33 @@ public class PasswordHasherTests
}
}
/// <summary>Sign in with the login alone; the legacy DOMAIN.login spelling still works.</summary>
public class LoginNameTests
{
[Theory]
[InlineData("50034", null, "50034")]
[InlineData(" GTOM1 ", null, "gtom1")]
[InlineData("Samer", null, "samer")]
[InlineData("ASEZA.50034", "ASEZA", "50034")]
[InlineData("ASEZA. 50034", "ASEZA", "50034")]
[InlineData("ASEZA .50034", "ASEZA", "50034")]
[InlineData("ASEZA..50034", "ASEZA", "50034")]
[InlineData("GN.GTOM1", "GN", "gtom1")]
public void Login_alone_or_domain_dot_login(string typed, string? domain, string login)
=> Assert.Equal((domain, login), LoginName.Parse(typed));
[Theory]
[InlineData("a.b.c")]
[InlineData("...")]
public void Anything_else_is_one_login_that_will_not_match(string typed)
=> Assert.Null(LoginName.Parse(typed).Domain);
[Fact]
public void Every_spelling_of_one_account_gives_the_same_throttle_login()
=> Assert.Equal(1, new[] { "ASEZA.50034", "ASEZA. 50034", "ASEZA..50034", "aseza.50034", "50034", " 50034 " }
.Select(n => LoginName.Parse(n).Login).Distinct().Count());
}
public class ClaimsMappingTests
{
private static readonly AuthenticatedUser Sample = new(

View File

@ -3,7 +3,7 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useLocation, useSearchParams } from 'react-router-dom';
import {
alpha, Alert, Badge, Box, Button, Chip, IconButton, ListItemIcon, ListItemText, Menu, MenuItem, Paper, Stack,
Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow, Tooltip, Typography, useTheme,
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tooltip, Typography, useTheme,
} from '@mui/material';
import CheckIcon from '@mui/icons-material/Check';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
@ -14,6 +14,7 @@ import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined';
import { api, ApiError, type PagedResult } from '@/api/client';
import { EmptyState } from '@/components/EmptyState';
import { LoadingBanner } from '@/components/LoadingBanner';
import { Pager } from '@/components/Pager';
import { SectionPaper } from '@/components/SectionPaper';
import { StatusChip } from '@/components/StatusChip';
import { formatDate, formatDateTime, formatNumber, getPath } from '@/components/meta/format';
@ -35,7 +36,7 @@ export interface DataGridProps<T> {
}
export function DataGrid<T>({ meta }: DataGridProps<T>) {
const { t, tr, lang, dir } = useUi();
const { t, tr, lang } = useUi();
const { langReady } = useLanguage();
const [sp, setSp] = useSearchParams();
const location = useLocation();
@ -266,18 +267,15 @@ export function DataGrid<T>({ meta }: DataGridProps<T>) {
</TableBody>
</Table>
</TableContainer>
<TablePagination
component="div"
{/* translated labels and first / last page buttons come from the shared pager; MUI already mirrors the arrow icons in RTL */}
<Pager
count={total}
page={Math.min(page - 1, Math.max(0, Math.ceil(total / pageSize) - 1))}
rowsPerPage={pageSize}
rowsPerPageOptions={[10, 25, 50, 100]}
onPageChange={(_, p) => write(active, p + 1, pageSize)}
onRowsPerPageChange={(e) => write(active, 1, Number(e.target.value))}
labelRowsPerPage={t('grid.rowsPerPage')}
labelDisplayedRows={({ from, to, count }) => t('grid.displayedRows', { from, to, count })}
// footer sits at the physical left in both directions; MUI already mirrors the arrow icons in RTL
sx={{ borderTop: 1, borderColor: 'divider', '.MuiTablePagination-spacer': { display: 'none' }, '.MuiTablePagination-toolbar': { flexWrap: 'wrap', justifyContent: dir === 'rtl' ? 'flex-end' : 'flex-start' } }}
sx={{ borderTop: 1, borderColor: 'divider' }}
/>
</>
)}

View File

@ -0,0 +1,36 @@
import type { ChangeEvent } from 'react';
import { TablePagination, type SxProps, type Theme } from '@mui/material';
import { useUi } from '@/i18n/useUi';
export interface PagerProps {
count: number;
/** zero based, as MUI wants it */
page: number;
rowsPerPage: number;
rowsPerPageOptions?: number[];
onPageChange: (event: unknown, page: number) => void;
onRowsPerPageChange?: (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
sx?: SxProps<Theme>;
}
/**
* The pager under every table and grid: Arabic labels ("عدد الصفوف", "1-10 من 250") and buttons for the first and the last page next
* to previous / next. One place, so a list or a log table never shows the English default text.
*/
export function Pager({ sx, ...props }: PagerProps) {
const { t, dir } = useUi();
return (
<TablePagination
component="div"
showFirstButton
showLastButton
labelRowsPerPage={t('grid.rowsPerPage')}
labelDisplayedRows={({ from, to, count }) => t('grid.displayedRows', { from, to, count })}
{...props}
sx={[
{ '.MuiTablePagination-spacer': { display: 'none' }, '.MuiTablePagination-toolbar': { flexWrap: 'wrap', justifyContent: dir === 'rtl' ? 'flex-end' : 'flex-start' } },
...(Array.isArray(sx) ? sx : sx ? [sx] : []),
]}
/>
);
}

View File

@ -1,8 +1,7 @@
import { useMemo, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
Alert, Box, Button, Collapse, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow, Typography,
useTheme,
Alert, Box, Button, Collapse, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import BlockIcon from '@mui/icons-material/Block';
@ -14,6 +13,7 @@ import { DataGrid, gridReturnUrl } from '@/components/DataGrid';
import { LoadingBanner } from '@/components/LoadingBanner';
import { MetaForm } from '@/components/MetaForm';
import { PageHeader } from '@/components/PageHeader';
import { Pager } from '@/components/Pager';
import { SectionPaper } from '@/components/SectionPaper';
import { SectionTitle } from '@/components/SectionTitle';
import { StatusChip } from '@/components/StatusChip';
@ -75,7 +75,6 @@ export function CardsPage() {
/** Movements of a card (legacy REFINERY_CARDS_logGrid, 5 per page). Collapsed until the title is clicked; nothing is fetched before. */
function CardLog({ id }: { id: number }) {
const { t, lang } = useFeatureUi(strings);
const dir = useTheme().direction;
const [open, setOpen] = useState(false);
const [page, setPage] = useState(0);
const [pageSize, setPageSize] = useState(5);
@ -130,12 +129,9 @@ function CardLog({ id }: { id: number }) {
</TableBody>
</Table>
</TableContainer>
<TablePagination
component="div" count={q.data?.totalCount ?? 0} page={page} rowsPerPage={pageSize} rowsPerPageOptions={[5, 10, 25]}
<Pager
count={q.data?.totalCount ?? 0} page={page} rowsPerPage={pageSize} rowsPerPageOptions={[5, 10, 25]}
onPageChange={(_, p) => setPage(p)} onRowsPerPageChange={(e) => { setPageSize(Number(e.target.value)); setPage(0); }}
labelRowsPerPage={t('grid.rowsPerPage')}
labelDisplayedRows={({ from, to, count }) => t('grid.displayedRows', { from, to, count })}
sx={{ '.MuiTablePagination-spacer': { display: 'none' }, '.MuiTablePagination-toolbar': { flexWrap: 'wrap', justifyContent: dir === 'rtl' ? 'flex-end' : 'flex-start' } }}
/>
</>
)}

View File

@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Paper, Stack, Table, TableBody, TableCell, TableContainer,
TableHead, TablePagination, TableRow, Tooltip, Typography,
TableHead, TableRow, Tooltip, Typography,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import BlockIcon from '@mui/icons-material/Block';
@ -15,6 +15,7 @@ import { DataGrid, gridReturnUrl } from '@/components/DataGrid';
import { LoadingBanner } from '@/components/LoadingBanner';
import { MetaForm } from '@/components/MetaForm';
import { PageHeader } from '@/components/PageHeader';
import { Pager } from '@/components/Pager';
import { SectionPaper } from '@/components/SectionPaper';
import { SectionTitle } from '@/components/SectionTitle';
import { StatusChip } from '@/components/StatusChip';
@ -166,8 +167,8 @@ function WalletLog({ id }: { id: number }) {
</TableBody>
</Table>
</TableContainer>
<TablePagination
component="div" count={q.data?.totalCount ?? 0} page={page} rowsPerPage={pageSize} rowsPerPageOptions={[5, 10, 25]}
<Pager
count={q.data?.totalCount ?? 0} page={page} rowsPerPage={pageSize} rowsPerPageOptions={[5, 10, 25]}
onPageChange={(_, p) => setPage(p)} onRowsPerPageChange={(e) => { setPageSize(Number(e.target.value)); setPage(0); }}
/>
</>