Add login function

TODO ws request auth

Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
This commit is contained in:
2025-09-26 11:35:10 +09:00
parent 6606be456b
commit 6be0512146
11 changed files with 604 additions and 55 deletions

222
main/service/auth.c Normal file
View File

@@ -0,0 +1,222 @@
#include "auth.h"
#include <esp_http_server.h>
#include <esp_random.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
static const char* TAG = "AUTH";
typedef struct
{
char token[TOKEN_LENGTH];
bool active;
time_t creation_time;
} auth_token_t;
static auth_token_t s_tokens[MAX_TOKENS];
static SemaphoreHandle_t s_token_mutex;
void auth_init(void)
{
s_token_mutex = xSemaphoreCreateMutex();
if (s_token_mutex == NULL)
{
ESP_LOGE(TAG, "Failed to create token mutex");
return;
}
for (int i = 0; i < MAX_TOKENS; i++)
{
s_tokens[i].active = false;
s_tokens[i].token[0] = '\0';
}
ESP_LOGI(TAG, "Auth module initialized.");
}
char* auth_generate_token(void)
{
if (xSemaphoreTake(s_token_mutex, portMAX_DELAY) != pdTRUE)
{
ESP_LOGE(TAG, "Failed to take token mutex");
return NULL;
}
int free_slot = -1;
for (int i = 0; i < MAX_TOKENS; i++)
{
if (!s_tokens[i].active)
{
free_slot = i;
break;
}
}
if (free_slot == -1)
{
ESP_LOGW(TAG, "No free token slots available. Invalidating oldest token.");
time_t oldest_time = time(NULL);
int oldest_idx = -1;
for (int i = 0; i < MAX_TOKENS; i++)
{
if (s_tokens[i].active && s_tokens[i].creation_time < oldest_time)
{
oldest_time = s_tokens[i].creation_time;
oldest_idx = i;
}
}
if (oldest_idx != -1)
{
s_tokens[oldest_idx].active = false;
free_slot = oldest_idx;
ESP_LOGI(TAG, "Oldest token at index %d invalidated.", oldest_idx);
}
else
{
ESP_LOGE(TAG, "Could not find an oldest token to invalidate. This should not happen if all are active.");
xSemaphoreGive(s_token_mutex);
return NULL;
}
}
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char* new_token = (char*)malloc(TOKEN_LENGTH);
if (new_token == NULL)
{
ESP_LOGE(TAG, "Failed to allocate memory for new token");
xSemaphoreGive(s_token_mutex);
return NULL;
}
for (int i = 0; i < TOKEN_LENGTH - 1; i++)
{
new_token[i] = charset[esp_random() % (sizeof(charset) - 1)];
}
new_token[TOKEN_LENGTH - 1] = '\0';
strncpy(s_tokens[free_slot].token, new_token, TOKEN_LENGTH);
s_tokens[free_slot].active = true;
s_tokens[free_slot].creation_time = time(NULL);
ESP_LOGI(TAG, "Generated new token at slot %d: %s", free_slot, new_token);
xSemaphoreGive(s_token_mutex);
return new_token;
}
bool auth_validate_token(const char* token)
{
if (token == NULL)
{
return false;
}
if (xSemaphoreTake(s_token_mutex, portMAX_DELAY) != pdTRUE)
{
ESP_LOGE(TAG, "Failed to take token mutex");
return false;
}
bool valid = false;
for (int i = 0; i < MAX_TOKENS; i++)
{
if (s_tokens[i].active && strcmp(s_tokens[i].token, token) == 0)
{
valid = true;
break;
}
}
xSemaphoreGive(s_token_mutex);
return valid;
}
void auth_invalidate_token(const char* token)
{
if (token == NULL)
{
return;
}
if (xSemaphoreTake(s_token_mutex, portMAX_DELAY) != pdTRUE)
{
ESP_LOGE(TAG, "Failed to take token mutex");
return;
}
for (int i = 0; i < MAX_TOKENS; i++)
{
if (s_tokens[i].active && strcmp(s_tokens[i].token, token) == 0)
{
s_tokens[i].active = false;
s_tokens[i].token[0] = '\0'; // Clear token string
ESP_LOGI(TAG, "Token at slot %d invalidated.", i);
break;
}
}
xSemaphoreGive(s_token_mutex);
}
void auth_cleanup_expired_tokens(void) { ESP_LOGD(TAG, "auth_cleanup_expired_tokens called (no-op for now)."); }
static const char* get_token_from_header(httpd_req_t* req)
{
char* auth_header = NULL;
size_t buf_len;
if (httpd_req_get_hdr_value_len(req, "Authorization") == 0)
{
return NULL;
}
buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
auth_header = (char*)malloc(buf_len);
if (auth_header == NULL)
{
ESP_LOGE(TAG, "Failed to allocate memory for auth header");
return NULL;
}
if (httpd_req_get_hdr_value_str(req, "Authorization", auth_header, buf_len) != ESP_OK)
{
free(auth_header);
return NULL;
}
if (strncmp(auth_header, "Bearer ", 7) == 0)
{
const char* token = auth_header + 7;
return token;
}
free(auth_header);
return NULL;
}
esp_err_t api_auth_check(httpd_req_t* req)
{
const char* token = get_token_from_header(req);
if (token == NULL)
{
ESP_LOGW(TAG, "API access attempt without token for URI: %s", req->uri);
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Authorization token required");
return ESP_FAIL;
}
if (!auth_validate_token(token))
{
ESP_LOGW(TAG, "API access attempt with invalid token for URI: %s", req->uri);
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid or expired token");
free((void*)token - 7);
return ESP_FAIL;
}
ESP_LOGD(TAG, "Token validated for URI: %s", req->uri);
free((void*)token - 7);
return ESP_OK;
}

