Sign the terminal in against the back office instead of against two constants

Sign-in compared `admin@nearle.in` / `nearle123` — a compile-time const — after
a 600ms delay standing in for a network call that was never made. Two things
followed, and the second was the serious one.

Every install of a build shared one password, and changing it meant a rebuild.
Worse: because nothing was checked with the back office, the *outlet* could not
come from the sign-in. It came from a store id typed into Settings, so the till
asserted which shop it belonged to and the server took its word. One field on
one screen moved a terminal into another tenant's books.

Now a person signs in with their own back-office account and the outlet arrives
as a consequence — sealed in a signed token, checked server-side on every
request, and not editable from this device. `DemoCredentials` is gone, along
with the prefilled fields and the "Demo account" hint that printed the password
on the login screen.

The pieces:

- `PosSession` — what the back office answers with. The token is opaque on
  purpose: the till must not parse it or reason about what it appears to say.
- `SessionStore` — the whole session to the platform keystore, not SQLite. The
  token is a bearer credential and SQLite here is a file behind a shop counter.
  An expired session reads back as absent, so no caller has to remember to
  check.
- `SyncConfig.bearerToken` — one accessor rather than the same `??` at each
  call site, because the request that forgot it would be the one silently
  sending no credentials. The session beats a static API key: the key says the
  request came from our fleet, the session says which outlet it came from, and
  only the second can stop a till reaching another tenant's books.
- Restore runs in `syncBootstrapProvider` *before* the engine starts. A drain
  that began first would upload the day's bills unauthenticated. A till trades
  all day; a reboot mid-shift must not put a login screen in front of a queue.
- An outlet picker, shown only when the account genuinely reaches several. Not
  dismissable — defaulting silently to the first outlet is how a day's takings
  end up filed against the wrong shop.

Store name, address, GSTIN and phone now come down with the session and are
written on sign-in. They were compile-time constants, and on a GST invoice
those fields are a legal requirement rather than decoration.

The smoke test signs in through a fake client and inside `runAsync`: sign-in
reaches SQLite now, and real disk I/O cannot complete on a widget test's fake
clock — pumping alone leaves it suspended for ever.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Suriya
2026-08-06 15:46:59 +05:30
parent 908058038a
commit b5b2047bcd
12 changed files with 1097 additions and 93 deletions

View File

