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/addbooktype.cpp
2017-11-20 08:15:49 +08:00

109 lines
2.4 KiB
C++

#include "Session.h"
#include "Util.h"
#include "json.hpp"
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 std::string& errmsg)
{
j["success"]=0;
j["errcode"]=errcode;
j["errmsg"]=errmsg;
};
do
{
if(se.isNew()||se.getUser().empty())
{
jsonfail(1,"Please Login First");
break;
}
if(req.requestMethod!="POST")
{
jsonfail(2,"Unsupported request method");
break;
}
if(req.post["booktype"].empty())
{
jsonfail(3,"Missing Parameters");
break;
}
postval(booktype);
DBInfo db;
MySQLConn conn;
if(db.readConfig()<0)
{
jsonfail(4,"Failed to read config");
break;
}
if(db.connectProxy(conn)<0)
{
jsonfail(5,"Failed to connect DB");
break;
}
int permission_level;
if(conn.exec(make_str("select permission_level from bs_user where username='",
se.getUser(),
"'"),
[&](MySQLResult& res)
{
res.stepRow([&](char** val,unsigned long* len)
{
permission_level=ParseInt(val[0]);
});
})<0)
{
jsonfail(6,"Failed to execute SQL");
break;
}
if(permission_level>1)
{
/// Permission Denied.
jsonfail(7,"Permission denied");
break;
}
if(conn.exec(make_str("insert into bs_booktype values ('",
booktype,
"')"),nullptr)<0)
{
jsonfail(8,"Failed to execute SQL");
break;
}
else
{
if(conn.getAffectedRows()!=1)
{
jsonfail(9,"insert affects not equals 1");
break;
}
else
{
j["success"]=1;
}
}
}while(0);
res.content.append(j.dump());
res.show();
return 0;
}