KScript docs
EN

Sign-in: KScript.Auth

API tokens

@api_token(user, name?, expires?) makes a token for a user. Show it once, because only its hash is kept. A request that sends Authorization: Bearer <token> is signed in as that user, so @user() and the auth middleware work as they do with a session. expires is a time such as '30d'. Without it, a token lasts until it is revoked.

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

<fn name="issue_token" params="json: map">
  <let name="user" value="@attempt($json.email, $json.password, not session)" />
  <if $user == null>
    <throw type="Unauthorized">That email and password don't match an account.</throw>
  </if>
  <return value="@response({ token: @api_token($user, name: 'cli', expires: 30d) }, status: 201)" />
</fn>
import KScript.Http
import KScript.Auth

fn issue_token(json: map) {
  $user = @attempt($json.email, $json.password, not session)
  if $user == null {
    throw Unauthorized "That email and password don't match an account."
  }
  return @response({ token: @api_token($user, name: 'cli', expires: 30d) }, status: 201)
}

@api_tokens(user) lists a user's tokens without the tokens themselves: [{ id, name, created_at, last_used_at, expires_at }]. @revoke_token(token or id, user?) revokes one. With user, it only revokes a token that belongs to that user, so an account page can let people revoke their own.

Edit this page on GitHub