@@ -1,6 +1,8 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../data/remote/pos_auth_api.dart';
import '../../../domain/entities/pos_session.dart';
import '../../../domain/entities/store_account.dart';
/// Sign-in state for the terminal.
@@ -31,46 +33,137 @@ class AuthFailure extends AuthState {
final String message;
}
/// Store-level credentials for the unregistered build.
/// Signs the terminal in against the back office and holds the session.
///
/// Still a constant, and deliberately so: this is the *store* login, not a
/// person's, and it is replaced wholesale when the terminal is registered
/// against a real back office. Staff PINs — the credential that actually opens
/// a till drawer — are no longer here. They live hashed in the database.
class DemoCredentials {
const DemoCredentials._();
static const String email = 'admin@nearle.in';
static const String password = 'nearle123';
}
/// Validates store credentials and holds the signed-in session.
/// This used to compare against two constants compiled into the app —
/// `admin@nearle.in` / `nearle123` — with a 600ms delay standing in for a
/// network call that was never made. Two things were wrong with that, and the
/// second was the serious one:
///
/// 1. every install of a build shared one password, and changing it meant a
/// rebuild; and
/// 2. because nothing was checked with the back office, the *outlet* could not
/// come from the sign-in. It came from a store id typed into Settings — so
/// a till named its own shop and was believed, and one number changed on
/// one screen moved a terminal into another tenant's books.
///
/// Now a person signs in with their own back-office account, and the outlet
/// arrives as a consequence: sealed in a signed token, checked server-side on
/// every request, and not editable from this device.
class AuthController extends StateNotifier<AuthState> {
AuthController(this._ref) : super(const Unauthenticated());
final Ref _ref;
/// The back office's answer to the last sign-in, if there is one.
///
/// Held so the outlet picker can offer a proprietor their other shops without
/// asking for the password a second time.
PosSession? _session;
PosSession? get session => _session;
/// Restores a session saved on a previous run.
///
/// Called at start-up so a till that was rebooted mid-shift comes back
/// trading rather than showing a login screen to a queue of customers.
/// Returns false when there is nothing usable, which includes an expired
/// session — [SessionStore] treats those as absent.
Future<bool> restore() async {
final saved = await _ref.read(sessionStoreProvider).read();
if (saved == null) return false;
await _adopt(saved);
return state is Authenticated;
}
Future<bool> signIn({
required String email,
required String password,
int? locationId,
}) async {
state = const Authenticating();
// Stand-in for the network round trip.
await Future<void>.delayed(const Duration(milliseconds: 600));
final terminal = _ref.read(terminalIdentityProvider);
final normalised = email.trim().toLowerCase();
if (normalised != DemoCredentials.email) {
state = const AuthFailure('No store is registered against that email.');
final PosSession session;
try {
session = await _ref.read(posAuthApiProvider).login(
authname: email,
password: password,
terminalId: terminal.code,
deviceId: terminal.deviceId,
locationId: locationId,
);
} on PosAuthException catch (e) {
state = AuthFailure(e.message);
return false;
} on Object {
state = const AuthFailure(
'Sign-in failed for an unexpected reason. Please try again.',
);
return false;
}
if (password != DemoCredentials.password) {
state = const AuthFailure('Incorrect password. Please try again.');
return false;
}
await _ref.read(sessionStoreProvider).write(session);
await _adopt(session);
return state is Authenticated;
}
/// Moves this terminal to another of the signed-in account's outlets.
///
/// A fresh sign-in rather than a local switch, because the outlet is inside
/// the signed token: the back office has to issue a new one, and re-checking
/// entitlement at that moment is the point. Requires the password again,
/// which is correct — moving a till between shops changes whose books it
/// writes to.
Future<bool> switchOutlet({
required String password,
required int locationId,
}) async {
final current = _session;
if (current == null) return false;
return signIn(
email: current.email.isNotEmpty ? current.email : current.fullName,
password: password,
locationId: locationId,
);
}
/// Adopts a session: points the terminal at its outlet, then opens it.
///
/// Order matters. The store id and token are written *before* the catalogue
/// or any uplink can run, so a terminal can never spend even one request
/// pointed at the outlet it had yesterday while claiming to be signed in as
/// today's.
Future<void> _adopt(PosSession session) async {
_session = session;
await _ref.read(localStoreProvider).identityStore.rename(
storeId: session.storeId,
);
_ref.invalidate(terminalIdentityProvider);
_ref.read(syncConfigProvider.notifier).state =
_ref.read(syncConfigProvider).copyWith(
storeId: session.storeId,
sessionToken: session.token,
);
// Store details for the receipt come from the back office now, not from
// constants compiled into the build. A GSTIN is a legal requirement on a
// tax invoice; it should not need a rebuild to correct.
await _ref.read(storeRepositoryProvider).save(
name: session.locationName.isNotEmpty
? session.locationName
: session.tenantName,
address: session.address,
gstin: session.gstin,
phone: session.phone,
);
_ref.invalidate(storeAccountProvider);
final store = await _ref.read(storeAccountProvider.future);
final staff = store.staff;
@@ -78,7 +171,7 @@ class AuthController extends StateNotifier<AuthState> {
state = const AuthFailure(
'This terminal has no staff accounts. Reinstall to seed them.',
);
return false;
return;
}
// The first admin, or whoever is there. A person switches to their own
@@ -89,7 +182,6 @@ class AuthController extends StateNotifier<AuthState> {
);
state = Authenticated(store: store, user: opener);
return true;
}
/// Switches the active operator, checking their PIN.
@@ -130,8 +222,18 @@ class AuthController extends StateNotifier<AuthState> {
/// answers with, never a catalogue instance carried over from this
/// session — so the local product table is dropped before the session
/// itself is.
///
/// The token goes with it, from the keystore and from the live configuration
/// both. Leaving it in place would let a signed-out terminal keep uploading
/// as the shop that signed in this morning.
Future<void> signOut() async {
await _ref.read(localStoreProvider).clearCatalogue();
await _ref.read(sessionStoreProvider).clear();
_ref.read(syncConfigProvider.notifier).state =
_ref.read(syncConfigProvider).copyWith(sessionToken: '');
_session = null;
state = const Unauthenticated();
}

View File

@@ -9,6 +9,7 @@ import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/validators.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../domain/entities/pos_session.dart';
import '../providers/auth_controller.dart';
/// Store sign-in. The terminal shows this until a valid account is entered.
@@ -21,8 +22,8 @@ class LoginScreen extends ConsumerStatefulWidget {
class _LoginScreenState extends ConsumerState<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _email = TextEditingController(text: DemoCredentials.email);
final _password = TextEditingController(text: DemoCredentials.password);
final _email = TextEditingController();
final _password = TextEditingController();
bool _obscure = true;
bool _rememberTerminal = true;
@@ -38,12 +39,42 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
FocusScope.of(context).unfocus();
if (!(_formKey.currentState?.validate() ?? false)) return;
final ok = await ref.read(authControllerProvider.notifier).signIn(
final auth = ref.read(authControllerProvider.notifier);
var ok = await auth.signIn(
email: _email.text,
password: _password.text,
);
if (!ok || !mounted) return;
// A proprietor with several shops signs in once and then says which counter
// this terminal is standing at. The back office has already decided which
// outlets they may reach, so this is a choice among those — never a free
// text field, which is what the old Settings store id amounted to.
final session = auth.session;
if (session != null && session.hasChoiceOfOutlet) {
final chosen = await showDialog<PosOutlet>(
context: context,
// Not dismissable: a terminal has to be standing somewhere, and
// defaulting silently to the first outlet is how a day's takings end up
// filed against the wrong shop.
barrierDismissible: false,
builder: (_) => _OutletPicker(session: session),
);
if (chosen == null || !mounted) return;
if (chosen.locationId != session.locationId) {
ok = await auth.signIn(
email: _email.text,
password: _password.text,
locationId: chosen.locationId,
);
if (!ok || !mounted) return;
}
}
if (ok && mounted) context.go(AppRoutes.pos);
if (mounted) context.go(AppRoutes.pos);
}
@override
@@ -432,15 +463,6 @@ class _FormPanel extends ConsumerWidget {
onPressed: onSubmit,
),
const SizedBox(height: AppSpacing.xl),
_DemoHint(
onFill: busy
? null
: () {
email.text = DemoCredentials.email;
password.text = DemoCredentials.password;
},
),
const SizedBox(height: AppSpacing.xxl),
Center(
@@ -483,58 +505,99 @@ class _Label extends StatelessWidget {
}
}
class _DemoHint extends StatelessWidget {
const _DemoHint({this.onFill});
/// Asks which of the signed-in account's outlets this terminal is standing in.
///
/// Only shown when there is genuinely a choice. A shop manager pinned to one
/// location never sees it, which is the common case — this is for a proprietor
/// whose account reaches several shops.
///
/// The list comes from the back office and cannot be typed into. That is the
/// whole difference from what this replaced: the outlet used to be a store id
/// entered in Settings, so a till asserted which shop it belonged to. Here it
/// picks from what the account is already entitled to, and the choice is
/// re-checked server-side when the new session is issued.
class _OutletPicker extends StatelessWidget {
const _OutletPicker({required this.session});
final VoidCallback? onFill;
final PosSession session;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.primarySurface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.primaryBorder),
return AlertDialog(
backgroundColor: AppColors.surface,
shape: RoundedRectangleBorder(borderRadius: AppRadius.brMd),
title: const Text(
'Which outlet is this terminal at?',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.info_outline_rounded,
size: 17, color: AppColors.primary,),
const SizedBox(width: AppSpacing.sm),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Demo account',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: AppColors.primary,
),
content: SizedBox(
width: 380,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.md),
child: Text(
'Signed in as ${session.fullName.isNotEmpty ? session.fullName : session.email}'
' · ${session.tenantName}',
style: const TextStyle(
fontSize: 12.5,
color: AppColors.textSecondary,
),
SizedBox(height: 2),
SelectableText(
'${DemoCredentials.email} · ${DemoCredentials.password}',
style: TextStyle(
fontSize: 12,
color: AppColors.textSecondary,
),
),
],
),
),
),
TextButton(
onPressed: onFill,
style: TextButton.styleFrom(
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm),
Flexible(
child: ListView.separated(
shrinkWrap: true,
itemCount: session.outlets.length,
separatorBuilder: (_, __) =>
const SizedBox(height: AppSpacing.xs),
itemBuilder: (context, i) {
final outlet = session.outlets[i];
final isCurrent = outlet.locationId == session.locationId;
return ListTile(
dense: true,
shape: RoundedRectangleBorder(
borderRadius: AppRadius.brSm,
side: BorderSide(
color: isCurrent
? AppColors.primaryBorder
: AppColors.border,
),
),
tileColor:
isCurrent ? AppColors.primarySurface : AppColors.surface,
title: Text(
outlet.locationName.isNotEmpty
? outlet.locationName
: 'Outlet ${outlet.locationId}',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
// The numeric id is shown deliberately. It is what appears
// in the back office, on a support call and in every log
// line, so a person can match what they are looking at.
subtitle: Text(
[
'ID ${outlet.locationId}',
if (outlet.city.isNotEmpty) outlet.city,
].join(' · '),
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
),
),
onTap: () => Navigator.of(context).pop(outlet),
);
},
),
),
child: const Text('Fill', style: TextStyle(fontSize: 12.5)),
),
],
],
),
),
);
}