Skip to content

Instantly share code, notes, and snippets.

@n400
Last active May 26, 2020 10:54
Show Gist options
  • Save n400/00f6ec6831469df7259b703fb9df1fef to your computer and use it in GitHub Desktop.
Save n400/00f6ec6831469df7259b703fb9df1fef to your computer and use it in GitHub Desktop.
Unofficial documentation on FaunaDB's Tokens() function

Tokens

Tokens( )

Description

The Tokens function provides access to the system collection that stores access tokens, created with the Login function. This is useful for:

  • Listing currently existing tokens
  • Creating tokens without credentials
  • Indexing tokens so that you can query tokens based on relationships with other documents.

If you have a reference to a specific token, acquired with Login, you can add custom fields to the token’s document using Update or Replace. Access tokens can be invalidated by calling Logout.

Examples

List existing tokens

The following query lists any existing tokens:

Paginate(Documents(Tokens()))

or

client.query(
  q.Paginate(q.Documents(q.Tokens()))
)
.then((ret) => console.log(ret))

Use Tokens() in an index

The following query creates an index on the internal tokens collection, so that tokens associated with a specific service can be queried:

client.query(
  q.CreateIndex({
    name: 'tokens_by_instance',
    permissions: { read: 'public' },
    source: q.Tokens(),
    terms: [ { field: 'instance' } ],
    values: [ { field: ['data', 'name'] } ],
  })
)
.then((ret) => console.log(ret))
{ ref: Index("tokens_by_instance"),
  ts: 1576104922970000,
  active: false,
  serialized: true,
  name: 'tokens_by_instance',
  permissions: { read: 'public' },
  source: Tokens(),
  terms: [ { field: 'instance' } ],
  values: [ { field: [Array] } ],
  partitions: 1 }

Modify a token

The following query generates a token by calling Login():

client.query(
  q.Login(
    q.Match(q.Index('users_by_email'), 'alice@site.example'),
    { password: 'new password' },
  )
)
.then((ret) => console.log(ret))
{ ref: Ref(Tokens(), "251500495731950080"),
  ts: 1576108413380000,
  instance: Ref(Collection("users"), "251407645221585408"),
  secret: 'fnEDfYJeTPACAAN9IwrU8AIAItH5Pfj5cqbybb_JmqNOncUKI14' }

In the following query, we use the token’s reference, from the previous query, to update the token with some metadata:

client.query(
  q.Update(
    q.Ref(q.Tokens(), '251500495731950080'),
    { data: { meta: 'data' } }
  )
)
.then((ret) => console.log(ret))
{ ref: Ref(Tokens(), "251500495731950080"),
  ts: 1576108413460000,
  instance: Ref(Collection("users"), "251407645221585408"),
  data: { meta: 'data' } }
@fauna-brecht
Copy link

The creation of tokens is missing :)

Create(Tokens(), {
instance: < reference to a document>
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment