150 lines
3.7 KiB
C++
150 lines
3.7 KiB
C++
#include "Session.h"
|
|
#include "Util.h"
|
|
#include "json.hpp"
|
|
#include "jsonfail.h"
|
|
using namespace std;
|
|
using json=nlohmann::json;
|
|
|
|
#define postval(NAME) string NAME=req.post[#NAME]
|
|
|
|
int main()
|
|
{
|
|
Request req;
|
|
Session se(req);
|
|
Response res;
|
|
json j;
|
|
|
|
auto jsonfail=[&](int errcode,const string& detail="")
|
|
{
|
|
j["success"]=0;
|
|
j["errcode"]=errcode;
|
|
j["errmsg"]=string(GetErrMsg(errcode))+" : "+detail;
|
|
};
|
|
|
|
do
|
|
{
|
|
if(!se.isReady())
|
|
{
|
|
jsonfail(err_session);
|
|
break;
|
|
}
|
|
|
|
if(!se.isNew()||!se.getUser().empty())
|
|
{
|
|
/// Logged in...
|
|
j["success"]=2;
|
|
j["next_url"]="/booksys/dashboard.html";
|
|
break;
|
|
}
|
|
|
|
if(req.requestMethod!="POST")
|
|
{
|
|
jsonfail(err_method_not_supported);
|
|
break;
|
|
}
|
|
if(req.post["username"].empty() ||
|
|
req.post["password"].empty() )
|
|
{
|
|
jsonfail(err_missing_parameter);
|
|
break;
|
|
}
|
|
|
|
postval(username);
|
|
postval(password);
|
|
|
|
DBInfo db;
|
|
MySQLConn conn;
|
|
if(db.readConfig()<0)
|
|
{
|
|
jsonfail(err_config);
|
|
break;
|
|
}
|
|
|
|
if(db.connectProxy(conn)<0)
|
|
{
|
|
jsonfail(err_connect);
|
|
break;
|
|
}
|
|
|
|
/// Check if password is correct
|
|
bool authpass=false;
|
|
if(conn.exec(make_str("select count(username) from bs_user where username='",
|
|
username,
|
|
"' and password='",
|
|
password,
|
|
"'"),
|
|
[&](MySQLResult& res)
|
|
{
|
|
res.stepRow([&](char** val,unsigned long* len)
|
|
{
|
|
if(string(val[0])=="1")
|
|
{
|
|
authpass=true;
|
|
}
|
|
});
|
|
})<0)
|
|
{
|
|
jsonfail(err_sql,"Step 1");
|
|
break;
|
|
}
|
|
|
|
if(!authpass)
|
|
{
|
|
jsonfail(err_data,"Auth Failed");
|
|
break;
|
|
}
|
|
|
|
/// Check if the user is allowed to login
|
|
int account_status;
|
|
if(conn.exec(make_str("select account_status from bs_user where username='",
|
|
username,
|
|
"'"),
|
|
[&](MySQLResult& res)
|
|
{
|
|
res.stepRow([&](char** val,unsigned long* len)
|
|
{
|
|
account_status=ParseInt(val[0]);
|
|
});
|
|
})<0)
|
|
{
|
|
jsonfail(err_sql,"Step 2");
|
|
break;
|
|
}
|
|
|
|
if(account_status==0)
|
|
{
|
|
/// Act as auth failed (username or password wrong) when account is hidden.
|
|
jsonfail(err_data,"Auth Failed");
|
|
break;
|
|
}
|
|
else if(account_status==1)
|
|
{
|
|
/// Banned
|
|
jsonfail(err_data,"Your account is banned.");
|
|
break;
|
|
}
|
|
else if(account_status==2)
|
|
{
|
|
/// Need verify, redirect to account enable.
|
|
jsonfail(err_data,"Need verify first.");
|
|
j["next_url"]="/booksys/enable.html";
|
|
}
|
|
|
|
/// Try to mark session logged in
|
|
int ret;
|
|
if((ret=se.setUser(username))<0)
|
|
{
|
|
jsonfail(err_session,make_str("Failed to set session, ret=",ret));
|
|
break;
|
|
}
|
|
|
|
j["success"]=1;
|
|
}
|
|
while(0);
|
|
|
|
res.content.append(j.dump());
|
|
res.show();
|
|
|
|
return 0;
|
|
}
|