Magic Poi Lite 0.1
IOT LED Poi
Loading...
Searching...
No Matches
Public Member Functions | Private Attributes | List of all members
Authentication Class Reference
Collaboration diagram for Authentication:
Collaboration graph

Public Member Functions

 Authentication ()
 Default constructor for Authentication class.
 
String readJWTTokenFromFile ()
 Reads JWT token from a file stored on LittleFS.
 
void saveJWTTokenToFile (const char *token)
 Saves a JWT token to a file on LittleFS.
 
bool authenticate ()
 Authenticates the client with the server.
 
bool checkSavedToken ()
 Checks for a saved JWT token and loads it if available.
 

Private Attributes

char token [500]
 Buffer for JWT token.
 
char jwtToken [500]
 Buffer for JWT token.
 
boolean gotToken = false
 Flag indicating whether a token has been retrieved.
 
const char * jwtFilePath = "/jwt.txt"
 Path to the file storing JWT token.
 
WiFiClient client
 WiFi client object.
 

Constructor & Destructor Documentation

◆ Authentication()

Authentication::Authentication ( )

Default constructor for Authentication class.

This constructor initializes the Authentication object by clearing the jwtToken buffer.

24{
25 // Initialize variables
26 memset(jwtToken, 0, sizeof(jwtToken)); // Clear jwtToken buffer
27}
char jwtToken[500]
Buffer for JWT token.
Definition Authentication.h:33

References jwtToken.

Member Function Documentation

◆ authenticate()

bool Authentication::authenticate ( )

Authenticates the client with the server.

This method attempts to authenticate the client with the server by sending a POST request to the login endpoint with the provided email and password. If the authentication is successful, the JWT token received from the server is parsed and saved, and the method returns true. If any error occurs during the HTTP request or JSON parsing, or if the server returns an error response code, the method returns false.

Returns
true if the authentication is successful, false otherwise.
118{
119 Serial.println("Authenticating...");
120
121 HTTPClient http;
122 http.begin(client, "http://" + String(serverIP) + ":" + String(serverPort) + "/api/login");
123 http.addHeader("Content-Type", "application/json");
124
125 Serial.println("[HTTP] POST...");
126 int httpCode = http.POST("{\"email\":\"" + String(email) + "\",\"password\":\"" + String(passwordJwt) + "\"}");
127
128 // httpCode will be negative on error
129 if (httpCode > 0)
130 {
131 if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_CREATED)
132 {
133 // Parse the response JSON to get the token
134 DynamicJsonDocument doc(1024);
135 DeserializationError error = deserializeJson(doc, http.getString());
136 if (error)
137 {
138 Serial.println("Failed to parse JSON.");
139 return false;
140 }
141
142 strcpy(token, doc["token"]);
143 Serial.println("Authentication successful.");
144 Serial.println(token);
145 gotToken = true;
146 saveJWTTokenToFile(token); //save for next time, so we won't need to do this again.
147 return true;
148 }
149 else
150 {
151 Serial.print("[HTTP] Error code: ");
152 Serial.println(httpCode);
153 }
154 }
155 else
156 {
157 Serial.println("Connection failed.");
158 }
159
160 http.end();
161 return false;
162
163 // bool isAuthenticated = true; // Simulated result
164 // return isAuthenticated;
165}
WiFiClient client
WiFi client object.
Definition Authentication.h:52
void saveJWTTokenToFile(const char *token)
Saves a JWT token to a file on LittleFS.
Definition Authentication.cpp:83
boolean gotToken
Flag indicating whether a token has been retrieved.
Definition Authentication.h:38
char token[500]
Buffer for JWT token.
Definition Authentication.h:26

References client, gotToken, saveJWTTokenToFile(), and token.

Referenced by handleAuthenticationAndLoading().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ checkSavedToken()

bool Authentication::checkSavedToken ( )

Checks for a saved JWT token and loads it if available.

This method checks if a JWT token is saved in a file. If a token is found, it loads the token into the internal token buffer. If no token is found, the method returns false.

