xref: /haiku/src/apps/haikudepot/model/AccessToken.cpp (revision e1c4049fed1047bdb957b0529e1921e97ef94770)
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 
16 AccessToken::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 
33 AccessToken::AccessToken()
34 	:
35 	fToken(""),
36 	fExpiryTimestamp(0)
37 {
38 }
39 
40 
41 AccessToken::~AccessToken()
42 {
43 }
44 
45 
46 AccessToken&
47 AccessToken::operator=(const AccessToken& other)
48 {
49 	fToken = other.fToken;
50 	fExpiryTimestamp = other.fExpiryTimestamp;
51 	return *this;
52 }
53 
54 
55 bool
56 AccessToken::operator==(const AccessToken& other) const
57 {
58 	return fToken == other.fToken;
59 }
60 
61 
62 bool
63 AccessToken::operator!=(const AccessToken& other) const
64 {
65 	return !(*this == other);
66 }
67 
68 
69 const BString&
70 AccessToken::Token() const
71 {
72 	return fToken;
73 }
74 
75 
76 uint64
77 AccessToken::ExpiryTimestamp() const
78 {
79 	return fExpiryTimestamp;
80 }
81 
82 
83 void
84 AccessToken::SetToken(const BString& value)
85 {
86 	fToken = value;
87 }
88 
89 
90 void
91 AccessToken::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 
101 bool
102 AccessToken::IsValid() const
103 {
104 	return JwtTokenHelper::IsValid(fToken);
105 }
106 
107 
108 bool
109 AccessToken::IsValid(uint64 currentTimestamp) const
110 {
111 	return IsValid() && (fExpiryTimestamp == 0 || fExpiryTimestamp > currentTimestamp);
112 }
113 
114 
115 void
116 AccessToken::Clear()
117 {
118 	fToken = "";
119     fExpiryTimestamp = 0;
120 }
121 
122 
123 status_t
124 AccessToken::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 }