neuctra_authix_dart_package 2.0.3
neuctra_authix_dart_package: ^2.0.3 copied to clipboard
Official Dart and Flutter SDK for the Neuctra Authix API — authentication, user records, app-wide data, cursor pagination, atomic batches and optimistic concurrency.
Neuctra Authix — Dart & Flutter SDK #
Authentication, identity, and user data as a service.
dependencies:
neuctra_authix_dart_package: ^2.0.0
Quick start (Flutter app) #
import 'package:neuctra_authix_dart_package/neuctra_authix_dart_package.dart';
// A publishable key (pk_live_…), passed at build time:
// flutter run --dart-define=AUTHIX_APP_ID=app_… \
// --dart-define=AUTHIX_PUBLISHABLE_KEY=pk_live_…
final authix = NeuctraAuthix(
const NeuctraAuthixConfig(
appId: String.fromEnvironment('AUTHIX_APP_ID'),
apiKey: String.fromEnvironment('AUTHIX_PUBLISHABLE_KEY'),
),
);
await authix.signupUser(
const SignupParams(
name: 'Ada Lovelace',
email: 'ada@example.com',
password: 'a-strong-password',
),
);
await authix.loginUser(
const LoginParams(email: 'ada@example.com', password: 'a-strong-password'),
);
final session = await authix.checkUserSession();
await authix.addUserData(
AddUserDataParams(
userId: session.userId!,
dataCategory: 'notes',
data: {'title': 'First note', 'body': 'Hello world'},
),
);
API keys #
Authix issues two kinds of key, both passed as apiKey. Create them on the API
Keys page of the dashboard; either kind can be limited to one app, and is then
refused for any other (403 KEY_APP_MISMATCH).
- Publishable key (
pk_live_…) — for Flutter apps. It can sign users up and in, verify email, reset passwords, read app data, and reach only the signed-in user's own profile and records: the user comes from the session cookie and anyuserIdyou pass is ignored. It cannot list or read other users, write app data, or set role,isActiveorpackageInfo. Native apps send noOriginheader, so leave the mobile app's allowed origins empty (give it its own Authix app). On Flutter Web, set the app's allowed origins, or requests are refused with 403ORIGINS_NOT_CONFIGURED. - Secret key (
sk_live_…) — full account authority over any user by id. Server only: never put it in a Flutter build or--dart-define, which are compiled into the binary. Olderak_live_…keys are secret keys.
// Dart backend — load the secret key from server environment configuration
final authix = NeuctraAuthix(
NeuctraAuthixConfig(
appId: appId,
apiKey: Platform.environment['AUTHIX_SECRET_KEY']!,
),
);
A secret key embedded in a shipped app is an account-level compromise. With a
secret key, userId is whatever you pass — take it from a session your server
has verified.
Pagination #
Every list and search returns a bounded Page — 20 records by default, 100
maximum. There is no "fetch everything" mode: one such request against a large
app would have to hold the whole dataset in memory, which on a phone is fatal.
final page = await authix.getUserData(
const GetUserDataParams(userId: 'u_1', limit: 50),
);
for (final record in page) { // a Page is an Iterable of its records
print(record['title']);
}
page.hasMore; // bool
page.nextCursor; // pass back as `cursor` for the next page
To walk everything, use the iterate* methods — they follow the cursor and
hand you a Stream, so a ListView can render rows as they arrive:
await for (final record in authix.iterateUserData(
const GetUserDataParams(userId: 'u_1'),
)) {
process(record);
}
// Bound the traversal when the dataset size is unknown
final rows = await authix
.iterateAllUsersData(q: 'invoice', maxPages: 10)
.toList();
Typed records #
Pass itemParser to decode into a model. DataItem.fromJson gives you the
built-in record shape, with version typed — which you need to update safely:
final page = await authix.getUserData<DataItem>(
const GetUserDataParams(userId: 'u_1'),
itemParser: DataItem.fromJson,
);
page.first.version; // int
page.first['title']; // payload field
page.first.payload; // payload without the identity fields
Searching #
keys is an exact-match containment query; q is a substring match. Both are
index-backed in Postgres, not filtered on the device.
await authix.searchInUserData(
const SearchUserDataParams(userId: 'u_1', keys: {'status': 'paid'}),
);
await authix.searchInAllAppUsersData(
const SearchAllAppUsersDataParams(q: 'invoice', limit: 100),
);
User search is restricted to a fixed field list — id, username, name,
email, phone, address, role, isVerified, isActive. Filtering on
anything else throws ValidationError; credential columns are never searchable.
Concurrency #
Pass the version you last read to avoid clobbering someone else's write:
final record = await authix.getSingleUserData(
const GetSingleUserDataParams(userId: 'u_1', dataId: 'd_1'),
);
try {
await authix.updateUserData(
UpdateUserDataParams(
userId: 'u_1',
dataId: 'd_1',
data: {'status': 'shipped'},
version: record.version,
),
);
} on VersionConflictError catch (e) {
print('changed since read; now at version ${e.currentVersion}');
}
Omit version and the write always wins — which is fine for a record only one
device touches, and wrong for anything else.
Atomic batches #
When records must change together, use batch() — every operation commits, or
none do:
await authix.batch(
const BatchParams(
userId: 'u_1',
operations: [
BatchOperation.create(dataCategory: 'orders', data: {'total': 40}),
BatchOperation.update(id: stockId, version: 3, data: {'remaining': 9}),
BatchOperation.delete(id: draftId),
],
),
);
A version mismatch or a missing record aborts the whole batch and nothing is written. Maximum 50 operations.
Share links #
Let anyone read one record by link, without signing in:
final link = await authix.shareUserData(
ShareUserDataParams(userId: uid, dataId: note.id), // expiresInDays, rotate
);
final url = 'https://myapp.com/s/${link.shareToken}';
final shared = await authix.getSharedData(token); // NotFoundError if revoked/expired
await authix.unshareUserData(UnshareUserDataParams(userId: uid, dataId: note.id));
Errors #
Every failure is an AuthixException, mapped to the most specific type the
response allows:
AuthixException // base — catches everything below
ConfigurationError // bad client setup; thrown before any request
NetworkError // connection failed or timed out
AuthixApiError // the API returned an error
AuthenticationError // 401 — bad, expired, or revoked credential
NoUserSessionError // 401 — publishable key, no live user session
InsufficientScopeError // 403 — publishable key on a secret-only endpoint
PermissionDeniedError // 403 — see .code, e.g. KEY_APP_MISMATCH
NotFoundError // 404
ValidationError // 400 — includes non-searchable field rejections
VersionConflictError // 409 — optimistic concurrency
RateLimitError // 429 — rate limited or monthly quota exhausted
ServerError // 5xx
InsufficientScopeError (code INSUFFICIENT_SCOPE) is a publishable key on an
endpoint that needs a secret key; it carries a .hint explaining the fix.
PermissionDeniedError.code names other refusals: SECRET_KEY_IN_BROWSER,
ORIGINS_NOT_CONFIGURED, KEY_APP_MISMATCH, an unverified account, or a plan
limit.
Sessions #
The client holds a cookie jar, so the session from loginUser() persists and
later calls act as that user:
await authix.loginUser(const LoginParams(email: '…', password: '…'));
await authix.checkUserSession(); // { authenticated: true, user: {...} }
await authix.logoutUser();
checkUserSession() never throws — a transport failure or an expired cookie
both resolve to authenticated: false. logoutUser() clears the local session
even if the server call fails, so a failed logout cannot leave a usable session
on the device.
Persist and restore a session across app launches through the store:
final token = authix.session.sessionCookie; // save it
authix.session.setSessionCookie(token); // restore on next launch
Flutter Web #
The browser owns the cookie jar there, so hand the client a BrowserClient
with credentials enabled and leave session empty:
import 'package:http/browser_client.dart';
NeuctraAuthix(config, client: BrowserClient()..withCredentials = true);
Configuration #
NeuctraAuthixConfig(
appId: 'app_…', // required
apiKey: 'pk_live_…', // publishable in an app; sk_live_… on a server
baseUrl: 'https://server.authix.neuctra.com/api',
appName: null, // optional label
timeout: Duration(seconds: 30),
);
Pass your own http.Client to NeuctraAuthix(config, client: …) for retries,
proxying, or tests. Call close() when you are done with the client.
API reference #
End-user auth — signupUser, loginUser, logoutUser,
checkUserSession, changePassword, requestEmailVerificationOTP,
verifyEmail, requestResetUserPasswordOTP, resetUserPassword
Users — getUserProfile, updateUser, deleteUser;
getUser, checkIfUserExists (secret key only)
User records — addUserData, getUserData, iterateUserData,
getSingleUserData, searchInUserData, updateUserData, deleteUserData,
deleteManyUserData, batch, shareUserData, unshareUserData,
getSharedData
App-wide records — getAppData, iterateAppData, getSingleAppData,
searchInAppData (any key); addAppData, updateAppData, deleteAppData
(secret key only)
Across all users (secret key only) — getAllUsersFromApp, iterateAllUsers,
searchInAllAppUsers, getAllUsersDataFromApp, searchInAllAppUsersData,
iterateAllUsersData
Escape hatch — rawRequest(SDKRequestOptions), pages(fetch)
Upgrading from 1.x #
See CHANGELOG.md. List and search methods return a Page instead of
an unbounded list, and errors are typed.
Development #
dart pub get
dart test
dart analyze
Links #
MIT licensed.