Returns
true if a saved token is successfully loaded, false otherwise.
178{
179 // check for saved token, load
180 String savedToken = readJWTTokenFromFile();
181 if (!savedToken.isEmpty())
182 {
183 strncpy(token, savedToken.c_str(), sizeof(token) - 1);
184 token[sizeof(token) - 1] = '\0'; // Null-terminate the token string
185 // strncpy(jwtToken, savedToken.c_str(), sizeof(jwtToken) - 1);
186 // jwtToken[sizeof(jwtToken) - 1] = '\0'; // Null-terminate the token string
187 gotToken = true;
188 Serial.println("Using saved JWT token:");
189 Serial.println(token);
190 return true;
191 }
192 else
193 {
194 return false;
195 }
196}
String readJWTTokenFromFile()
Reads JWT token from a file stored on LittleFS.
Definition Authentication.cpp:39

References gotToken, readJWTTokenFromFile(), and token.

Referenced by handleAuthenticationAndLoading().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ readJWTTokenFromFile()

String Authentication::readJWTTokenFromFile ( )

Reads JWT token from a file stored on LittleFS.

This method attempts to read a JWT token from a file stored on LittleFS (Little File System). If the file exists, it reads the token from the file and returns it. If the file does not exist or if there's any failure during the file system operation, an empty string is returned.

Returns
A string containing the JWT token read from the file, or an empty string if the token couldn't be read.
40{
41 String jwtToken = "";
42
43 if (LittleFS.begin())
44 {
45 if (LittleFS.exists(jwtFilePath))
46 {
47 File file = LittleFS.open(jwtFilePath, "r");
48 if (file)
49 {
50 jwtToken = file.readString();
51 file.close();
52 }
53 else
54 {
55 Serial.println("no file?");
56 }
57 }
58 else
59 {
60 Serial.println("file not found on LittleFS");
61 }
62 LittleFS.end();
63 }
64 else
65 {
66 Serial.println("LittlFS Failed to begin");
67 }
68
69 return jwtToken;
70}
const char * jwtFilePath
Path to the file storing JWT token.
Definition Authentication.h:45

References jwtFilePath, and jwtToken.

Referenced by checkSavedToken(), and Loading::Loading().

Here is the caller graph for this function:

◆ saveJWTTokenToFile()

void Authentication::saveJWTTokenToFile ( const char * token)

Saves a JWT token to a file on LittleFS.

This method attempts to save a JWT token to a file stored on LittleFS (Little File System). If LittleFS initialization succeeds and the file is successfully created and written, a success message is printed to the Serial monitor. If there's any failure during the file system operation, an error message is printed.

Parameters
tokenThe JWT token to be saved to the file.
84{
85 if (LittleFS.begin())
86 {
87 File file = LittleFS.open(jwtFilePath, "w");
88 if (file)
89 {
90 file.print(token);
91 file.close();
92 Serial.println("JWT token saved to file.");
93 }
94 else
95 {
96 Serial.println("couldn't create file?");
97 }
98 LittleFS.end();
99 }
100 else{
101 Serial.println("Couldn't open Littlefs to write jwt");
102 }
103}

References jwtFilePath, and token.

Referenced by authenticate().

Here is the caller graph for this function:

Member Data Documentation

◆ client

WiFiClient Authentication::client
private

WiFi client object.

This object is used for network communication with the server.

Referenced by authenticate().

◆ jwtFilePath

const char* Authentication::jwtFilePath = "/jwt.txt"
private

Path to the file storing JWT token.

This string represents the file path of the file storing the JWT token in LittleFS.

Referenced by readJWTTokenFromFile(), and saveJWTTokenToFile().

◆ jwtToken

char Authentication::jwtToken[500]
private

Buffer for JWT token.

This buffer stores the JWT token retrieved from LittleFS.

Referenced by Authentication(), and readJWTTokenFromFile().

◆ token

char Authentication::token[500]
private

Buffer for JWT token.

This buffer stores the JWT token retrieved from authentication.

Referenced by authenticate(), checkSavedToken(), and saveJWTTokenToFile().


The documentation for this class was generated from the following files: