FQL v4 will be decommissioned on June 30, 2025. Ensure that you complete your migration from FQL v4 to FQL v10 by that date.

For more details, see the v4 EOL announcement and migration guide. Contact support@fauna.com with any questions.

Tokens

This reference topic applies to FQL v4. Go to this page for the latest FQL v10 reference topics.

Tokens( [database] )
tokens( [database] )
Tokens( )
ScopedTokens( database )
Tokens( [database] )
Tokens( [database] )

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.

A token’s instance field contains a Reference to the associated identity document. See Tokens for details.

Parameters

Parameter Type Definition and requirements

database

Reference

Optional - A Reference to a child database. If not specified, the current database is used.

A Reference to a child database.

Optional - A Reference to a child database. If not specified, the current database is used.

Optional - A Reference to a child database. If not specified, the current database is used.

Optional - A Reference to a child database. If not specified, the current database is used.

Optional - A Reference to a child database. If not specified, the current database is used.

Optional - A Reference to a child database. If not specified, the current database is used.

Returns

An Set Reference for the available Tokens in the specified child database, or the current database if database is not specified.

Examples

  1. Create a token

    The following query lists any existing tokens (up to the pagination limit) in the current database:

    client.query(
      q.Login(
        q.Match(q.Index('users_by_email'), 'alice@site.example.com'),
        { password: 'secret password' },
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    { ref: Ref(Tokens(), "251500495731950080"),
      ts: 1576108413380000,
      instance: Ref(Collection("users"), "251407645221585408"),
      secret: 'fnEDfYJeTPACAAN9IwrU8AIAItH5Pfj5cqbybb_JmqNOncUKI14' }
    result = client.query(
      q.login(
        q.match(q.index("users_by_email"), "alice@site.example.com"),
        {"password": "secret password"},
      )
    )
    print(result)
    {'ref': Ref(id=251502661795316224, collection=Ref(id=tokens)), 'ts': 1576110479070000, 'instance': Ref(id=251407645221585408, collection=Ref(id=users, collection=Ref(id=collections))), 'secret': 'fnEDfYRWoGACAAN9IwrU8AIAFwnfIh4vM_28LzJqFIP_45o8X2Q'}
    result, err := client.Query(
    	f.Login(
    		f.MatchTerm(f.Index("users_by_email"), "alice@site.example.com"),
    		f.Obj{"password": "secret password"},
    	))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[instance:{1 0xc00008e510 0xc00008e510 <nil>} ref:{280481975565812224 0xc00008e360 0xc00008e360 <nil>} secret:fnED5Hje54ACAAPkeN55YAYAIveL6bdkDgZ0-2-Eng567vL_H_0 ts:1603747306320000]
    try
    {
        Value result = await client.Query(
            Login(
                Match(Index("users_by_email"), "alice@site.example.com"),
                Obj("password", "secret password")
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(ref: RefV(id = "280491974570541568", collection = RefV(id = "tokens")),ts: LongV(1603756842110000),instance: RefV(id = "1", collection = RefV(id = "users", collection = RefV(id = "collections"))),secret: StringV(fnED5IH2-qACAAPkgfXLUAYAx7PIdaBJcNJko75-RceyXHxk4PA))
    Login(
      Match(Index('users_by_email'), 'alice@site.example.com'),
      { password: 'secret password' },
    )
    {
      ref: Ref(Tokens(), "302044099688530432"),
      ts: 1624310550300000,
      instance: Ref(Collection("users"), "1"),
      secret: 'fnEEMROCJHACAAQxE4GIcAIADYV7pzCKqnsAm8N0nsY1vlCMJYQ'
    }
    Query metrics:
    •    bytesIn:  130

    •   bytesOut:  291

    • computeOps:    1

    •    readOps:    1

    •   writeOps:    1

    •  readBytes:  295

    • writeBytes:  414

    •  queryTime: 50ms

    •    retries:    0

    You can also create a token directly, without knowing the credentials for an identity document:

    client.query(
      q.Create(
        q.Tokens(),
        { instance: q.Ref(q.Collection('users'), '1') },
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    {
      ref: Ref(Tokens(), "293497693263626752"),
      ts: 1616160062000000,
      instance: Ref(Collection("users"), "1"),
      secret: 'fnEEEraY1WACAAQStphjIAYALk1agYtuTK3v_x8KTSs7bpe2scg'
    }
    result = client.query(
      q.create(
        q.tokens(),
        {"instance": q.ref(q.collection("users"), "1")},
      )
    )
    print(result)
    {'ref': Ref(id=293498079059902976, collection=Ref(id=tokens)), 'ts': 1616160429920000, 'instance': Ref(id=1, collection=Ref(id=users, collection=Ref(id=collections))), 'secret': 'fnEEErbyqKACAAQStvIo8AYA8p8sN07-yrVgDzXke1NWRgnqxCc'}
    result, err := client.Query(
    	f.Create(
    		f.Tokens(),
    		f.Obj{"instance": f.Ref(f.Collection("users"), "1")},
    	))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[instance:{1 0xc00014c270 0xc00014c270 <nil>} ref:{293498065541661184 0xc00014c0c0 0xc00014c0c0 <nil>} secret:fnEEErbvguACAAQStu7jYAIAEIJ3Z3UMa7-cr_-6IVyErFg9ua4 ts:1616160417020000]
    try
    {
        Value result = await client.Query(
            Create(
                Tokens(),
                Obj("instance", Ref(Collection("users"), "1"))
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(ref: RefV(id = "293498062688485888", collection = RefV(id = "tokens")),ts: LongV(1616160414310000),instance: RefV(id = "1", collection = RefV(id = "users", collection = RefV(id = "collections"))),secret: StringV(fnEEErbu2NACAAQStu1CoAIAR6v4yT6ii450sVhEfdcttH3eLhE))
    Create(
      Tokens(),
      { instance: Ref(Collection('users'), '1') },
    )
    {
      ref: Ref(Tokens(), "302044084418118144"),
      ts: 1624310535730000,
      instance: Ref(Collection("users"), "1"),
      secret: 'fnEEMRN-lkACAAQxE33O0AYA3fbFMCO_kONC35tJ2tPZIMoJ4Lc'
    }
    Query metrics:
    •    bytesIn:   99

    •   bytesOut:  291

    • computeOps:    1

    •    readOps:    0

    •   writeOps:    1

    •  readBytes:    0

    • writeBytes:  414

    •  queryTime: 39ms

    •    retries:    0

    When you create a token directly, you can also set its ttl (time to live):

    client.query(
      q.Create(
        q.Tokens(),
        {
          instance: q.Ref(q.Collection('users'), '1'),
          ttl: q.TimeAdd(q.Now(), 2, 'days'),
        },
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    {
      ref: Ref(Tokens(), "294155374728053248"),
      ts: 1616787275910000,
      instance: Ref(Collection("users"), "1"),
      ttl: Time("2021-03-28T19:34:35.900Z"),
      secret: 'fnEEFQzBO3ACAAQVDMDIIAYAvxbzRoRT6Tax-k8N9fGhR2ledDk'
    }
    result = client.query(
      q.create(
        q.tokens(),
        {
          "instance": q.ref(q.collection("users"), "1"),
          "ttl": q.time_add(q.now(), 2, "days"),
        },
      )
    )
    print(result)
    {'ref': Ref(id=294155377506779648, collection=Ref(id=tokens)), 'ts': 1616787278560000, 'instance': Ref(id=1, collection=Ref(id=users, collection=Ref(id=collections))), 'ttl': FaunaTime('2021-03-28T19:34:38.550Z'), 'secret': 'fnEEFQzB4RACAAQVDMFlQAYAGniNtprOy79A7nWPQ8TVJfD-6zg'}
    result, err := client.Query(
    	f.Create(
    		f.Tokens(),
    		f.Obj{
    			"instance": f.Ref(f.Collection("users"), "1"),
    			"ttl": f.TimeAdd(f.Now(), 2, "days"),
    		},
    	))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[instance:{1 0xc000184660 0xc000184660 <nil>} ref:{294155364114366976 0xc0001844b0 0xc0001844b0 <nil>} secret:fnEEFQy-wtACAAQVDL37gAIADRiIr6AEwLSUV0A7XJJCKJO32x8 ts:1616787265790000 ttl:{780000000 63752556865 <nil>}]
    try
    {
        Value result = await client.Query(
            Create(
                Tokens(),
                Obj(
                    "instance", Ref(Collection("users"), "1"),
                    "ttl", TimeAdd(Now(), 2, "days")
                )
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(ref: RefV(id = "295343068397175296", collection = RefV(id = "tokens")),ts: LongV(1617919948860000),instance: RefV(id = "1", collection = RefV(id = "users", collection = RefV(id = "collections"))),ttl: FaunaTime(2021-03-28T19:34:28.857Z),secret: StringV(fnEEGUT0trACAAQZRPNp4AYAK_7_A4jRa6iPR5LJIRhzT8NIxYU))
    Create(
      Tokens(),
      {
        instance: Ref(Collection('users'), '1'),
        ttl: TimeAdd(Now(), 2, 'days'),
      },
    )
    {
      ref: Ref(Tokens(), "302044087434871296"),
      ts: 1624310538620000,
      instance: Ref(Collection("users"), "1"),
      ttl: Time("2021-06-23T21:22:18.607Z"),
      secret: 'fnEEMRN_ShACAAQxE36hQAYAWLgKxjGircfBLeB5z-IGW4eZU_Y'
    }
    Query metrics:
    •    bytesIn:  156

    •   bytesOut:  332

    • computeOps:    1

    •    readOps:    0

    •   writeOps:    1

    •  readBytes:    0

    • writeBytes:  430

    •  queryTime: 46ms

    •    retries:    0

  2. List existing tokens

    client.query(
      q.Paginate(q.Tokens())
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    { data: [ Ref(Tokens(), "255391018093904394") ] }
    result = client.query(
      q.paginate(q.tokens())
    )
    print(result)
    {'data': [Ref(id=1, collection=Ref(id=tokens))]}
    result, err := client.Query(
    	f.Paginate(f.Tokens()))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[data:[{1 0xc0000b7230 0xc0000b7230 <nil>}]]
    try
    {
        Value result = await client.Query(
            Paginate(Tokens())
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(data: Arr(RefV(id = "1", collection = RefV(id = "tokens"))))
    Paginate(Tokens())
    { data: [ Ref(Tokens(), "1") ] }
    Query metrics:
    •    bytesIn:  28

    •   bytesOut:  81

    • computeOps:   1

    •    readOps:   8

    •   writeOps:   0

    •  readBytes: 250

    • writeBytes:   0

    •  queryTime: 8ms

    •    retries:   0

    The following query lists the References for any tokens (up to the pagination limit) in a child database named "child_db":

    client.query(
      q.Paginate(q.Tokens(q.Database('child_db')))
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    { data: [] }
    result = client.query(
      q.paginate(q.tokens(q.database("child_db")))
    )
    print(result)
    {'data': []}
    result, err := client.Query(
    	f.Paginate(f.ScopedTokens(f.Database("child_db"))))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[data:[]]
    try
    {
        Value result = await client.Query(
            Paginate(Tokens(Database("child_db")))
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(data: Arr())
    Paginate(Tokens(Database('child_db')))
    { data: [] }
    Query metrics:
    •    bytesIn:   47

    •   bytesOut:   24

    • computeOps:    1

    •    readOps:    8

    •   writeOps:    0

    •  readBytes:  363

    • writeBytes:    0

    •  queryTime: 14ms

    •    retries:    0

  3. 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))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    {
      ref: Index("tokens_by_instance"),
      ts: 1592112574490000,
      active: true,
      serialized: true,
      name: 'tokens_by_instance',
      permissions: { read: 'public' },
      source: Tokens(),
      terms: [ { field: 'instance' } ],
      values: [ { field: [ 'data', 'name' ] } ],
      partitions: 1
    }
    result = client.query(
      q.create_index({
        "name": "tokens_by_instance",
        "permissions": {"read": "public"},
        "source": q.tokens(),
        "terms": [{"field": "instance"}],
        "values": [{"field": ["data", "name"]}]
      })
    )
    print(result)
    {'ref': Ref(id=tokens_by_instance, collection=Ref(id=indexes)), 'ts': 1592867275570000, 'active': True, 'serialized': True, 'name': 'tokens_by_instance', 'permissions': {'read': 'public'}, 'source': Ref(id=tokens), 'terms': [{'field': 'instance'}], 'values': [{'field': ['data', 'name']}], 'partitions': 1}
    result, err := client.Query(
    	f.CreateIndex(
    		f.Obj{
    			"name": "tokens_by_instance",
    			"permissions": f.Obj{"read": "public"},
    			"source": f.Tokens(),
    			"terms": f.Arr{f.Obj{"field": "instance"}},
    			"values": f.Arr{f.Obj{"field": f.Arr{"data", "name"}}}}))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[active:true name:tokens_by_instance partitions:1 permissions:map[read:public] ref:{tokens_by_instance 0xc00008e210 0xc00008e210 <nil>} serialized:true source:0x15326c0 terms:[map[field:instance]] ts:1603747302540000 values:[map[field:[data name]]]]
    try
    {
        Value result = await client.Query(
            CreateIndex(
                Obj(
                    "name", "tokens_by_instance",
                    "permissions", Obj("read", "public"),
                    "source", Tokens(),
                    "terms", Arr(Obj("field", "instance")),
                    "values", Arr(Obj("field", Arr("data", "name")))
                )
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(ref: RefV(id = "tokens_by_instance", collection = RefV(id = "indexes")),ts: LongV(1603756832100000),active: BooleanV(True),serialized: BooleanV(True),name: StringV(tokens_by_instance),permissions: ObjectV(read: StringV(public)),source: RefV(id = "tokens"),terms: Arr(ObjectV(field: StringV(instance))),values: Arr(ObjectV(field: Arr(StringV(data), StringV(name)))),partitions: LongV(1))
    CreateIndex({
      name: 'tokens_by_instance',
      permissions: { read: 'public' },
      source: Tokens(),
      terms: [ { field: 'instance' } ],
      values: [ { field: ['data', 'name'] } ],
    })
    {
      ref: Index("tokens_by_instance"),
      ts: 1624310541660000,
      active: true,
      serialized: true,
      name: 'tokens_by_instance',
      permissions: { read: 'public' },
      source: Tokens(),
      terms: [ { field: 'instance' } ],
      values: [ { field: [ 'data', 'name' ] } ],
      partitions: 1
    }
    Query metrics:
    •    bytesIn:   215

    •   bytesOut:   327

    • computeOps:     1

    •    readOps:     0

    •   writeOps:     1

    •  readBytes: 1,364

    • writeBytes:   484

    •  queryTime:  68ms

    •    retries:     0

  4. Modify a token

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

    client.query(
      q.Update(
        q.Ref(q.Tokens(), '1'),
        { data: { meta: 'data' } }
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    { ref: Ref(Tokens(), "251500495731950080"),
      ts: 1576108413460000,
      instance: Ref(Collection("users"), "251407645221585408"),
      data: { meta: 'data' } }
    result = client.query(
      q.update(
        q.ref(q.tokens(), "1"),
        {"data": {"meta": "data"}}
      )
    )
    print(result)
    {'ref': Ref(id=251502661795316224, collection=Ref(id=tokens)), 'ts': 1576110479090000, 'instance': Ref(id=251407645221585408, collection=Ref(id=users, collection=Ref(id=collections))), 'data': {'meta': 'data'}}
    result, err := client.Query(
    	f.Update(
    		f.Ref(f.Tokens(), "1"),
    		f.Obj{"data": f.Obj{"meta": "data"}},
    	))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    map[data:map[meta:data] instance:{1 0xc000174270 0xc000174270 <nil>} ref:{1 0xc0001740c0 0xc0001740c0 <nil>} ts:1603747308150000]
    try
    {
        Value result = await client.Query(
            Update(
                Ref(Tokens(), "1"),
                Obj("data", Obj("meta", "data"))
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    ObjectV(ref: RefV(id = "1", collection = RefV(id = "tokens")),ts: LongV(1603756847050000),instance: RefV(id = "1", collection = RefV(id = "users", collection = RefV(id = "collections"))),data: ObjectV(meta: StringV(data)))
    Update(
      Ref(Tokens(), '1'),
      { data: { meta: 'data' } }
    )
    {
      ref: Ref(Tokens(), "1"),
      ts: 1624310552760000,
      instance: Ref(Collection("users"), "1"),
      data: { meta: 'data' }
    }
    Query metrics:
    •    bytesIn:   99

    •   bytesOut:  234

    • computeOps:    1

    •    readOps:    0

    •   writeOps:    1

    •  readBytes:  138

    • writeBytes:  172

    •  queryTime: 63ms

    •    retries:    0

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!