-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserDatabase.cpp
70 lines (53 loc) · 2.02 KB
/
UserDatabase.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
#include "UserDatabase.h"
struct UserDatabase::Impl {
QString path;
auto Write(const QList<User::Pointer>& users)->void;
};
namespace Field {
constexpr char size[] = "SIZE";
constexpr char id[] = "ID";
constexpr char password[] = "PW";
constexpr char privilege[] = "PV";
}
auto ReadField(QSettings& qs, const char key[]) -> QVariant {
if (!qs.contains(key)) throw std::runtime_error(std::string("Missing key in user database: ") + key);
return qs.value(key);
}
UserDatabase::UserDatabase() : d{ std::make_unique<Impl>() } {}
UserDatabase::~UserDatabase() {};
auto UserDatabase::GetInstance() -> Pointer {
static Pointer theInstance{ new UserDatabase() };
return theInstance;
}
bool fileExists(const QString &filePath) {
return QFile::exists(filePath);
}
auto UserDatabase::Load(const QString& path) -> bool {
d->path = path;
auto qs = QSettings(path, QSettings::IniFormat);
fileExists(path) ? qDebug() << "File exists:" << path : qDebug() << "File does not exist:" << path;
auto manager = UserManager::GetInstance();
try {
qs.beginGroup("USER COUNT");
const int count = qs.value("COUNT").toInt();
qs.endGroup();
for(auto i = 0; i < count; ++i) {
auto user = std::make_shared<User>();
const QString userI = "User" + QString::number(i);
qDebug() << "UserI: " << userI;
qs.beginGroup(userI);
user->SetUserID(ReadField(qs, Field::id).toString());
user->SetPassword(ReadField(qs, Field::password).toString());
user->SetPrivilege(ReadField(qs, Field::privilege).toInt());
qs.endGroup();
manager->AddUser(user);
}
} catch(std::exception& ex) {
qDebug() << "It fails to read user database. Error = " << ex.what();
qs.endArray();
return false;
}
auto finfo = QFileInfo(d->path);
auto dirPath = finfo.absolutePath();
return true;
}