Files
nearle_pos/lib/presentation/auth/providers/auth_controller.dart
Suriya e17937e8f1 Move staff PINs out of the shipped binary into hashed database rows
Three StaffUser constants carried plaintext PINs (1234/2345/3456) in
auth_controller.dart. Every build shipped every till's credentials, readable
by anyone who unzipped the APK. Across 100 deployed devices that is one
credential, not a hundred.

- Schema v5 adds a staff table. Only a PBKDF2-HMAC-SHA256 hash and a per-user
  random salt are stored; the PIN itself exists nowhere, including there.
  12,000 iterations, tuned so one sign-in is imperceptible while working
  through all 10,000 four-digit PINs against a stolen database takes ~15
  minutes per account instead of milliseconds.
- Verification is constant-time. String == returns at the first differing
  byte, and that timing leaks how much of a guess was right.
- StaffUser no longer has a pin field at all, so the credential cannot drift
  back into memory, into widgets, or into a const declaration.
- Weak PINs are refused: under four digits, non-numeric, repeated digits, and
  sequences. Two staff cannot share a PIN — the till identifies a cashier by
  PIN alone, so a shared one would attribute bills to whichever row was
  checked first.
- The last admin cannot be demoted or deactivated. A till with no admin cannot
  be administered, including to appoint one, and recovering means editing the
  database by hand.
- Staff are deactivated, never deleted, so bills already rung keep naming a
  real person.

Seed accounts are now 4821/5093/6274 rather than 1234/2345/3456 — the weak-PIN
rule refuses the old ones, and a default the rule itself would reject is not a
defensible default. All three are flagged must-change-pin so they get a shop
trading on day one without becoming permanent.

Store details are now editable data, not compile-time constants. Name,
address, GSTIN and phone persist to the database and are read back rather than
falling through to the build's constants, which would silently undo a failed
save. GSTIN is format-validated including the state code — it prints on every
invoice as a legal requirement, so a typo is a compliance problem across
hundreds of bills before anyone notices.

Tests: 141 -> 160. Includes a test that reads every column of every staff row
and asserts no seed PIN appears anywhere in the database.

Migration test now asserts v5 and that an upgraded terminal comes up with the
staff table present but empty — seeding is the store's job on first open, so
an existing shop is never handed accounts it did not create.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 13:00:12 +05:30

157 lines
4.5 KiB
Dart

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../domain/entities/store_account.dart';
/// Sign-in state for the terminal.
sealed class AuthState {
const AuthState();
bool get isAuthenticated => this is Authenticated;
}
class Unauthenticated extends AuthState {
const Unauthenticated();
}
class Authenticating extends AuthState {
const Authenticating();
}
class Authenticated extends AuthState {
const Authenticated({required this.store, required this.user});
final StoreAccount store;
final StaffUser user;
}
class AuthFailure extends AuthState {
const AuthFailure(this.message);
final String message;
}
/// Store-level credentials for the unregistered build.
///
/// 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.
class AuthController extends StateNotifier<AuthState> {
AuthController(this._ref) : super(const Unauthenticated());
final Ref _ref;
Future<bool> signIn({
required String email,
required String password,
}) async {
state = const Authenticating();
// Stand-in for the network round trip.
await Future<void>.delayed(const Duration(milliseconds: 600));
final normalised = email.trim().toLowerCase();
if (normalised != DemoCredentials.email) {
state = const AuthFailure('No store is registered against that email.');
return false;
}
if (password != DemoCredentials.password) {
state = const AuthFailure('Incorrect password. Please try again.');
return false;
}
final store = await _ref.read(storeAccountProvider.future);
final staff = store.staff;
if (staff.isEmpty) {
state = const AuthFailure(
'This terminal has no staff accounts. Reinstall to seed them.',
);
return false;
}
// The first admin, or whoever is there. A person switches to their own
// account at the till.
final opener = staff.firstWhere(
(s) => s.role == StaffRole.admin,
orElse: () => staff.first,
);
state = Authenticated(store: store, user: opener);
return true;
}
/// Switches the active operator, checking their PIN.
///
/// Every bill is stamped with whoever is active, so this is the boundary that
/// decides who a sale is attributed to — it cannot be a bare selection from a
/// list.
Future<bool> switchUser(String pin) async {
final current = state;
if (current is! Authenticated) return false;
final store = _ref.read(localStoreProvider);
final user = await store.staff.authenticate(pin);
if (user == null) return false;
state = Authenticated(store: current.store, user: user);
return true;
}
/// Re-reads the store after staff or details change, keeping the session.
Future<void> refreshStore() async {
final current = state;
if (current is! Authenticated) return;
_ref.invalidate(storeAccountProvider);
final store = await _ref.read(storeAccountProvider.future);
final me = store.staff.where((s) => s.id == current.user.id);
state = Authenticated(
store: store,
// Signed out if the active operator was just deactivated — carrying on
// would keep stamping bills with an account the shop has revoked.
user: me.isEmpty ? store.staff.first : me.first,
);
}
void signOut() => state = const Unauthenticated();
void clearError() {
if (state is AuthFailure) state = const Unauthenticated();
}
}
final authControllerProvider = StateNotifierProvider<AuthController, AuthState>(
AuthController.new,
);
/// The signed-in store, or null before sign-in.
final currentStoreProvider = Provider<StoreAccount?>((ref) {
final s = ref.watch(authControllerProvider);
return s is Authenticated ? s.store : null;
});
/// The active operator, or null before sign-in.
final currentUserProvider = Provider<StaffUser?>((ref) {
final s = ref.watch(authControllerProvider);
return s is Authenticated ? s.user : null;
});
/// True while anyone is still on a seeded or admin-reset PIN.
final mustChangePinProvider = Provider<bool>((ref) {
final user = ref.watch(currentUserProvider);
return user?.mustChangePin ?? false;
});