KScript 文档
ZH

KScript.Auth

用于 kscript serve 应用的登录功能:用户、会话、auth 与 guest 中间件、CSRF、密码重置和 API 令牌。

在脚本顶部导入:

<import package="KScript.Auth" />
import KScript.Auth

KScript.Auth 用于为 kscript serve 应用提供用户登录,因此其示例无法在文档内直接运行。请将示例复制到 .ks.xml 文件中,然后用 kscript 运行。

元素语句

#<policy>policy

规定谁可以对模型的记录执行哪些操作。其中的每个 fn 都是一项权限,以其允许的操作命名(create、read、update、delete 或你自定义的名称),接收用户和记录作为参数,并返回 true 或 false:policy for Post { fn update(user: User, post: Post) => $user.id == $post.author_id }。若用户类型为 User?,则访客可以以 null 调用该函数;其他类型则会先拒绝访客。fn before(user) 会在所有权限检查之前运行:返回 true 或 false 即作出决定,返回 null 则继续检查。每个模型保留一个策略,放在项目的 policies 文件夹中,@can 会按模型名称找到它。规定谁可以对模型的记录执行哪些操作。其中的每个 fn 都是一项权限,以其允许的操作命名(create、read、update、delete 或你自定义的名称),接收用户和记录作为参数,并返回 true 或 false:policy for Post { fn update(user: User, post: Post) => $user.id == $post.author_id }。若用户类型为 User?,则访客可以以 null 调用该函数;其他类型则会先拒绝访客。fn before(user) 会在所有权限检查之前运行:返回 true 或 false 即作出决定,返回 null 则继续检查。每个模型保留一个策略,放在项目的 policies 文件夹中,@can 会按模型名称找到它。
规定谁可以对模型的记录执行哪些操作。编写 policy for Post { fn update(user: User, post: Post) => $user.id == $post.author_id }。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

属性值说明
for 必填a string该策略所适用的模型或类型。
descriptiona string策略的用途,鼠标悬停时显示。
示例
<import package="KScript.Data" /><model name="Note"><field name="owner_id" type="int" /></model>
<policy for="Note">
  <fn name="read" params="user, note: Note" value="$user != null and $user.id == $note.owner_id" />
</policy>
import KScript.Data
model Note {
  owner_id: int
}
policy for Note {
  fn read(user, note: Note) => $user != null and $user.id == $note.owner_id
}

命令

命令可通过 @ 调用,可用于任何表达式:@name(arguments)。

#@acting_as(user) → any

在测试中,设置 @can、@authorize 和 @user() 所询问的用户,直到测试结束。适用于测试本身以及通过 @api(/...) 调用的路由:@acting_as($editor)。传入 null 则以访客身份操作。
示例
<do>@acting_as({ id: 1, role: 'editor' })</do>
@acting_as({ id: 1, role: 'editor' })

#@acting_as_guest(id?: any) → any

在测试中,以访客身份操作,直到测试结束。适用于测试本身以及通过 @api(/...) 或 @visit() 调用的路由:@guest() 使用此 id(省略时生成新的 id),在有请求发送已登录用户的会话 cookie 之前,都不视为已登录,就像浏览器在登录后那样。返回访客 id。
参数接受
id 可选any
示例
<do>@acting_as_guest()</do>
@acting_as_guest()

#@api_token(user, name?, expires?: duration) → string

为用户创建一个 API 令牌并返回该令牌。令牌只显示一次,系统只保存其哈希值。发送 Authorization: Bearer <token> 的请求会以该用户身份登录(认证中间件会放行)。expires 为令牌的有效期,例如 30d;默认情况下,令牌一直有效,直到被撤销。
参数接受
user 必填任意值
name 可选任意值
expires 可选duration

参数可以按名称指定:@api_token(…, name: …, expires: …)。

示例
<let name="token" value="@api_token(@user(), name: 'laptop')" />
$token = @api_token(@user(), name: 'laptop')

#@api_tokens(user) → list

用户的 API 令牌列表,不包含令牌本身:[{ id, name, created_at, last_used_at, expires_at }]。
示例
<for each="t" in="@api_tokens(@user())"><echo>{ $t.name }</echo></for>
for t in @api_tokens(@user()) {
  echo $t.name
}

#@attempt(email, password, remember?: bool, session?: bool) → map

