From 779a61c97d39b0f61cfa5fae6c5b613e6ad352d7 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Fri, 4 Jun 2021 16:17:47 +0300 Subject: [PATCH] [#298] pkg/session: Implement methods to work with Token lifetime Implement `Exp`/`SetExp`/`Nbf`/`SetNbf`/`Iat`/`SetIat` methods on `Token` type which provide access to the message fields of the same name. Signed-off-by: Leonard Lyubich --- pkg/session/session.go | 57 +++++++++++++++++++++++++++++++++++++ pkg/session/session_test.go | 30 +++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/pkg/session/session.go b/pkg/session/session.go index e4076335..99b71a14 100644 --- a/pkg/session/session.go +++ b/pkg/session/session.go @@ -89,6 +89,63 @@ func (t *Token) SetSessionKey(v []byte) { }) } +func (t *Token) setLifetimeField(f func(*session.TokenLifetime)) { + t.setBodyField(func(body *session.SessionTokenBody) { + lt := body.GetLifetime() + if lt == nil { + lt = new(session.TokenLifetime) + body.SetLifetime(lt) + } + + f(lt) + }) +} + +// Exp returns epoch number of the token expiration. +func (t *Token) Exp() uint64 { + return (*session.SessionToken)(t). + GetBody(). + GetLifetime(). + GetExp() +} + +// SetExp sets epoch number of the token expiration. +func (t *Token) SetExp(exp uint64) { + t.setLifetimeField(func(lt *session.TokenLifetime) { + lt.SetExp(exp) + }) +} + +// Nbf returns starting epoch number of the token. +func (t *Token) Nbf() uint64 { + return (*session.SessionToken)(t). + GetBody(). + GetLifetime(). + GetNbf() +} + +// SetNbf sets starting epoch number of the token. +func (t *Token) SetNbf(nbf uint64) { + t.setLifetimeField(func(lt *session.TokenLifetime) { + lt.SetNbf(nbf) + }) +} + +// Iat returns starting epoch number of the token. +func (t *Token) Iat() uint64 { + return (*session.SessionToken)(t). + GetBody(). + GetLifetime(). + GetIat() +} + +// SetIat sets the number of the epoch in which the token was issued. +func (t *Token) SetIat(iat uint64) { + t.setLifetimeField(func(lt *session.TokenLifetime) { + lt.SetIat(iat) + }) +} + // Sign calculates and writes signature of the Token data. // // Returns signature calculation errors. diff --git a/pkg/session/session_test.go b/pkg/session/session_test.go index 6358cea2..88ec8093 100644 --- a/pkg/session/session_test.go +++ b/pkg/session/session_test.go @@ -132,3 +132,33 @@ func TestGetContainerContext(t *testing.T) { require.Nil(t, session.GetContainerContext(tok)) } } + +func TestToken_Exp(t *testing.T) { + tok := session.NewToken() + + const exp = 11 + + tok.SetExp(exp) + + require.EqualValues(t, exp, tok.Exp()) +} + +func TestToken_Nbf(t *testing.T) { + tok := session.NewToken() + + const nbf = 22 + + tok.SetNbf(nbf) + + require.EqualValues(t, nbf, tok.Nbf()) +} + +func TestToken_Iat(t *testing.T) { + tok := session.NewToken() + + const iat = 33 + + tok.SetIat(iat) + + require.EqualValues(t, iat, tok.Iat()) +}