KissCount/model/Database.cpp
Grégory Soutadé ee8d4c0c8f Initial commit
A good base to start working
2010-05-14 15:04:01 +02:00

116 lines
2.2 KiB
C++

#include "Database.h"
Database::Database()
{
std::ifstream bdd_file;
bdd_file.open(BDD_FILE);
if (!bdd_file)
{
CreateDatabase();
}
else
_db.Open(_(BDD_FILE));
bdd_file.close();
}
void Database::CreateDatabase()
{
std::ifstream init_script;
std::string line;
wxMessageBox(_("No database found, creating a new one"), _("KissCount"), wxICON_EXCLAMATION | wxOK );
init_script.open(INIT_SCRIPT);
if (!init_script)
{
wxMessageBox(_(INIT_SCRIPT " not found, aborting"), _("Error"), wxICON_ERROR | wxOK );
throw "init.sql not found, aborting";
}
_db.Open(_(BDD_FILE));
do
{
getline(init_script, line);
if (!_db.CheckSyntax(line.data()))
{
std::cout << line << " is invalid !\n" ;
continue;
}
try
{
_db.ExecuteUpdate(line.data());
}
catch (...)
{
wxMessageBox(_("Error creating original database"), _("Error"), wxICON_ERROR | wxOK );
throw line;
}
} while (init_script);
init_script.close();
}
std::list<wxString> Database::GetUsers()
{
std::list<wxString> res;
// Check whether value exists in table
wxSQLite3ResultSet set ;
try
{
set = _db.ExecuteQuery(wxT("SELECT name FROM user"));
}
catch (wxSQLite3Exception e)
{
std::cerr << e.GetMessage().mb_str() << "\n" ;
return res;
}
while (set.NextRow())
{
res.push_front(set.GetAsString(0));
}
set.Finalize();
return res;
}
bool Database::IsValidUser(wxString user, wxString password)
{
bool res;
blk_SHA_CTX sha_ctx;
unsigned char sha[20];
wxString req, wxSHA;
wxSQLite3ResultSet set;
blk_SHA1_Init(&sha_ctx);
blk_SHA1_Update(&sha_ctx, password.c_str(), password.Length());
blk_SHA1_Final(sha, &sha_ctx);
for(int i=0; i<20; i++)
wxSHA += wxString::Format(wxT("%02F"), (int)sha[i]);
req = _("SELECT name FROM user WHERE name='") + user + _("' AND password='") + wxSHA + _("'");
// Check whether value exists in table
try
{
set = _db.ExecuteQuery(req);
}
catch (wxSQLite3Exception e)
{
std::cerr << e.GetMessage().mb_str() << "\n" ;
return false;
}
res = set.NextRow() ;
set.Finalize();
return res;
}