使用邮箱和密码登录用户:返回该用户;若不匹配则返回 null。session: false 仅进行验证,适用于以令牌而非 cookie 作答的 API。同一邮箱和地址在 http.auth.lockout(一分钟)内失败达到 http.auth.attempts(5 次)后,将抛出 TooManyRequests 错误并说明需等待的时间(kscript serve 会以 429 响应)。
参数接受
email 必填任意值
password 必填任意值
remember 可选标志:remember 或 not remember
session 可选标志:session 或 not session

参数可以按名称指定:@attempt(…, password: …, remember: …)。

示例
<let name="user" value="@attempt($form.email, $form.password, remember: $form.remember)" />
$user = @attempt($form.email, $form.password, remember: $form.remember)

#@authorize(ability, target) → any

除非模型的策略允许该用户使用此权限,否则将中止:抛出 Forbidden 错误(路由中为 403),或对被该权限拒绝的访客抛出 Unauthorized(401,或跳转至登录页)。返回目标对象,因此可以链式调用。

参数可以按名称指定:@authorize(…, target: …)。

示例
<do>@authorize(update, $post)</do>
@authorize(update, $post)

#@can(ability, target) → bool

当模型的策略允许该用户对某条记录使用此权限时返回 true:@can(update, $post)。对于尚无记录的权限,请指定模型:@can(create, Post)。用户为已登录用户;访客则为 null。

参数可以按名称指定:@can(…, target: …)。

示例
<if test="@can(update, $post)"><echo>Edit</echo></if>
if @can(update, $post) {
  echo 'Edit'
}

#@cannot(ability, target) → bool

与 @can 相反:当策略不允许该用户使用此权限时返回 true。

参数可以命名:@cannot(…, target: …)。

示例
<if test="@cannot(update, $post)"><echo>Read only</echo></if>
if @cannot(update, $post) {
  echo 'Read only'
}

#@csrf_field() → string

在每个 <form method="post"> 中写入 {! @csrf_field() },即可放入保存 CSRF 令牌的隐藏表单字段。
示例
<form method="post" action="/login">{! @csrf_field() }</form>
form(method: 'post', action: '/login') "{! @csrf_field() }"

#@csrf_token() → string

会话的 CSRF 令牌。表单会以 _token 字段回传,脚本则以 X-CSRF-Token 请求头回传。
示例
<meta name="csrf-token" content="{ @csrf_token() }" />
meta(name: 'csrf-token', content: @csrf_token())

#@file_users() → list

以文件形式保存在应用数据文件夹中的用户,与 http.auth.users 以模型保存时一样:每个用户包含其 id、password_hash,以及作为日期的 created_at 和 updated_at。用于迁移的 Run 块,可将它们以原有 id 复制到 User 模型中。
示例
<echo>{ @file_users()->count() } people signed up before the users moved into a model</echo>
echo "{ @file_users()->count() } people signed up before the users moved into a model"

#@guest() → any

浏览器的访客 id:其 Guest 记录的键(一个 uuid,除非你的 Guest 副本另有规定),保存在长期有效的 Cookie 中(http.auth.guest_lifetime,默认为一年),并在首次读取时生成。用户登录后或在请求之外时为 null。访客创建的可归属记录归其所有。
示例
<echo>{ @guest() }</echo>
echo @guest()

#@has_passkeys() → bool

若本站已配置通行密钥来源,则为 true。
示例
<if test="@has_passkeys()"><button type="button" passkey="login">Sign in with a passkey</button></if>
if @has_passkeys() {
  button(type: 'button', passkey: 'login') "Sign in with a passkey"
}

#@intended(default?) → string

登录后前往的地址:身份验证中间件将用户带离的页面,否则为 default(http.auth.home,即 /)。它始终是本站的路径。
示例
<return value="@redirect(@intended())" />
return @redirect(@intended())

#@is_confirmed(within?: duration) → bool

若已登录用户在此时间范围内登录或验证过通行密钥(默认为 http.auth.confirm_within,即 5 分钟),则为 true。在执行无法撤销的操作(例如删除账户)之前,请要求进行通行密钥验证。
参数接受
within 可选duration
示例
<if test="!@is_confirmed()"><button type="button" passkey="login">Confirm it's you</button></if>
if !@is_confirmed() {
  button(type: 'button', passkey: 'login') "Confirm it's you"
}

#@is_signed_in() → bool

若有用户已登录(通过会话或 API 令牌),则为 true。
示例
<if test="@is_signed_in()"><echo>Welcome back</echo></if>
if @is_signed_in() {
  echo 'Welcome back'
}

#@login(user, remember?: bool) → map