28
main/service/auth.h Normal file
View File

@@ -0,0 +1,28 @@
#ifndef AUTH_H
#define AUTH_H
#include <stdbool.h>
#include "esp_err.h"
#include "esp_http_server.h"
#define MAX_TOKENS 4
#define TOKEN_LENGTH 33 // 32 characters + null terminator
// Function to initialize the authentication module
void auth_init(void);
// Function to generate a new token
char* auth_generate_token(void);
// Function to validate a token
bool auth_validate_token(const char* token);
// Function to invalidate a token (e.g., on logout)
void auth_invalidate_token(const char* token);
// Function to clean up expired tokens (if any)
void auth_cleanup_expired_tokens(void);
esp_err_t api_auth_check(httpd_req_t* req);
#endif // AUTH_H

View File

@@ -5,9 +5,15 @@
#include "freertos/FreeRTOS.h"
#include "sw.h"
#include "webserver.h"
#include "auth.h"
static esp_err_t control_get_handler(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
cJSON* root = cJSON_CreateObject();
cJSON_AddBoolToObject(root, "load_12v_on", get_main_load_switch());
@@ -25,6 +31,11 @@ static esp_err_t control_get_handler(httpd_req_t* req)
static esp_err_t control_post_handler(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
char buf[128];
int ret, remaining = req->content_len;

View File

@@ -8,11 +8,17 @@
#include "nconfig.h"
#include "webserver.h"
#include "wifi.h"
#include "auth.h"
static const char* TAG = "webserver";
static esp_err_t setting_get_handler(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
wifi_ap_record_t ap_info;
cJSON* root = cJSON_CreateObject();
@@ -103,6 +109,11 @@ static esp_err_t setting_get_handler(httpd_req_t* req)
static esp_err_t wifi_scan(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
wifi_ap_record_t* ap_records;
uint16_t count;
@@ -133,6 +144,11 @@ static esp_err_t wifi_scan(httpd_req_t* req)
static esp_err_t setting_post_handler(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
char buf[512];
int received = httpd_req_recv(req, buf, sizeof(buf) - 1);

View File

@@ -9,6 +9,7 @@
#include <string.h>
#include "esp_http_server.h"
#include "esp_system.h"
#include "auth.h"
static const char* TAG = "odroid";
@@ -50,6 +51,11 @@ void start_reboot_timer(int sec)
static esp_err_t reboot_post_handler(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
httpd_resp_set_type(req, "application/json");
const char* resp_str = "{\"status\": \"reboot timer started\"}";
httpd_resp_send(req, resp_str, strlen(resp_str));
@@ -80,6 +86,11 @@ void register_reboot_endpoint(httpd_handle_t server)
static esp_err_t version_get_handler(httpd_req_t* req)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK) {
return err;
}
httpd_resp_set_type(req, "application/json");
char buf[100];
sprintf(buf, "{\"version\": \"%s-%s\"}", VERSION_TAG, VERSION_HASH);

View File

@@ -11,6 +11,8 @@
#include "monitor.h"
#include "nconfig.h"
#include "system.h"
#include "cJSON.h"
#include "auth.h"
static const char* TAG = "WEBSERVER";
@@ -42,9 +44,70 @@ static esp_err_t index_handler(httpd_req_t* req)
return ESP_OK;
}
static esp_err_t login_handler(httpd_req_t* req)
{
char content[100]; // Adjust size as needed for username/password
int ret = httpd_req_recv(req, content, sizeof(content) - 1); // -1 for null terminator
if (ret <= 0) { // 0 means connection closed, < 0 means error
if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
httpd_resp_send_408(req);
}
return ESP_FAIL;
}
content[ret] = '\0'; // Null-terminate the received data
ESP_LOGI(TAG, "Received login request: %s", content);
cJSON *root = cJSON_Parse(content);
if (root == NULL) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
return ESP_FAIL;
}
cJSON *username_json = cJSON_GetObjectItemCaseSensitive(root, "username");
cJSON *password_json = cJSON_GetObjectItemCaseSensitive(root, "password");
if (!cJSON_IsString(username_json) || (username_json->valuestring == NULL) ||
!cJSON_IsString(password_json) || (password_json->valuestring == NULL)) {
cJSON_Delete(root);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing username or password");
return ESP_FAIL;
}
const char *username = username_json->valuestring;
const char *password = password_json->valuestring;
// TODO: Implement actual credential validation
// For now, a simple hardcoded check
if (strcmp(username, "admin") == 0 && strcmp(password, "password") == 0) {
char *token = auth_generate_token();
if (token) {
cJSON *response_root = cJSON_CreateObject();
cJSON_AddStringToObject(response_root, "token", token);
char *json_response = cJSON_Print(response_root);
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, json_response);
free(token); // Free the token generated by auth_generate_token
free(json_response);
cJSON_Delete(response_root);
} else {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to generate token");
}
} else {
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid credentials");
}
cJSON_Delete(root);
return ESP_OK;
}
void start_webserver(void)
{
auth_init();
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.stack_size = 1024 * 8;
@@ -61,6 +124,10 @@ void start_webserver(void)
httpd_uri_t index = {.uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL};
httpd_register_uri_handler(server, &index);
// Login endpoint
httpd_uri_t login = {.uri = "/login", .method = HTTP_POST, .handler = login_handler, .user_ctx = NULL};
httpd_register_uri_handler(server, &login);
register_wifi_endpoint(server);
register_ws_endpoint(server);
register_control_endpoint(server);

View File

@@ -12,6 +12,7 @@
#include "pb_encode.h"
#include "status.pb.h"
#include "webserver.h"
#include "auth.h"
#define UART_NUM UART_NUM_1
#define BUF_SIZE (2048)
@@ -202,6 +203,11 @@ static void uart_event_task(void* arg)
static esp_err_t ws_handler(httpd_req_t* req)
{
// esp_err_t err = api_auth_check(req);
// if (err != ESP_OK) {
// return err;
// }
if (req->method == HTTP_GET)
{
ESP_LOGI(TAG, "Handshake done, the new connection was opened");