@simpleapps-com/augur-server
The server side of an Augur site on Next.js 16: one call sets up the SDK client, server actions and NextAuth; a client proxy routes React Query through server actions so the JWT never reaches the browser; and reads are cached in Redis.
pnpm add @simpleapps-com/augur-server @simpleapps-com/augur-hooksPeer dependencies: @simpleapps-com/augur-api, @simpleapps-com/augur-hooks (the site installs it, so it has one copy: …/hooks registers queryAction in it), @tanstack/react-query 5, next 16, react 19, next-auth 5; optional: ioredis 5 (without it nothing is cached) and jose (session-scoped clients). Every export, with its description: API Reference.
Entry points
| Import | Purpose |
|---|---|
@simpleapps-com/augur-server |
createSiteActions, getSiteActions, withServerCache, sdkCall, safeAction, environment, Redis, query clients, registerAllowedMethodPaths, isMethodPathAllowlistRegistered, and queryAction, queryActionWith, queryActionRaw, queryActionRawWith, unwrapBaseResponse for server code (no "use server", so importing them registers no action) |
@simpleapps-com/augur-server/site |
createServerSite |
@simpleapps-com/augur-server/hooks |
createServerQueryProxy (client code; importing it registers queryAction with augur-hooks) |
@simpleapps-com/augur-server/query-action |
queryAction, the server action behind the proxy; queryActionRaw, the same call with the full response; queryActionWith and queryActionRawWith, the same calls bounded by a deadline or signal, or with their own cache number (cacheTtl). It exports these server actions and nothing else. Server code imports the same functions, and getSessionCredentials, from the root, @simpleapps-com/augur-server |
@simpleapps-com/augur-server/api |
createAugurApiHandler, a route handler for fetch mode |
@simpleapps-com/augur-server/sitemap |
createSitemapIndexHandler, createItemSitemapHandler, sitemapRewrite, robotsSitemaps, isSitemapPath: item sitemaps built at request time |
@simpleapps-com/augur-server/auth |
createAuthConfig for NextAuth |
@simpleapps-com/augur-server/query |
createQueryOptions, createSuspenseQueryOptions |
@simpleapps-com/augur-server/actions |
Types only: SafeActionResult, ApiResult, ListResult |
@simpleapps-com/augur-server/testing |
createMockSiteActions, createMockClient, clearSiteActions |
@simpleapps-com/augur-server/next-auth |
NextAuth type augmentations (/// <reference types="…/next-auth" />) |
createServerSite
import { AugurAPI } from "@simpleapps-com/augur-api";
import { createServerSite } from "@simpleapps-com/augur-server/site";
const api = new AugurAPI({ siteId: process.env.AUGUR_SITE_ID!, bearerToken: process.env.AUGUR_JWT! });
export const site = createServerSite(api, {
auth: { secret: process.env.AUTH_SECRET, withoutCustomer: "none" },
shipping: { fromAddress: { address1: "123 Main", city: "Provo", state: "UT", postalCode: "84606" } },
});
// site.client: the SDK; site.actions: SiteActions; site.auth: a NextAuth config, when `auth` is givenIt also registers what queryAction needs: the site actions, the SDK client, a Redis cache wrapper using the config's cachePrefix, redisTtl (default 3600 s) and longRedisTtl (default 28800 s), a factory for session-scoped clients, the auth secret (auth.secret, else AUTH_SECRET), whether this is the cross-site site, and the site's queryAction allowlist when given.
Cross-site sessions (one site signing users in for others, augur-support's pattern) are on exactly for the augur_info site, read from the client's own siteId: there is no setting. That site also posts the target siteId to signIn, the site whose password Joomla checks. On every other site the posted siteId is ignored and queryAction never reads the session cookie, so pages that prefetch through it can render statically and honour revalidate.
The queryAction allowlist
allowedMethodPaths names the SDK method paths queryAction may call. Any other path is refused before a request:
export const site = createServerSite(api, {
auth: { secret: process.env.AUTH_SECRET, withoutCustomer: "none" },
allowedMethodPaths: ["items.invMast.doc.get", "pricing.priceEngine.list", "commerce.cartLine.add.create"],
});- Typed by the SDK. Each entry is one of the SDK's method paths, so a typo fails
tsc. - What it covers. Everything that goes through
queryAction: the server actionscreateServerQueryProxycalls, fetch mode, and server prefetches built withcreateAugurOptions(queryAction). The list MUST include their paths too, or those pages fail with "… is not on the site's allowlist. Add it to createServerSite's allowedMethodPaths."site.actions.*call the SDK directly and need no entry. - Absent or empty. Without the option every path passes;
[]refuses every one. - Checked in a test.
isMethodPathAllowlistRegistered()(from@simpleapps-com/augur-server) istrueonce a list is registered, so a site's test can import its setup and assert it.registerAllowedMethodPaths(paths), also from the root, adds paths from other server code. Neither is ever a server action.
import { isMethodPathAllowlistRegistered } from "@simpleapps-com/augur-server";
import "@/lib/site"; // runs createServerSite
it("registers the queryAction allowlist", () => {
expect(isMethodPathAllowlistRegistered()).toBe(true);
});The config (SiteActionsConfig) also takes cachePrefix (default "<siteId>:"), edgeCache, longEdgeCache, defaultCustomerId and defaultContactId (falling back to DEFAULT_CUSTOMER_ID and DEFAULT_CONTACT_ID), convertUnitOfMeasure, and per-service options for pricing, items, search, payments, shipping and vmi.
createServerQueryProxy
The way to fetch data on sites whose JWT stays on the server. It mirrors the SDK like useAugurOptions() does, and each queryFn calls queryAction, a server action:
"use client";
import { createServerQueryProxy } from "@simpleapps-com/augur-server/hooks";
import { useMutation, useQuery } from "@tanstack/react-query";
const q = createServerQueryProxy();
const { data: item } = useQuery(q.items.invMast.doc.get(invMastUid));
const { data: price } = useQuery(q.pricing.priceEngine.list({ itemId: "SKU-1", customerId }));
const addLine = useMutation(q.commerce.cartLine.add.create());For an infinite list, spread the options into useInfiniteQuery and add getNextPageParam and initialPageParam.
Types default to DeepQueryOptions<AugurAPI>, so a new SDK method works with no code change. Keys match createOptionsProxy and augur-hooks' createAugurOptions, so server prefetches hydrate. It takes an optional query action and an optional cache config.
queryAction
queryAction(methodPath, ...args):
- Checks no caller: that is the site's job. From
@simpleapps-com/augur-server/query-actionit is a server action, and a server action is a public endpoint: anyone who has its id can call it. Each call goes out with the site's own credentials. Deciding who may make a call, and for which customer's records, belongs in the site's own server action, which checks the caller before it callsqueryAction:
// app/actions/query.ts
"use server";
import type { AugurAPI } from "@simpleapps-com/augur-api";
import type { MethodPath } from "@simpleapps-com/augur-core";
import { queryAction } from "@simpleapps-com/augur-server"; // the root: no action of its own
import { auth } from "@/auth";
export async function siteQuery(methodPath: string, ...args: unknown[]) {
const session = await auth();
// the site's own rules: which paths, and which customer's records, this caller may read
if (!mayCall(session, methodPath, args)) throw new Error("Not allowed");
return queryAction(methodPath as MethodPath<AugurAPI>, ...(args as []));
} Register it for the browser with augur-hooks' registerQueryAction(siteQuery) in place of …/hooks. Server code (prefetches, createAugurOptions(queryAction), other actions) imports the query functions from the root too: importing …/query-action anywhere, server code included, registers its four actions in the build. The allowlist narrows the paths, not the callers.
- Picks a client. On the augur_info site with a valid session (an Auth.js cookie whose
targetSiteIdandtokenagree with the token'sclient_id), it uses a client scoped to that site and user, and caches under"<targetSiteId>:". Otherwise it uses the site's own client, and on every other site it reads no cookies at all (getSessionCredentialsreturnsnull). - Only API routes, with proper data. A method path must be an endpoint id in the site's own SDK registry (
api.hasEndpoint; a data proxy such asitems.invMastData.listcounts asitems.invMast.list), and is followed through the client's services and their own properties only. The client's own methods (setAuthToken,call,withRequest), itsconfighooks and a service'shttpclient answer "is not an API route". The SDK then refuses a sent query param that does not fit its declared type, before any request. Upgrade@simpleapps-com/augur-apiwith this package: an older SDK has nohasEndpoint, and only the walk check runs. - Only the site's allowlist, when it has one. With createServerSite's
allowedMethodPaths, a path not on it is refused before anything else. - Caches reads. Reads (
get,list,lookup,search,suggest) are cached in Redis: the long TTL when the tier's staleTime is an hour or more, the standard TTL otherwise. It never caches a tier without a Redis TTL:commerce,payments, wishlists and favorites. P21 data (a customer's records, the user profile, orders, VMI) is held one minute. A query can send its own number instead (cacheTtl). Writes go straight through. - Strips edge caching on no-cache, user and P21 paths. It removes
edgeCachefrom the arguments of those calls. - Unwraps the response. It returns the response's
data, so a client query getsT, never{ data, status, message }. - Answers a missing record as
null. A read by path id (agetcalled with its id first:items.invMast.get(uid),orders.oeHdr.doc.get(orderNo, …), thegetaliasitems.invMast.doc.get(0, { itemId })) whose record doesn't exist (the SDK'sNotFoundError, 404) returnsnull, typedT | null. Every other failure still throws, so an outage still reacheserror.tsx: alist's 404, agetthat takes no id (items.invMast.lookup.get(params),healthCheck), a 500, a refusal. Thenullis never cached, so a record created later shows at once. A page checks it and callsnotFound():
const item = await queryClient.fetchQuery(q.items.invMast.doc.get(0, { itemId }));
if (!item) notFound(); // a 404 page, and generateMetadata can set noindex- Is typed by path. The path is one of the SDK's method paths, the arguments that method's own, the result its
datatype, so a wrong path or arguments that an SDK upgrade changed failtscinstead of a live request:
await queryAction("orders.oeHdr.doc.get", orderNo, { postalCode }); // typed: the order document
await queryAction("openSearch.itemSearch.attributes.list", "moulding"); // tsc error: it takes { q, ... }On upgrading, a site may see new type errors where it calls queryAction: each is a call the SDK would refuse, or a read by path id whose result it uses without checking for null. Pass one literal path per call; a union of paths is typed loosely. A path built at runtime (a route forwarding a request) has no literal type: cast it, queryAction(path as MethodPath<AugurAPI>, ...args) (augur-core's MethodPath), and its arguments are unknown[]; the allowlist still checks it. queryActionRaw keeps its caller-named T.
It caches the SDK's raw response under augur-core's buildRawCacheKey, apart from the actions' shaped values, so getStock and queryAction("items.invMast.stock.get", uid) never read each other's entry. The cache key holds the site, method and arguments but not the user's token. Users of one site share cached reads outside commerce and payments, so a namespace whose responses depend on the user MUST be added to augur-core's NO_CACHE_PATHS.
queryActionRaw
queryActionRaw<T>(methodPath, ...args) is the same call (client, cache, allowlist, edgeCache strip) answered as the SDK returned it: augur-api's BaseResponse<T>, so a page can read total / totalResults and page a list. It throws a missing record's NotFoundError as before (only queryAction and queryActionWith answer null). A method path carries no type, so name the data's type as T. A queryAction and a queryActionRaw of one call share one Redis entry.
"use client";
import { queryActionRaw } from "@simpleapps-com/augur-server/query-action";
import { useQuery } from "@tanstack/react-query";
const { data: page } = useQuery({
queryKey: ["articles-page", { limit, offset }],
queryFn: () => queryActionRaw<Article[]>("joomla.content.list", { limit, offset }),
});
// page?.data: the articles; page?.total: how many there are in allGive it its own query key. A key from the proxy (q.joomla.content.list(...).queryKey) holds queryAction's unwrapped value, and one key MUST hold one shape.
queryActionWith
queryActionWith(options, methodPath, ...args) (and queryActionRawWith) is the same call, bounded. A server render that awaits a read SHOULD use it: unbounded, the SDK's retry budget (3 retries at 30 s each, plus backoff) becomes page latency.
import { queryActionWith } from "@simpleapps-com/augur-server";
// In a server component: within 5 s, or render without it and let the client fetch
const items = await queryActionWith({ deadline: 5000 }, "items.categories.items.list", uid, params)
.catch(() => undefined);deadline(ms) bounds the whole call, every retry and wait included. At the deadline it rejects with aTimeoutError: the request is cancelled, nothing more is retried, and nothing is cached.signalcancels it too. Server code only: a signal can't be sent to a server action from the browser, but adeadlinecan.- The options are not SDK arguments and not part of the cache key, so a bounded call and an unbounded one share one Redis entry.
- It runs on the SDK client's
withRequestview, so it needs an@simpleapps-com/augur-apithat has it. On an older client the call is refused rather than run unbounded.
A query's own cache number
cacheTtl (seconds) sets how long one query's answer may be cached on the server, in place of the default (a customer's records, the user profile, orders and VMI: one minute).
import { minutes, seconds } from "@simpleapps-com/augur-utils";
import { queryActionWith } from "@simpleapps-com/augur-server";
// Always fresh from P21: no Redis read or write
const orders = await queryActionWith({ cacheTtl: seconds(0) }, "customers.customer.orders.list", customerId);
// Up to five minutes old is fine for this page
const shipTos = await queryActionWith({ cacheTtl: minutes(5) }, "customers.customer.shipTo.list", customerId);- Left out, nothing changes: the default stays.
- Sent, it is an age limit: the query is never served an answer older than its number, even one another query stored with a longer one, and what it stores lives that long.
0is no cache: no Redis read, no Redis write.- It never caches wishlists, favorites, commerce or payments, whatever is sent.
- Anything but whole seconds, 0 or more (a negative, a fraction, text), is refused before any request. It is a number, so it can be sent from the browser as
deadlinecan. - Where a browser can reach (
queryActionWith,queryActionRawWith, the fetch-mode route), it is 0 to 3600: at most an hour. Server-only code (the actions below) takes any whole seconds. - The customers, orders, VMI and joomla profile actions take it as an optional last argument:
site.actions.customers.getCustomerOrders(customerId, params, { cacheTtl: seconds(0) }). - In the browser, a query proxy sends it with every read:
createServerQueryProxy({ cacheTtl })(server actions) orcreateQueryActionProxy(createFetchQueryAction("/api/augur", { cacheTtl }))(fetch mode). Make one proxy per number; the number is not part of the query key, souseQuerycaches the same way. - A number alone needs no
withRequest: only adeadlineor asignalbounds the call.
import { seconds } from "@simpleapps-com/augur-utils";
import { createServerQueryProxy } from "@simpleapps-com/augur-server/hooks";
const fresh = createServerQueryProxy({ cacheTtl: seconds(0) });
const { data: orders } = useQuery(fresh.customers.customer.orders.list(customerId));Fetch mode
Where server actions can't read request cookies (Cloudflare Workers through OpenNext), expose queryAction as a route and point the browser at it:
// app/api/augur/route.ts
import { createAugurApiHandler } from "@simpleapps-com/augur-server/api";
export const POST = createAugurApiHandler();import { createFetchQueryAction } from "@simpleapps-com/augur-core";
import { registerQueryAction } from "@simpleapps-com/augur-hooks";
registerQueryAction(createFetchQueryAction("/api/augur"));For the full response in fetch mode, call augur-core's createFetchQueryActionRaw("/api/augur"): it sends raw: true, and the route answers through queryActionRaw (any other raw gets queryAction's data).
Both take a cache number as their second argument, sent with every call: createFetchQueryAction("/api/augur", { cacheTtl: 0 }).
import { createFetchQueryAction, createQueryActionProxy } from "@simpleapps-com/augur-core";
const fresh = createQueryActionProxy(createFetchQueryAction("/api/augur", { cacheTtl: 0 }));The handler refuses cross-site requests (Sec-Fetch-Site), bodies without a methodPath string and an args array, and a cacheTtl that is not whole seconds from 0 to 3600 (400).
Site actions
site.actions (or getSiteActions() in a server action) has 25 services: pricing, items, commerce, search, orders, shipping, joomla, legacy, customers, smartyStreets, p21Pim, agrSite, avalara, payments, logistics, vmi, p21Core, p21Apis, p21Sism, agrWork, agrInfo, brandFolder, gregorovich, favorites and wishlists. Each is built on first use. A method a service doesn't define falls through to augur-core's createActionsProxy, which calls the SDK method of that path and caches reads with the tier's redisTtl.
"use server";
import { getSiteActions, safeAction } from "@simpleapps-com/augur-server";
export async function getPrice(itemId: string) {
return safeAction(() => getSiteActions().pricing.getItemPrice(itemId));
}pricing.getItemPrice(itemId, customerId?, quantity?, unitOfMeasure?) prices the default selling unit when no unit is given; a cart line passes its own ("CASE/6" gets the case price). It has the signature of augur-hooks' useCartPricing queryFn, which passes each line's unit. batchGetItemPrices takes the unit in the same place. Each resolves its customer as the first usable one of the caller's and defaultCustomerId; with neither it throws "A price needs a customer" and asks nothing, and batchGetItemPrices throws once, before any item, rather than returning {}.
The customers actions (getCustomerDoc, getCustomerOrders, getCustomerOrderDetail, getCustomerInvoices, getCustomerInvoiceDetail, getCustomerQuotes, getCustomerQuoteDetail, getShipToAddresses) take the customer id as a number and throw before any request when it is not a usable P21 customer id (0, a negative, a fraction), so none ever reads customers/0/…. Resolve a session's text with augur-utils resolveAddressId first.
Each action read calls the SDK method its spec names (read-specs.ts), and its cache key uses that same path. List reads that should return everything page to the end instead of stopping at the route's default 10 rows: wishlists and their lines, favorites, ship-to addresses, states, item tags, FAQs, substitutes and accessories, agr-site settings, gregorovich documents, and a menu's children. These reads page 100 rows a call, at most 50 calls, and return { data, total, capReached }; capReached is true when the cap stopped the read, so the list may be incomplete. Wishlist and favorites reads are never cached on the server. P21 data (a customer's records, the user profile, orders, VMI) is held one minute in Redis, whatever TTL the site sets, unless the call sends its own cacheTtl. Neither is cached at the edge. To refresh a browser's copy after the user's own write, install augur-hooks' userWriteClearing on the site's QueryClient.
An action that reads one record by its id answers a missing record (the SDK's NotFoundError, 404) as null, as queryAction does, and is typed T | null: items.getItemCategory, getInvMast, getInvMastDoc (now read through the doc.get alias, so its Redis entries start cold once), getStock, getStockCompanySummary; customers.getCustomerDoc and the order, invoice and quote details; joomla.getJoomlaContent, getJoomlaMenuDoc, getUserProfile; orders.getOrderDoc; wishlists.getWishlists and getWishlistDetail. The null is never cached, and batchGetInvMastDocs / batchGetStockData leave a missing item out as they leave a failed one. Every list read, and every other failure, still throws.
getSiteActions() looks in a globalThis singleton, then a module-level copy (Next.js standalone builds can reset globalThis), then builds one from AUGUR_SITE_ID and AUGUR_JWT, and throws if none of those works.
Account flows
joomla.registerUser, activateUser, requestPasswordReset and confirmPasswordReset run registration and password reset through the joomla service. The site gives its account emails once, in createServerSite's joomla.account: the page each email links to (with {token} in it, which the service fills in), the site name and the sender.
createServerSite({
// …
joomla: {
account: {
activationUrl: "https://example.com/register/verify/{token}",
resetUrl: "https://example.com/forgot-password/verify/{token}",
siteName: "Example",
fromAddress: "noreply@example.com",
fromName: "Example Store",
},
},
});Each action answers { ok: true } or { ok: false, reason, message } and never throws for an expected refusal; message is the service's text.
| Action | Takes | reason when it fails |
|---|---|---|
registerUser |
{ username, email, password, name?, profileValues?, groups? } |
taken (username or email in use), approvalRequired (the site needs admin approval, not supported yet), emailUnavailable (the email couldn't be sent; no user is made), invalid, notConfigured, serviceError |
activateUser |
the emailed token | invalidToken (invalid, expired or used), invalid, serviceError |
requestPasswordReset |
an email address | invalid, notConfigured, serviceError; a known and an unknown email both answer { ok: true } |
confirmPasswordReset |
{ username, token, password } |
invalidToken, invalid, serviceError |
profileValues maps the site's own profile fields by profile key (for example simpleweb_customer.simpleweb_customer_id). A blank required field is invalid and the joomla service is not called; account emails missing, or a link without {token}, is notConfigured.
"use server";
import { getSiteActions } from "@simpleapps-com/augur-server";
export async function activate(token: string) {
const result = await getSiteActions().joomla.activateUser(token);
if (result.ok) return "Your account is active. You can sign in.";
return result.reason === "invalidToken"
? "This link is invalid or has expired."
: "Something went wrong. Please try again.";
}Helpers
| Export | Does |
|---|---|
safeAction(fn, onError?) |
{ ok: true, data } or { ok: false, error } instead of throwing; for server actions, not React Query reads (let those throw so React Query retries) |
sdkCall(method, ...args) |
Calls an SDK method with its parameter and result types inferred |
withServerCache(prefix, ttl, methodPath, fn, ...keyArgs) |
Redis read-through for a shaped value, using augur-core's buildCacheKey; a TTL of 0, or a no-cache or user methodPath, skips caching; a P21 methodPath is held one minute |
cacheGet, cacheSet, isRedisConnected, getCircuitState |
The Redis client; never throws, and a circuit breaker stops calls while Redis is down |
batchFetch |
Parallel fetches keyed by param; a failed one is left out |
paginateOffset |
Wraps a list with offset paging metadata |
getServerQueryClient, createServerQueryClient |
A per-request QueryClient, or a new one, for prefetching |
verifyRecaptcha |
reCAPTCHA v3 check with RECAPTCHA_SECRET_KEY |
unwrap, unwrapOr |
Re-exported from augur-utils |
Redis's URL comes from REDIS_SERVERS (containers), else REDIS_URL_DEV, REDIS_URL_STAGING or REDIS_URL_PROD by environment.
Item sitemaps
The item sitemaps are built per request from the catalog (googMc.sitemaps.items.list), so the number of files follows the catalog without a deploy, however large it is. They sit in the items' own folder, /items/ unless you pass base:
/items/sitemap.xml: the item index, listing one file per 5,000 items./items/sitemap-1.xml,/items/sitemap-2.xml, …: each page's items.
The sitemap protocol only lets a sitemap list URLs under its own folder, so base MUST match the item links Augur returns. A link outside it is left out.
// app/items/sitemap.xml/route.ts
import { createSitemapIndexHandler } from "@simpleapps-com/augur-server/sitemap";
import { site } from "@/lib/augur-site";
export const dynamic = "force-dynamic";
export const GET = createSitemapIndexHandler(site, { siteUrl: "https://www.example.com" });// app/items/sitemap.xml/[page]/route.ts
import { createItemSitemapHandler } from "@simpleapps-com/augur-server/sitemap";
import { site } from "@/lib/augur-site";
export const dynamic = "force-dynamic";
export const GET = createItemSitemapHandler(site, { siteUrl: "https://www.example.com" });// next.config.ts: serve /items/sitemap-{n}.xml from the page handler
import { sitemapRewrite } from "@simpleapps-com/augur-server/sitemap";
const nextConfig = {
async rewrites() {
return [sitemapRewrite()];
},
};// app/robots.ts
import { robotsSitemaps } from "@simpleapps-com/augur-server/sitemap";
export default function robots() {
return {
rules: { userAgent: "*", allow: "/" },
sitemap: robotsSitemaps("https://www.example.com"),
};
}- Main pages: the site's own root
/sitemap.xml(for example Next'sapp/sitemap.ts) lists its static pages, categories and blog. robots.txt names it and the item index; the root sitemap doesn't list the item index, because the specs don't put one index inside another. - Item-URL redirects: a proxy that normalizes item URLs (for example uppercasing them) MUST pass
isSitemapPath(pathname)through first. The proxy runs before rewrites, so otherwise/items/sitemap-1.xmlis redirected to an item page. - Responses:
- a served file is cached for a day at the CDN and an hour in browsers;
- a page number that isn't one, or an empty page past the first, is a 404;
- when Augur fails or takes longer than
deadline(10 s by default), the response is a 503 withRetry-After, never cached.
- Format: every value is XML-escaped, and each element sits on its own line.
Environment
env is "development", "staging" or "production", with isDev, isStaging and isProduction. It comes from DEPLOYMENT_ENV (dev is staging, live is production), else NODE_ENV on the server, else the hostname in the browser.
Auth
import NextAuth from "next-auth";
import { createAuthConfig } from "@simpleapps-com/augur-server/auth";
export const { handlers, signIn, signOut, auth } = NextAuth(
createAuthConfig({ augurClient: site.client, withoutCustomer: "none" }),
);
// The login form posts what the person typed; the server checks it.
await signIn("credentials", { username, password, redirect: false });A Joomla credentials provider with JWT sessions; the callbacks add the user's profile and cart header to the session. Options: withoutCustomer (required, below), augurClient or callbacks (to replace the SDK calls: getUserProfile, cartHdrLookup, verifyPassword), secret (default AUTH_SECRET), maxAge (default 4 hours), defaultCustomerId, defaultContactId and debug. createServerSite builds this for you when given auth.
Sign-in is checked on the server (atlas#97). authorize reads only username and password (and siteId on the augur_info site), asks Joomla (joomla.users.verifyPassword, or callbacks.verifyPassword), and signs in as the user Joomla's answer names, with the token Joomla issued. A posted id, isVerified or token is never read: a login page that called verifyPassword in the browser and passed its answer to signIn MUST post the username and password instead. A wrong password, a blank field or an unknown user signs no one in; a Joomla or network failure is an error, never a wrong password. A config built from callbacks with no augurClient MUST give both getUserProfile and verifyPassword.
A blocked account has no session. Joomla refuses a blocked account's password, and every session read re-reads the account: a blocked (block) or deleted one's session ends at once. A site's own getUserProfile SHOULD set blocked from the users doc. A failed read (the API down) keeps the session until the next good read.
Logs carry no secrets. The auth logger writes an error's type only, never its cause (Auth.js's default prints an expired session's decrypted cookie, the token included).
The session never carries the user's Augur token (atlas#212). The session object reaches the browser (/api/auth/session, useSession), so the token stays in the encrypted JWT cookie; server code reads it from there (getToken from next-auth/jwt, or queryAction's cross-site sessions, which already do).
withoutCustomer says what a signed-in user with no usable customer of their own gets, and it has no default, because both answers are right for some site:
| Value | The session's customerId and cart |
For |
|---|---|---|
"default" |
defaultCustomerId and its cart |
A site whose shoppers buy as the site's customer, or that keeps the legacy rule that an unapproved account acts as the default |
"none" |
none, and no cart is looked up | A B2B portal: the default customer's orders and invoices are not the user's |
The user's own customer always wins: the session's customerId is the profile's when it is a usable P21 customer (a whole number at least 1), else the default on a "default" site, else unset. Joomla's "" or "0" never reaches the session, and no cart header is looked up for customer 0 (atlas#95). joomla.getUserProfile returns customerId as a number, or null when the profile has none. Pricing, tax and commerce.cartHdrLookup resolve their customer from the caller's id and defaultCustomerId, as before.
Related
- augur-hooks: the provider that picks up the registered
queryAction - augur-core: the proxies, tiers and cache keys