让用户登录:会话会获得新的 id 和用户信息。remember 会在浏览器关闭后,为用户保持 http.auth.remember(30 天)的登录状态。用户是包含 id 的 map,可来自 @register()、@users()->find(),或你自己的存储。
参数接受
user 必填任意值
remember 可选标志:remember 或 not remember

参数可以命名:@login(…, remember: …)。

示例
<do>@login($user, remember: true)</do>
@login($user, remember: true)

#@logout(everywhere?: bool)

退出登录:会话结束,其 Cookie 被移除。everywhere 会结束该用户在所有设备上的会话。
参数接受
everywhere 可选标志:everywhere 或 not everywhere
示例
<do>@logout()</do>
@logout()

#@oidc_abort(uid) → string

结束登录步骤但不登录:应用会收到 access_denied。返回下一步要将浏览器跳转到的地址,或 null。
示例
<let name="next" value="@oidc_abort($params.uid)" />
$next = @oidc_abort($params.uid)

#@oidc_account_deleted(user) → number

用户账户被删除时调用:其应用授权会被撤销,每个设有 account_deletion_uri 的应用都会收到一条已签名的账户清除通知,直至其响应为止。返回已加入队列的通知数量。
示例
<do>@oidc_account_deleted($user)</do>
@oidc_account_deleted($user)

#@oidc_connections() → list

已登录用户授权登录的应用,按最新排序:client_id、client_name、scopes、granted_at 和 last_used_at(自 1970 年起的秒数)。
示例
<for each="app" in="@oidc_connections()"><echo>{ $app.client_name }</echo></for>
for app in @oidc_connections() {
  echo $app.client_name
}

#@oidc_consent(uid, allow: bool) → string

处理同意步骤:allow 表示允许应用从此时起查看其所请求的内容;否则应用会收到 access_denied。返回下一步要将浏览器跳转到的地址;若该步骤不属于此浏览器,则为 null。
参数接受
uid 必填任意值
allow 必填标志:allow 或 not allow

参数可以命名:@oidc_consent(…, allow: …)。

示例
<let name="next" value="@oidc_consent($params.uid, allow: $form.decision == 'allow')" />
$next = @oidc_consent($params.uid, allow: $form.decision == 'allow')

#@oidc_data_exports(user) → list

一次性询问每个设有 data_export_uri 的应用其持有的该用户数据副本,用于用户的数据下载:每个应用返回一个 map,包含 client_id、client_name、included(若应用在 30 秒内无法被询问,或未返回 JSON 对象,则为 false)以及 data,即其返回的对象。
示例
<let name="apps" value="@oidc_data_exports(@user())" />
$apps = @oidc_data_exports(@user())

#@oidc_disconnect(client_id) → bool

撤销已登录用户对某应用的访问权限:该应用的令牌立即失效,下次会重新请求授权。若该应用原先有访问权限,则为 true。
示例
<do>@oidc_disconnect($form.client_id)</do>
@oidc_disconnect($form.client_id)

#@oidc_interaction(uid) → map

应用发送给此浏览器的登录步骤(http.auth.provider),对应页面 {interaction}/{uid}:uid、prompt(login 或 consent)、client_id、client_name、return_host、scopes、ui_locales、login_hint,以及 resume,即步骤完成后要将浏览器跳转到的地址。除非此浏览器发起了该步骤且尚未过期,否则为 null。
示例
<let name="sign_in" value="@oidc_interaction($params.uid)" />
$sign_in = @oidc_interaction($params.uid)

#@oidc_subscriptions(user, blocking_only?: bool) → list

一次性询问每个设有 subscriptions_uri 的应用,用户在这些应用中有哪些订阅,用于在删除账户之前检查:每个应用返回一个 map,包含 client_id、client_name、blocking、checked(若无法询问该应用则为 false)、subscriptions(name、store、renews、ends_at、manage_url),以及 blocks(该应用设有 block_deletion_with_subscriptions 且仍在续订中的订阅)。blocking_only 仅询问这些应用。
参数接受
user 必填任意值
blocking_only 可选标志:blocking_only 或 not blocking_only

参数可以命名:@oidc_subscriptions(…, blocking_only: …)。

示例
<let name="held" value="@oidc_subscriptions(@user(), blocking_only: true)->filter(fn(app) => $app.blocks)" />
$held = @oidc_subscriptions(@user(), blocking_only: true)->filter(fn(app) => $app.blocks)

#@openid_finish() → 映射

