1 #include <afb/c++/binding>
2 #include <json-c/json.h>
6 : public afb::base_api_t<tuto5>
9 afb::event event_login;
10 afb::event event_logout;
13 void login(afb::req req)
15 json_object *user, *passwd;
17 json_object* args = req.json();
18 if (!json_object_object_get_ex(args, "user", &user)
19 || !json_object_object_get_ex(args, "password", &passwd)) {
20 AFB_REQ_ERROR(req, "login, bad request: %s", json_object_get_string(args));
21 req.fail("bad-request");
22 } else if (afb_req_context_get(req)) {
23 AFB_REQ_ERROR(req, "login, bad state, logout first");
24 req.fail("bad-state");
25 } else if (std::string(json_object_get_string(passwd)) != std::string("please")) {
26 AFB_REQ_ERROR(req, "login, unauthorized: %s", json_object_get_string(args));
27 req.fail("unauthorized");
29 char* username = strdup(json_object_get_string(user));
30 AFB_REQ_NOTICE(req, "login user: %s", username);
31 req.session_set_LOA(1);
32 afb_req_context_set(req, username, free);
34 event_login.push(json_object_new_string(username));
38 void action(afb::req req) const
41 json_object* args = req.json();
42 char* username = reinterpret_cast<char*>(afb_req_context_get(req));
43 AFB_REQ_NOTICE(req, "action for user %s: %s", username, json_object_get_string(args));
44 if (json_object_object_get_ex(args, "subscribe", &val)) {
45 if (json_object_get_boolean(val)) {
46 AFB_REQ_NOTICE(req, "user %s subscribes to events", username);
47 req.subscribe(event_login);
48 req.subscribe(event_logout);
50 AFB_REQ_NOTICE(req, "user %s unsubscribes to events", username);
51 req.unsubscribe(event_login);
52 req.unsubscribe(event_logout);
55 req.success(json_object_get(args));
58 void logout(afb::req req)
60 char* username = reinterpret_cast<char*>(afb_req_context_get(req));
61 AFB_REQ_NOTICE(req, "login user %s out", username);
62 event_logout.push(json_object_new_string(username));
63 req.session_set_LOA(0);
64 afb_req_context_clear(req);
68 int preinit(afb_api_t h) override
71 (add_verb<&tuto5::login>("login", "log in the system") == 0) &&
72 (add_verb<&tuto5::action>("action", "perform an action", nullptr, nullptr, AFB_SESSION_LOA_1) == 0) &&
73 (add_verb<&tuto5::logout>("logout", "log out the system", nullptr, nullptr, AFB_SESSION_LOA_1) == 0)
79 AFB_API_NOTICE(api_, "init");
80 event_login = make_event("login");
81 event_logout = make_event("logout");
82 if (event_login.is_valid() && event_logout.is_valid())
84 AFB_API_ERROR(api_, "Can't create events");
89 int afbBindingEntry(afb_api_t h)
91 afb::new_api<tuto5>(h, "tuto-5", "fifth tutorial: C++");