-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_manager.c
113 lines (98 loc) · 2.84 KB
/
user_manager.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "user_manager.h"
#include <logger.h>
#include <crc32.h>
#include <string.h>
#include <stdlib.h>
DECLARE_LOGGER(User)
variant_stack_t *user_list;
int hash_password(const char *password)
{
return crc32(0, password, strlen(password));
}
void delete_user_entry(void *arg)
{
user_entry_t *e = (user_entry_t *)arg;
free(e->username);
free(e);
}
void user_manager_init()
{
LOG_ADVANCED(User, "Initializing user manager");
user_list = stack_create();
LOG_INFO(User, "User manager initialized");
}
int user_manager_get_count()
{
return user_list->count;
}
bool user_manager_add_user(const char *username, const char *password)
{
stack_for_each(user_list, user_entry_variant)
{
user_entry_t *entry = VARIANT_GET_PTR(user_entry_t, user_entry_variant);
if (strcmp(entry->username, username) == 0)
{
return false;
}
}
user_entry_t *new_entry = malloc(sizeof(user_entry_t));
new_entry->username = strdup(username);
new_entry->password = hash_password(password);
stack_push_back(user_list, variant_create_ptr(DT_PTR, new_entry, delete_user_entry));
return true;
}
void user_manager_add_hashed_user(const char *username, const char *password)
{
stack_for_each(user_list, user_entry_variant)
{
user_entry_t *entry = VARIANT_GET_PTR(user_entry_t, user_entry_variant);
if (strcmp(entry->username, username) == 0)
{
return;
}
}
user_entry_t *new_entry = malloc(sizeof(user_entry_t));
new_entry->username = strdup(username);
sscanf(password, "%d", &new_entry->password);
stack_push_back(user_list, variant_create_ptr(DT_PTR, new_entry, delete_user_entry));
}
void user_manager_del_user(const char *username)
{
stack_for_each(user_list, user_entry_variant)
{
user_entry_t *entry = VARIANT_GET_PTR(user_entry_t, user_entry_variant);
if (strcmp(entry->username, username) == 0)
{
stack_remove(user_list, user_entry_variant);
variant_free(user_entry_variant);
break;
}
}
}
bool user_manager_authenticate(const char *username, const char *password)
{
stack_for_each(user_list, user_entry_variant)
{
user_entry_t *entry = VARIANT_GET_PTR(user_entry_t, user_entry_variant);
if (strcmp(entry->username, username) == 0)
{
if (hash_password(password) == entry->password)
{
return true;
}
else
{
return false;
}
}
}
return false;
}
void user_manager_for_each_user(void (*visitor)(user_entry_t *entry, void *arg), void *arg)
{
stack_for_each(user_list, user_entry_variant)
{
user_entry_t *entry = VARIANT_GET_PTR(user_entry_t, user_entry_variant);
visitor(entry, arg);
}
}