database: Add fetch() for SessionDao

This commit is contained in:
Albert S. 2023-02-01 18:54:11 +01:00
джерело aaa0f2f76a
коміт f160ac8102
4 змінених файлів з 49 додано та 19 видалено

Бінарний файл не відображається.

@ -10,6 +10,7 @@ class SessionDao
virtual void save(const Session &session) = 0;
virtual std::optional<Session> find(std::string token) = 0;
virtual void deleteSession(std::string token) = 0;
virtual std::vector<Session> fetch() = 0;
virtual ~SessionDao()
{
}

63
database/sessiondaosqlite.cpp Normal file → Executable file

@ -50,6 +50,29 @@ void SessionDaoSqlite::deleteSession(std::string token)
}
}
void SessionDaoSqlite::fillSession(int userid, Session &sess)
{
if(userid > -1)
{
UserDaoSqlite userDao{this->db};
auto u = userDao.find(userid);
if(u)
{
sess.user = *u;
}
else
{
Logger::error() << "Session for non existent user";
throw DatabaseQueryException("Session for non existent user");
}
}
else
{
sess.user = User::Anonymous();
}
sess.loggedIn = userid != -1;
}
std::optional<Session> SessionDaoSqlite::find(std::string token)
{
Session result;
@ -62,25 +85,7 @@ std::optional<Session> SessionDaoSqlite::find(std::string token)
int userid;
q >> std::tie(userid, result.token, result.csrf_token, result.creation_time);
if(userid > -1)
{
UserDaoSqlite userDao{this->db};
auto u = userDao.find(userid);
if(u)
{
result.user = *u;
}
else
{
Logger::error() << "Session for non existent user";
throw DatabaseQueryException("Session for non existent user");
}
}
else
{
result.user = User::Anonymous();
}
result.loggedIn = userid != -1;
fillSession(userid, result);
}
catch(const sqlite::exceptions::no_rows &e)
{
@ -92,3 +97,23 @@ std::optional<Session> SessionDaoSqlite::find(std::string token)
}
return result;
}
std::vector<Session> SessionDaoSqlite::fetch()
{
std::vector<Session> result;
*db << "SELECT userid, token, csrf_token, strftime('%s', creationtime) FROM session" >>
[this, &result](int userid, std::string token, std::string csrf_token, time_t creationtime)
{
Session tmp;
tmp.csrf_token = csrf_token;
tmp.token = token;
tmp.creation_time = creationtime;
fillSession(userid, tmp);
result.push_back(tmp);
};
return result;
}

@ -6,11 +6,15 @@
class SessionDaoSqlite : public SessionDao, protected SqliteDao
{
private:
void fillSession(int userid, Session &sess);
public:
SessionDaoSqlite();
void save(const Session &session) override;
std::optional<Session> find(std::string token) override;
void deleteSession(std::string token) override;
std::vector<Session> fetch() override;
using SqliteDao::SqliteDao;
};