From 69196cfe8ff7488026666f070b231b8b15ca046e Mon Sep 17 00:00:00 2001 From: johnabass Date: Mon, 26 Aug 2024 15:06:38 -0700 Subject: [PATCH] working example of augmenting a token --- authenticator_examples_test.go | 57 ++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 authenticator_examples_test.go diff --git a/authenticator_examples_test.go b/authenticator_examples_test.go new file mode 100644 index 0000000..def9eeb --- /dev/null +++ b/authenticator_examples_test.go @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: 2024 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package bascule + +import ( + "context" + "fmt" +) + +type Extra struct { + Name string + Age int +} + +func (e Extra) Principal() string { return e.Name } + +// ExampleJoinTokens_augment shows how to augment a Token as part +// of authentication workflow. +func ExampleJoinTokens_augment() { + original := StubToken("original") + authenticator, _ := NewAuthenticator[string]( + WithTokenParsers( + StubTokenParser[string]{ + Token: original, + }, + ), + WithValidators( + AsValidator[string]( + func(t Token) (Token, error) { + // augment this token with extra information + return JoinTokens(t, Extra{Name: "extra", Age: 33}), nil + }, + ), + ), + ) + + authenticated, _ := authenticator.Authenticate( + context.Background(), + "source", + ) + + fmt.Println("authenticated principal:", authenticated.Principal()) + + var extra Extra + if !TokenAs(authenticated, &extra) { + panic("token cannot be converted") + } + + fmt.Println("extra.Name:", extra.Name) + fmt.Println("extra.Age:", extra.Age) + + // Output: + // authenticated principal: original + // extra.Name: extra + // extra.Age: 33 +}