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
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include "lua-bcrypt/compat/include/pwd.h"
#define USER_DATABASE "./user.db"
#define SECURITY_LEVEL 12
static bool
valid_char(int ch)
{
return isalnum(ch) || ch == '_' || ch == '-' || ch == '.';
}
/**
* Create a new user/password
*
* \param[in] username
* \param[in] password
*
* \return true on success (user was created) or false on error
*/
bool
create_user(const char *username, const char *password)
{
// check for invalid characters in username
for ( const char *ptr = username; *ptr; ++ptr ) {
if ( !valid_char(*ptr) ) {
return false;
}
}
FILE *db = fopen(USER_DATABASE, "a");
if ( db == NULL ) {
return false;
}
char hash[_PASSWORD_LEN + 1] = { 0 };
if ( bcrypt_newhash(password, SECURITY_LEVEL, hash, _PASSWORD_LEN) != 0 ) {
return false;
}
fprintf(db, "%s|%s\n", username, hash);
fclose(db);
return true;
}
/**
* Check is a valid username/password exists in the user-database
*
* \param[in] username
* \param[in] password
*
* \return true, if the user was successfully authenticated, otherwise false
*/
bool
check_user(const char *username, const char *password)
{
FILE *db = fopen(USER_DATABASE, "r");
if ( db == NULL ) {
return false;
}
const size_t username_length = strlen(username);
char line[256];
bool found = false;
while ( !found && fgets(line, sizeof line, db) ) {
line[strcspn(line, "\r\n")] = '\0'; // remove newline (if exists)
if ( strncmp(line, username, username_length) != 0 ) {
continue;
}
if ( line[username_length] != '|' ) {
continue;
}
if ( bcrypt_checkpass(password, &line[username_length+1]) != 0 ) {
continue;
}
// User successfully authenticated!
found = true;
}
fclose(db);
return found;
}
int
main(void)
{
if ( check_user("Thomas", "Passwort") ) {
puts("Benutzer erfolgreich überprüft!");
}
return EXIT_SUCCESS;
}
|