Tokens

Tokens( )
Tokens( )
Tokens( )
Tokens( )
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.

Due to implementation details, Paginate(Tokens()) does not list existing tokens. See the Examples.

Parameters

None.

Returns

None.

Examples

  1. List existing tokens

    The following query lists any 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', err))
    { data: [ Ref(Tokens(), "255391018093904394") ] }
    result = client.query(
      q.paginate(q.tokens())
    )
    print(result)
    {'data': [Ref(id=1, collection=Ref(id=tokens))]}
    try {
      println(Await.result(
      client.query(
        Paginate(Tokens())
      ),
      5.seconds
    ))} catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    {data: [ref(id = "1", collection = ref(id = "tokens"))]}
  2. 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', err))
    {
      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: [Array] } ],
      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}
    try {
      println(Await.result(
      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")))
          )
        )
      ),
      5.seconds
    ))} catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    {name: "tokens_by_instance", source: ref(id = "tokens"), ts: 1576105489780000, permissions: {read: "public"}, ref: ref(id = "tokens_by_instance", collection = ref(id = "indexes")), values: [{field: ["data", "name"]}], partitions: 1, terms: [{field: "instance"}], serialized: true, active: true}
  3. Modify a token

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

    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', err))
    { 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'}
    try {
      println(Await.result(
      client.query(
        Login(
          Match(Index("users_by_email"), "alice@site.example.com"),
          Obj("password" -> "secret password")
        )
      ),
      5.seconds
    ))} catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    {ref: ref(id = "251502310512919040", collection = ref(id = "tokens")), ts: 1576110144060000, instance: ref(id = "251407645221585408", collection = ref(id = "users", collection = ref(id = "collections"))), secret: "fnEDfYQE1lACAAN9IwrU8AIAaicAc8rxWsP_rUoTiLjYK00NRI4"}

    In the following query, we use the token’s reference, from the previous query, 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', err))
    { 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'}}
    try {
      println(Await.result(
      client.query(
        Update(
          Ref(Tokens(), "1"),
          Obj("data" -> Obj("meta" -> "data"))
        )
      ),
      5.seconds
    ))} catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    {ref: ref(id = "251502310512919040", collection = ref(id = "tokens")), ts: 1576110144160000, instance: ref(id = "251407645221585408", collection = ref(id = "users", collection = ref(id = "collections"))), data: {meta: "data"}}

Was this article helpful?

We're sorry to hear that.
Tell us how we can improve!
Visit Fauna's Discourse forums or email docs@fauna.com

Thank you for your feedback!