k.account — Login and Identity
Authentication state, login/logout, and token APIs on the
k.accountroot object
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
Server-side KScript (k.api, <script env="server">) | Basic login and JWT reads work out of the box; generateToken and renewInfo require login plus the platform Account service; thirdPartyLogin requires the platform Account service | Check auth state, authenticate platform or org sub-accounts, sign out, and protect routes |
Quick Start
Check whether the request is signed in, or authenticate with username and password:
k.api.post(() => {
if (k.account.isLogin) {
return { isLogin: true, userName: k.account.user.current.userName }
}
const user = k.account.login(k.request.form.username, k.request.form.password)
return {
isLogin: k.account.isLogin,
userName: user ? user.userName : null
}
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
isLogin | Whether the current HTTP request carries a valid platform user identity | boolean |
login(username, password, code?) | Logs in with platform credentials and writes a JWT cookie | User | null |
loginOrganization(username, password) | Logs in as a sub-account of the current site's organization | User | null |
logout(returnUrl?) | Clears login cookies and redirects when configured | void |
ensureLogin(redirectUrl) | Sets a 302 redirect when unauthenticated (does not halt JS; return manually) | void |
generateToken(userName, expireIn) | Generates a JWT token for a user (requires admin rights & Account service) | string |
getAccessToken() | Reads the JWT string from the current request context | string | null |
setIdentity(token) | Sets the given JWT as the bearer identity for the current request | void |
thirdPartyLogin(thirdPartyName, userName) | Requests third-party login info from the platform Account service | ThirdPartyLoginInfo |
renewInfo() | Reads account/site renewal info (requires login & Account service) | RenewInfo |
Methods & Properties
isLogin
Whether the current HTTP request carries a valid platform user identity.
Parameters: None.
Returns: boolean. true when logged in; false otherwise.
k.api.get(() => {
return { isLogin: k.account.isLogin }
})login()
Logs in with a username and password. On success, it writes a JWT cookie and sets the current user for the request; on failure, returns null and isLogin remains false.
| Parameter | Type | Required | Description |
|---|---|---|---|
username | string | Yes | Platform username. |
password | string | Yes | Account password. |
code | string | No | Verification code, if required by account policy. |
Returns: User | null. The user object on success, or null on failure.
k.api.post(() => {
const username = k.request.form.username
const password = k.request.form.password
const user = k.account.login(username, password)
return {
isLogin: k.account.isLogin,
userName: user ? user.userName : null
}
})loginOrganization()
Logs in as an organization sub-account: internally rewrites the username as {username}@{current site organization ID} before authenticating. Use this when a site is bound to an organization and uses organization sub-accounts.
| Parameter | Type | Required | Description |
|---|---|---|---|
username | string | Yes | Organization sub-account username without the @organizationId suffix. |
password | string | Yes | Password. |
Returns: User | null. The user object on success, or null on failure (isLogin remains false).
k.api.post(() => {
const username = k.request.form.username
const password = k.request.form.password
const user = k.account.loginOrganization(username, password)
return {
isLogin: k.account.isLogin,
userName: user ? user.userName : null
}
})logout()
Clears login cookies. If SSO is enabled on the site, it redirects to the SSO logout URL; otherwise it redirects to returnUrl when provided.
Same-Request Auth State & k.api Return Value
logout()deletes the login cookie without clearingcontext.User, sok.account.isLoginremainstruefor the remainder of the current request (it becomesfalseon subsequent requests).- When passing
returnUrl(or when SSO is enabled), a 302 redirect is set on the response: ink.api, immediatelyreturnorreturn null, because returning any non-null value causesKApito overwrite theLocationheader with the serialized response body. To return JSON from a non-SSO endpoint instead, callk.account.logout()with noreturnUrl(and do not readk.account.isLoginexpectingfalsein the same request).
| Parameter | Type | Required | Description |
|---|---|---|---|
returnUrl | string | No | Site-relative redirect path after logout. |
Returns: void.
k.api.get(() => {
// Passing returnUrl sets a 302 redirect; return null / return so KApi does not overwrite Location
k.account.logout("/")
return null
})ensureLogin()
If not logged in, sets a 302 redirect to redirectUrl and marks the response as ended; if logged in, performs no operation. Note: ensureLogin() does not halt subsequent JavaScript execution. Always follow it immediately with if (!k.account.isLogin) return so remaining code does not continue running, throw an error, or overwrite the 302 Location header with a non-null return value.
| Parameter | Type | Required | Description |
|---|---|---|---|
redirectUrl | string | Yes | URL to redirect to when the user is not logged in. |
Returns: void.
k.api.get(() => {
k.account.ensureLogin("/login?return=" + encodeURIComponent(k.request.url))
if (!k.account.isLogin) return
return k.account.user.current
})generateToken()
Generates a JWT login token for the specified platform user. This calls the platform Account service and requires an authenticated session with the corresponding administrative permissions; calling it unauthenticated or when the Account service is unavailable throws an error.
| Parameter | Type | Required | Description |
|---|---|---|---|
userName | string | Yes | Target username. |
expireIn | number | Yes | Token lifetime in seconds (for example, 86400 for 1 day). |
Returns: string. Generated JWT login token.
k.api.post(() => {
k.account.ensureLogin("/login")
if (!k.account.isLogin) return
const userName = k.request.form.userName
const expireIn = parseInt(k.request.form.expireIn || "86400", 10)
const token = k.account.generateToken(userName, expireIn)
return { tokenLength: token ? token.length : 0 }
})getAccessToken()
Reads the JWT string in the current request context when logged in.
Parameters: None.
Returns: string | null. JWT for the current request, or null / empty when unauthenticated or no token is present.
k.api.get(() => {
const token = k.account.getAccessToken()
return {
hasToken: !!token,
prefix: token ? token.substring(0, 20) + "..." : null
}
})setIdentity()
Applies the given JWT as the Authorization: Bearer … identity for the current request so subsequent logic can access login-gated APIs. Passing an invalid token leaves isLogin as false.
Runtime Constraints
- Must be called before reading auth state:
setIdentity(token)only mutates theAuthorizationrequest header and does not reset the cachedRenderContext.Userlookup. Ifk.account.isLoginork.account.userhas already been read earlier in the same request, callingsetIdentity()afterward has no effect onisLoginoruser.current. - Existing
jwt_tokencookie takes precedence: Token resolution inspects thejwt_tokenrequest cookie before theAuthorizationheader, so an existing login cookie overrides the token supplied tosetIdentity().
| Parameter | Type | Required | Description |
|---|---|---|---|
token | string | Yes | JWT login token. |
Returns: void.
k.api.post(() => {
const token = k.request.form.token
k.account.setIdentity(token)
return { isLogin: k.account.isLogin }
})thirdPartyLogin()
Retrieves third-party login information from the platform Account service by provider name and username (for external IdP integrations). Does not require an existing authenticated session; throws an error if unconfigured, not found, or if the Account service is unavailable.
| Parameter | Type | Required | Description |
|---|---|---|---|
thirdPartyName | string | Yes | Third-party provider identifier. |
userName | string | Yes | Associated username. |
Returns: ThirdPartyLoginInfo. Third-party login information.
k.api.post(() => {
const info = k.account.thirdPartyLogin(
k.request.form.thirdPartyName,
k.request.form.userName
)
return { verified: !!info }
})renewInfo()
Retrieves renewal information for the current account or site from the platform Account service. Only supported in environments connected to the Kooboo Account service and requires an authenticated user with appropriate permissions; throws an error when unauthenticated or unavailable.
Parameters: None.
Returns: RenewInfo. Renewal information for the current account or site.
k.api.get(() => {
if (!k.account.isLogin) {
return { error: "not logged in" }
}
return k.account.renewInfo()
})TypeScript Definitions
Show full TypeScript definitions
interface KAccount {
isLogin: boolean;
login(username: string, password: string, code?: string): User;
loginOrganization(username: string, password: string): User;
logout(returnUrl?: string): void;
ensureLogin(redirectUrl: string): void;
generateToken(userName: string, expireIn: number): string;
getAccessToken(): string;
setIdentity(token: string): void;
thirdPartyLogin(thirdPartyName: string, userName: string): ThirdPartyLoginInfo;
renewInfo(): RenewInfo;
user: KUser;
organization: KOrganization;
oAuth: kOAuth;
}
interface ThirdPartyLoginInfo {
token: string;
success: boolean;
koobooUserName: string;
thirdPartyUserName: string;
}
interface RenewInfo {
balance: number;
currency: string;
membership: RenewMembershipInfo;
domains: RenewInfoDomain[];
}
interface RenewMembershipInfo {
id: any;
name: string;
serverLevel: number;
expiredIn?: Date;
}
interface RenewInfoDomain {
id: any;
name: string;
expiredIn?: Date;
}