diff --git a/src/NTP.Application/Auth/AuthService.cs b/src/NTP.Application/Auth/AuthService.cs index e217ba9..84bb14b 100644 --- a/src/NTP.Application/Auth/AuthService.cs +++ b/src/NTP.Application/Auth/AuthService.cs @@ -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 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 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; diff --git a/src/NTP.Application/Auth/IAuthRepository.cs b/src/NTP.Application/Auth/IAuthRepository.cs index b804226..534f32d 100644 --- a/src/NTP.Application/Auth/IAuthRepository.cs +++ b/src/NTP.Application/Auth/IAuthRepository.cs @@ -48,6 +48,9 @@ public interface IAuthRepository Task FindActiveUserByPasswordAsync(string login, string domain, IReadOnlyList passwordCandidates, bool requireActiveCompany, CancellationToken ct = default); + /// The domains (NTPUSERS.DOMAINNAME) of the ACTIVE users with this login: lets a user sign in with the login alone. + Task> GetActiveDomainsAsync(string login, CancellationToken ct = default); + /// GateEventsFactory.CheckAuthorization: active UTT (booth) row for the login. Task HasActiveBoothAsync(string login, CancellationToken ct = default); diff --git a/src/NTP.Application/Auth/LoginName.cs b/src/NTP.Application/Auth/LoginName.cs new file mode 100644 index 0000000..b35ec59 --- /dev/null +++ b/src/NTP.Application/Auth/LoginName.cs @@ -0,0 +1,19 @@ +namespace NTP.Application.Auth; + +/// +/// 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. +/// +public static class LoginName +{ + /// + /// Domain is null when only a login was typed. Login 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). + /// + 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()); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs index 172114f..9759c42 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs @@ -68,6 +68,13 @@ internal sealed class AuthRepository(INtpDbSession session, IDbSession primarySe return QueryFirstAsync(sql.ToString(), p, ct); } + public Task> GetActiveDomainsAsync(string login, CancellationToken ct = default) => + QueryAsync(""" + 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 HasActiveBoothAsync(string login, CancellationToken ct = default) => await Primary.ScalarAsync(""" SELECT COUNT(*) FROM UTT diff --git a/tests/NTP.Tests/AuthTests.cs b/tests/NTP.Tests/AuthTests.cs index 3dbc94e..e8831c6 100644 --- a/tests/NTP.Tests/AuthTests.cs +++ b/tests/NTP.Tests/AuthTests.cs @@ -38,6 +38,33 @@ public class PasswordHasherTests } } +/// Sign in with the login alone; the legacy DOMAIN.login spelling still works. +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( diff --git a/web/src/components/DataGrid/DataGrid.tsx b/web/src/components/DataGrid/DataGrid.tsx index a848c36..700aaa9 100644 --- a/web/src/components/DataGrid/DataGrid.tsx +++ b/web/src/components/DataGrid/DataGrid.tsx @@ -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 { } export function DataGrid({ meta }: DataGridProps) { - 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({ meta }: DataGridProps) { - 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' }} /> )} diff --git a/web/src/components/Pager.tsx b/web/src/components/Pager.tsx new file mode 100644 index 0000000..17cc6bd --- /dev/null +++ b/web/src/components/Pager.tsx @@ -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) => void; + sx?: SxProps; +} + +/** + * 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 ( + 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] : []), + ]} + /> + ); +} diff --git a/web/src/features/refinery/cards/pages.tsx b/web/src/features/refinery/cards/pages.tsx index 2bf72b8..02b4877 100644 --- a/web/src/features/refinery/cards/pages.tsx +++ b/web/src/features/refinery/cards/pages.tsx @@ -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 }) { - 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' } }} /> )} diff --git a/web/src/features/refinery/wallets/pages.tsx b/web/src/features/refinery/wallets/pages.tsx index ac00b2f..516a825 100644 --- a/web/src/features/refinery/wallets/pages.tsx +++ b/web/src/features/refinery/wallets/pages.tsx @@ -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 }) { - setPage(p)} onRowsPerPageChange={(e) => { setPageSize(Number(e.target.value)); setPage(0); }} />