1/*
2 * Copyright 2023, Andrew Lindesay <apl@lindesay.co.nz>.
3 * All rights reserved. Distributed under the terms of the MIT License.
4 */
5#include "AccessToken.h"
6
7#include "JwtTokenHelper.h"
8#include "Logger.h"
9
10// These are keys that are used to store this object's data into a BMessage instance.
11
12#define KEY_TOKEN				"token"
13#define KEY_EXPIRY_TIMESTAMP	"expiryTimestamp"
14
15
16AccessToken::AccessToken(BMessage* from)
17	:
18	fToken(""),
19	fExpiryTimestamp(0)
20{
21	if (from->FindString(KEY_TOKEN, &fToken) != B_OK) {
22		HDERROR("expected key [%s] in the message data when creating an access"
23			" token", KEY_TOKEN);
24	}
25
26	if (from->FindUInt64(KEY_EXPIRY_TIMESTAMP, &fExpiryTimestamp) != B_OK) {
27		HDERROR("expected key [%s] in the message data when creating an access"
28			" token", KEY_EXPIRY_TIMESTAMP);
29	}
30}
31
32
33AccessToken::AccessToken()
34	:
35	fToken(""),
36	fExpiryTimestamp(0)
37{
38}
39
40
41AccessToken::~AccessToken()
42{
43}
44
45
46AccessToken&
47AccessToken::operator=(const AccessToken& other)
48{
49	fToken = other.fToken;
50	fExpiryTimestamp = other.fExpiryTimestamp;
51	return *this;
52}
53
54
55bool
56AccessToken::operator==(const AccessToken& other) const
57{
58	return fToken == other.fToken;
59}
60
61
62bool
63AccessToken::operator!=(const AccessToken& other) const
64{
65	return !(*this == other);
66}
67
68
69const BString&
70AccessToken::Token() const
71{
72	return fToken;
73}
74
75
76uint64
77AccessToken::ExpiryTimestamp() const
78{
79	return fExpiryTimestamp;
80}
81
82
83void
84AccessToken::SetToken(const BString& value)
85{
86	fToken = value;
87}
88
89
90void
91AccessToken::SetExpiryTimestamp(uint64 value)
92{
93	fExpiryTimestamp = value;
94}
95
96
97/*! The access token may have a value or may be the empty string. This method
98    will check that the token appears to be an access token.
99*/
100
101bool
102AccessToken::IsValid() const
103{
104	return JwtTokenHelper::IsValid(fToken);
105}
106
107
108bool
109AccessToken::IsValid(uint64 currentTimestamp) const
110{
111	return IsValid() && (fExpiryTimestamp == 0 || fExpiryTimestamp > currentTimestamp);
112}
113
114
115void
116AccessToken::Clear()
117{
118	fToken = "";
119    fExpiryTimestamp = 0;
120}
121
122
123status_t
124AccessToken::Archive(BMessage* into, bool deep) const
125{
126	status_t result = B_OK;
127	if (result == B_OK && into == NULL)
128		result = B_ERROR;
129	if (result == B_OK)
130		result = into->AddString(KEY_TOKEN, fToken);
131	if (result == B_OK)
132		result = into->AddUInt64(KEY_EXPIRY_TIMESTAMP, fExpiryTimestamp);
133	return result;
134}