This repository has been archived on 2021-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
DBHomework/join.cpp
2017-11-20 09:40:00 +08:00

123 lines
2.9 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.getUser().empty())
{
/// Logged in. Redirect user to dashboard.
j["success"]=2;
j["next_url"]="/booksys/dashboard.html";
break;
}
if(req.requestMethod!="POST")
{
jsonfail(err_method_not_supported);
break;
}
if(req.post["account"].empty() ||
req.post["pass"].empty() ||
req.post["nickname"].empty())
{
jsonfail(err_missing_parameter);
break;
}
postval(account);
postval(pass);
postval(nickname);
/// Connect DB
DBInfo db;
MySQLConn conn;
if(db.readConfig()<0)
{
jsonfail(err_config);
break;
}
if(db.connectProxy(conn)<0)
{
jsonfail(err_connect);
break;
}
/// Check username conflict
int count_val;
if(conn.exec(make_str("select count(username) from bs_user where username='",
account,
"'"),
[&](MySQLResult& res)
{
res.stepRow([&](char** val,unsigned long* len)
{
count_val=ParseInt(val[0]);
});
})<0)
{
jsonfail(err_sql);
break;
}
if(count_val!=0)
{
jsonfail(err_data,"username conflict");
break;
}
/// Do insert
if(conn.exec(make_str("insert into bs_user values ('",
account,
"','",
pass,
"','",
nickname,
"',3,2"),nullptr)<0)
{
jsonfail(err_sql);
break;
}
if(conn.getAffectedRows()!=1)
{
jsonfail(err_sql_logic,"Affected rows not equals 1");
break;
}
/// Redirect user to enable page.
j["success"]=1;
j["next_url"]="/booksys/enable.html";
}while(0);
res.content.append(j.dump());
res.show();
return 0;
}