完成通过其他网站账户的登录,在 redirect_uri 路由上进行:检查 state,将 code 换取为 ID token,并检查其签名、issuer、audience、时间和 nonce。返回 status(signed_in、declined、expired 或 failed)、sub、name、email 和 claims(仅 signed_in 时),以及 error(出错原因)和 return_to(传给 @openid_start() 的路径)。它不会让任何人登录:请通过 sub 查找或添加你的用户,然后为其调用 @login()。
示例
<let name="result" value="@openid_finish()" />
$result = @openid_finish()

#@openid_logout_url(id_token?: string) → 字符串

对方网站的退出登录地址,在 @logout() 之后重定向到该地址,以便该用户也在对方网站上退出登录,并返回到 logout_redirect_uri。提供方没有此地址时为 null。
参数接受
id_token 可选string
示例
<return value="@redirect(@openid_logout_url() ?? '/')" />
return @redirect(@openid_logout_url() ?? '/')

#@openid_notice(body: string) → 映射

检查登录提供方发送的已签名通知(安全事件令牌,application/secevent+jwt),例如该提供方中的某个账户被删除时发送的通知。返回 event(purged,附带 sub,即已被删除的账户;或 verification,即提供方的试运行),并且 error 为 null;或返回 error(invalid_request、authentication_failed、invalid_issuer 或 invalid_audience)和 description,用于以 400 响应。
参数接受
body 必需string
示例
<let name="notice" value="@openid_notice($body)" />
$notice = @openid_notice($body)

#@openid_question(body: string) → 映射

检查登录提供方就某个人发送的问题(application/jwt):data-export-query+jwt,询问应用为其保存了哪些数据,以供其下载数据;或 subscriptions-query+jwt,在其账户被删除前询问其订阅了哪些内容。返回 question(data_export 或 subscriptions)和 sub(被询问的账户),并且 error 为 null;或返回 error(invalid_request、authentication_failed、invalid_issuer 或 invalid_audience)和 description,用于以 400 响应。
参数接受
body 必需string
示例
<let name="asked" value="@openid_question($body)" />
$asked = @openid_question($body)

#@openid_start(return_to?: string, params?: map) → 字符串

开始使用其他网站的账户为某人登录(http.auth.sign_in_with):在会话中保存一个新的 state、nonce 和 PKCE verifier,并给出将浏览器重定向到的提供方地址。return_to 是 @openid_finish() 将其送回的位置(本站的路径;其他任何值都会变为 /);params 会添加到提供方的查询参数中,例如 { ui_locales: 'fr' }。
参数接受
return_to 可选string
params 可选map

参数可以命名:@openid_start(…, params: …)。

示例
<return value="@redirect(@openid_start($query.return_to))" />
return @redirect(@openid_start($query.return_to))

#@passkey(action, step, body) → map

从应用自身的 POST 路由运行通行密钥流程的一个步骤,与 /_ks/passkeys/{action}/{step} 的方式相同:action 为 login、register 或 signup,step 为 options 或 verify,body 为浏览器发送的 JSON。以 map 形式返回给浏览器的响应。检查失败时会抛出异常(Forbidden、Validation 或 Unauthorized)。

参数可以命名:@passkey(…, step: …, body: …)。

示例
<let name="options" value="@passkey('login', 'options', $request.body)" />
$options = @passkey('login', 'options', $request.body)

#@passkeys() → list

列出已登录会话用户在本站的通行密钥:每个通行密钥的 id、created_at、last_used_at(在其首次用于登录前为 null),以及 synced(若为已备份的通行密钥,例如保存在密码管理器中的,则为 true)。
示例
<for each="key" in="@passkeys()"><echo>{ $key.created_at }</echo></for>
for key in @passkeys() {
  echo $key.created_at
}

#@register(email, password, fields...: User) → map

添加一个用户并返回该用户(不会让其登录)。邮箱和密码分别由 email 和 password 类型检查,并遵循你项目的规则(kscript.json 中的 "types": { "password": { "min": 12 } });若存在问题,或邮箱已被占用,则抛出 Validation 错误并指明字段。密码仅以 argon2id 哈希形式保存。其他命名值则作为用户的字段保存。
参数接受
email 必填任意值
password 必填任意值
fieldsUser,任意数量

参数可以命名:@register(…, password: …, fields: …)。

示例
<let name="user" value="@register($form.email, $form.password, name: $form.name)" />
$user = @register($form.email, $form.password, name: $form.name)

#@reset_password(token, password) → map

