added definitions for sending and receiving messages
This commit is contained in:
84
src/server/responses/Login.c
Normal file
84
src/server/responses/Login.c
Normal file
@@ -0,0 +1,84 @@
|
||||
#include "responses.h"
|
||||
|
||||
#define LOGGER conn->server->logger
|
||||
#define LOG_FUNC conn->server->log_func
|
||||
|
||||
declare_RequestHandler(Login)
|
||||
{
|
||||
Deferral(4);
|
||||
logInfo(log_ctx, "requested %s", req_type_name);
|
||||
|
||||
// receive request
|
||||
LoginRequest req;
|
||||
try_void(PacketHeader_validateContentSize(req_head, sizeof(req)));
|
||||
try_void(EncryptedSocketTCP_recvStruct(&conn->sock, &req));
|
||||
|
||||
if(conn->authorized){
|
||||
try_void(sendErrorMessage(log_ctx, conn, res_head,
|
||||
LogSeverity_Warn,
|
||||
STR("is authorized in already")
|
||||
));
|
||||
Return RESULT_VOID;
|
||||
}
|
||||
|
||||
// validate username
|
||||
str username_str = str_null;
|
||||
str name_error_str = validateUsername_cstr(req.username, &username_str);
|
||||
if(name_error_str.data){
|
||||
Defer(str_free(name_error_str));
|
||||
try_void(sendErrorMessage(log_ctx, conn, res_head,
|
||||
LogSeverity_Warn,
|
||||
name_error_str
|
||||
));
|
||||
Return RESULT_VOID;
|
||||
}
|
||||
|
||||
// lock users cache
|
||||
try_stderrcode(pthread_mutex_lock(&conn->server->users_cache_mutex));
|
||||
bool unlocked_users_cache_mutex = false;
|
||||
Defer(
|
||||
if(!unlocked_users_cache_mutex)
|
||||
pthread_mutex_unlock(&conn->server->users_cache_mutex)
|
||||
);
|
||||
|
||||
// try get id from name cache
|
||||
u64* id_ptr = HashMap_tryGetPtr(&conn->server->users_name_id_map, username_str);
|
||||
if(id_ptr == NULL){
|
||||
try_void(sendErrorMessage_f(log_ctx, conn, res_head,
|
||||
LogSeverity_Warn,
|
||||
"Username '%s' is not registered",
|
||||
username_str.data
|
||||
));
|
||||
Return RESULT_VOID;
|
||||
}
|
||||
u64 user_id = *id_ptr;
|
||||
|
||||
// get user by id
|
||||
try_assert(user_id < List_len(conn->server->users_cache_list, UserInfo));
|
||||
UserInfo* u = &List_index(conn->server->users_cache_list, UserInfo, user_id);
|
||||
|
||||
// validate token hash
|
||||
if(memcmp(req.token, u->token, sizeof(req.token)) != 0){
|
||||
try_void(sendErrorMessage(log_ctx, conn, res_head,
|
||||
LogSeverity_Warn,
|
||||
STR("wrong password")
|
||||
));
|
||||
Return RESULT_VOID;
|
||||
}
|
||||
|
||||
// manually unlock mutex
|
||||
pthread_mutex_unlock(&conn->server->users_cache_mutex);
|
||||
unlocked_users_cache_mutex = true;
|
||||
|
||||
// authorize
|
||||
conn->authorized = true;
|
||||
logInfo(log_ctx, "authorized user '%s'", username_str.data);
|
||||
|
||||
// send response
|
||||
LoginResponse res;
|
||||
LoginResponse_construct(&res, res_head, user_id, conn->server->landing_channel_id);
|
||||
try_void(EncryptedSocketTCP_sendStruct(&conn->sock, res_head));
|
||||
try_void(EncryptedSocketTCP_sendStruct(&conn->sock, &res));
|
||||
|
||||
Return RESULT_VOID;
|
||||
}
|
||||
Reference in New Issue
Block a user