-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserStore.cpp
129 lines (117 loc) · 2.17 KB
/
UserStore.cpp
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "UserStore.h"
UserStore::UserStore()
{
this->total = 0;
}
void UserStore::addUser(const String& username,const String& password)
{
size_t size = users.getSize();
for (size_t i = 0; i < size; ++i)
{
if (users[i].getName() == username)
{
std::cout << "This user already exists!\n";
return;
}
}
User newUser;
newUser.setName(username);
newUser.setPassword(password);
if (username == "admin")
{
newUser.setAdmin(true);
newUser.setLoggedIn(true);
}
else
{
newUser.setLoggedIn(false);
newUser.setAdmin(false);
}
this->total++;
users.pushBack(newUser);
}
void UserStore::removeUser(const String& username)
{
size_t size = users.getSize();
int indexOfUser = -1;
for (size_t i = 0; i < size; ++i)
{
if (users[i].getName() == username)
{
indexOfUser = i;
break;
}
}
if (indexOfUser == -1)
{
std::cout << "User not found!\n";
return;
}
users.removeAt(indexOfUser);
this->total--;
std::cout << "User successfully removed!\n";
}
size_t UserStore::getSize() const
{
return this->users.getSize();
}
User& UserStore::operator[](const size_t index) const
{
return this->users[index];
}
const int UserStore::activeUserIndex() const
{
size_t size = users.getSize();
int index = -1;
for (size_t i = 0; i < size; ++i)
{
if (users[i].getLoggedIn() == true)
{
index = i;
break;
}
}
return index;
}
const size_t UserStore::getLinesOfFile(std::ifstream& in) const
{
in.unsetf(std::ios_base::skipws);
size_t line_count = std::count(
std::istream_iterator<char>(in),
std::istream_iterator<char>(),
'\n');
return line_count;
}
void UserStore::loadUsers(std::ifstream& in)
{
in.seekg(0, std::ios::end);
int size = in.tellg();
if (size == -1)
{
std::cout << "Database can't be empty!\n";
return;
}
in.seekg(0, std::ios::beg);
size_t total;
in >> total;
for (size_t i = 0; i < total; ++i)
{
User user;
user.loadUser(in);
this->addUser(user.getName(), user.getPassword());
}
}
void UserStore::saveUsers(std::ofstream& out)
{
out << this->total << "\n";
size_t size = users.getSize();
for (size_t i = 0;i < size; ++i)
{
users[i].saveUser(out);
}
}
void UserStore::clear()
{
UserStore clean;
*this = clean;
}