Tokens

Tokens( [database] )
Tokens( )
ScopedTokens( database )
Tokens( [database] )
Tokens( [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

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:

    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))
    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]
    System.out.println(
        client.query(
            Login(
                Match(Index("users_by_email"), Value("alice@site.example.com")),
                Obj("password", Value("secret password"))
            )
        ).get());
    {ref: ref(id = "251501214465786368", collection = ref(id = "tokens")), ts: 1576109098790000, instance: ref(id = "251407645221585408", collection = ref(id = "users", collection = ref(id = "collections"))), secret: "fnEDfYMFpNACAAN9IwrU8AIAci6OvrScKEoSVSpbfZq7_LfCpeA"}
    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'}
    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:

    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))
    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]
    System.out.println(
        client.query(
            Create(
                Tokens(),
                Obj("instance", Ref(Collection("users"), Value("1")))
            )
        ).get());
    {ref: ref(id = "293498073803391488", collection = ref(id = "tokens")), ts: 1616160424910000, instance: ref(id = "1", collection = ref(id = "users", collection = ref(id = "collections"))), secret: "fnEEErbxb1ACAAQStu-OYAYA14OfYlj7hD7jbg8uI73gZGZHp3g"}
    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'}
    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):

    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))
    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>}]
    System.out.println(
        client.query(
            Create(
                Tokens(),
                Obj(
                    "instance", Ref(Collection("users"), Value("1")),
                    "ttl", TimeAdd(Now(), 2, "days")
                )
            )
        ).get());
    {ref: ref(id = "294155372234539520", collection = ref(id = "tokens")), ts: 1616787273540000, instance: ref(id = "1", collection = ref(id = "users", collection = ref(id = "collections"))), ttl: 2021-03-28T19:34:33.528Z, secret: "fnEEFQzAptACAAQVDL7JYAYAzLPtSdFzHxT2a4WYjMbHi4OhB9I"}
    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'}
    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

    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"))))
    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>}]]
    System.out.println(
        client.query(
            Paginate(Tokens())
        ).get());
    {data: [ref(id = "1", collection = ref(id = "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))]}
    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":

    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())
    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:[]]
    System.out.println(
        client.query(
            Paginate(Tokens(Database("child_db")))
        ).get());
    {data: []}
    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': []}
    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:

    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))
    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]]]]
    System.out.println(
        client.query(
            CreateIndex(
                Obj(
                    "name", Value("tokens_by_instance"),
                    "permissions", Obj("read", Value("public")),
                    "source", Tokens(),
                    "terms", Arr(Obj("field", Value("instance"))),
                    "values", Arr(
                        Obj("field", Arr(Value("data"), Value("name")))
                    )
                )
            )
        ).get());
    {ref: ref(id = "tokens_by_instance", collection = ref(id = "indexes")), ts: 1594335339530000, active: true, serialized: true, name: "tokens_by_instance", permissions: {read: "public"}, source: ref(id = "tokens"), terms: [{field: "instance"}], values: [{field: ["data", "name"]}], partitions: 1}
    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}
    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:

    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)))
    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]
    System.out.println(
        client.query(
            Update(
                Ref(Tokens(), "1"),
                Obj("data", Obj("meta", Value("data")))
            )
        ).get());
    {ref: ref(id = "251501214465786368", collection = ref(id = "tokens")), ts: 1576109098880000, instance: ref(id = "251407645221585408", collection = ref(id = "users", collection = ref(id = "collections"))), data: {meta: "data"}}
    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'}}
    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!