完成密码重置:为令牌对应的用户设置新密码(由 password 类型检查),并结束其会话。返回该用户;若令牌错误、已使用或已过期,则返回 null。

参数可以命名:@reset_password(…, password: …)。

示例
<let name="user" value="@reset_password($form.token, $form.password)" />
$user = @reset_password($form.token, $form.password)

#@reset_token(email) → string

开始密码重置:返回一个令牌,放入你通过邮件发给用户的链接中;如果没有用户使用该邮箱,则返回 null。该令牌只能使用一次,有效期为 http.auth.reset_lifetime(一小时),新令牌会替换旧令牌。无论邮箱是否存在,都告诉用户相同的内容,以免页面泄露谁拥有账户。
示例
<let name="token" value="@reset_token($form.email)" />
$token = @reset_token($form.email)

#@revoke_passkey(id) → bool

撤销已登录会话用户的某个通行密钥(按其 id)。成功移除时返回 true。
示例
<do>@revoke_passkey($id)</do>
@revoke_passkey($id)

#@revoke_token(token, user?) → bool

撤销一个 API 令牌,可传入令牌本身或其 id(来自 @api_tokens())。传入 user 时,只撤销该用户自己的令牌,因此页面可以让用户撤销自己的令牌。若存在该令牌则返回 true。

参数可以使用具名形式:@revoke_token(…, user: …)。

示例
<do>@revoke_token($id)</do>
@revoke_token($id)

#@user() → map

已登录的用户(一个包含 id、email 以及注册时所填字段的 map),访客则返回 null。信息来自会话 Cookie,或来自 API 令牌(Authorization: Bearer)。
示例
<if test="@user() != null"><echo>Hello { @user().email }</echo></if>
if @user() != null {
  echo "Hello { @user().email }"
}

#@users() → users

应用的用户,保存在其数据文件夹中:->find(id)、->find_email(email)、->all()、->count()、->verify(email, password)、->update(id, ...)、->set_password(id, password)、->delete(id)。
示例
<echo>{ @users()->count() } people have signed up</echo>
echo "{ @users()->count() } people have signed up"

#@verification_token(user, expires?: duration) → string

一个用于证明用户拥有其邮箱地址的令牌,放入邮箱验证邮件的链接中:@route('verification.verify', token: @verification_token($user))。它使用应用的密钥(KSCRIPT_SECRET)签名,包含用户及其邮箱信息,在 expires 指定的时间内有效(默认一小时),或直到其邮箱发生变化为止。不保存任何数据:由 @verify_email() 进行校验。
参数接受
user 必填任意值
expires 可选duration

参数可以使用具名形式:@verification_token(…, expires: …)。

示例
<let name="token" value="@verification_token(@user(), expires: 24h)" />
$token = @verification_token(@user(), expires: 24h)

#@verify_email(token) → map

完成邮箱验证:将令牌所属用户的 email_verified_at 设为当前时间,并返回该用户;如果令牌错误、已过期,或是为用户已不再使用的邮箱生成的,则返回 null。已验证的用户保留其首次验证的时间。verified 中间件只允许已验证的用户通过。
示例
<let name="user" value="@verify_email($token)" />
$user = @verify_email($token)

方法

关于 session 的值:->get()、->has()、->set()、->flash()、->remove()、->pull()、->clear()、->all()、->regenerate()

关于 users 的值:->find()、->find_email()、->all()、->count()、->verify()、->update()、->set_password()、->delete()

变量

变量类型说明
$sessionsession请求的会话:通过 Cookie 在请求之间保留的值。$session->set('cart', $items)、$session->get('cart'),以及用于重定向后显示消息的 $session->flash('status', 'Saved')。

模型与 mixin

KScript.Auth 内置了以下内容,均使用 KScript 编写:

  • User,一个模型:拥有账户的人。当 kscript.json 中设置 "http": { "auth": { "users": "User" } } 时,KScript.Auth 会将用户保存在此模型中:@register 创建用户,而 @user() 返回的就是该用户。
  • Guest,一个模型:未使用账户而使用应用的人。每个浏览器都会获得一个,保存在长期有效的 Cookie 中,并在其首次拥有记录时存储。其键即 @guest() 的返回值。它……
  • Ownable,一个 mixin:属于某一所有者的记录:已登录的用户,或浏览器的访客。继承 Ownable 的模型会同时获得 user 和 guest 两个字段,其中一个会根据创建记录的人自动填充……

每个模型接受的选项以及所有内置 mixin:模型与 mixin。