4 #include <json-c/json.h>
6 #define AFB_BINDING_VERSION 3
7 #include <afb/afb-binding>
9 afb::event event_login, event_logout;
16 session(const char *user) : user_(user) {}
18 operator const char *() const { return user_.c_str(); }
21 void login(afb::req req)
23 json_object *args, *user, *passwd;
27 if (!json_object_object_get_ex(args, "user", &user)
28 || !json_object_object_get_ex(args, "password", &passwd)) {
29 AFB_REQ_ERROR(req, "login, bad request: %s", json_object_get_string(args));
30 req.fail("bad-request");
31 } else if (afb_req_context_get(req)) {
32 AFB_REQ_ERROR(req, "login, bad state, logout first");
33 req.fail("bad-state");
34 } else if (strcmp(json_object_get_string(passwd), "please")) {
35 AFB_REQ_ERROR(req, "login, unauthorized: %s", json_object_get_string(args));
36 req.fail("unauthorized");
38 usr = json_object_get_string(user);
39 AFB_REQ_NOTICE(req, "login user: %s", usr);
40 req.context<session>().set(new session(usr));
41 req.session_set_LOA(1);
43 event_login.push(json_object_new_string(usr));
47 void action(afb::req req)
49 json_object *args, *val;
50 session &usr = req.context<session>();
53 AFB_REQ_NOTICE(req, "action for user %s: %s", (const char*)usr, json_object_get_string(args));
54 if (json_object_object_get_ex(args, "subscribe", &val)) {
55 if (json_object_get_boolean(val)) {
56 AFB_REQ_NOTICE(req, "user %s subscribes to events", (const char*)usr);
57 req.subscribe(event_login);
58 req.subscribe(event_logout);
60 AFB_REQ_NOTICE(req, "user %s unsubscribes to events", (const char*)usr);
61 req.unsubscribe(event_login);
62 req.unsubscribe(event_logout);
65 req.success(json_object_get(args));
68 void logout(afb::req req)
70 session &usr = req.context<session>();
72 AFB_REQ_NOTICE(req, "login user %s out", (const char*)usr);
73 event_logout.push(json_object_new_string((const char*)usr));
74 req.session_set_LOA(0);
75 req.context<session>().clear();
79 int init(afb_api_t api)
82 event_login = afb_daemon_make_event("login");
83 event_logout = afb_daemon_make_event("logout");
84 if (afb_event_is_valid(event_login) && afb_event_is_valid(event_logout))
86 AFB_ERROR("Can't create events");
90 const afb_verb_t verbs[] = {
91 afb::verb("login", login, "log in the system"),
92 afb::verb("action", action, "perform an action", AFB_SESSION_LOA_1),
93 afb::verb("logout", logout, "log out the system", AFB_SESSION_LOA_1),
97 const afb_binding_t afbBindingExport = afb::binding("tuto-3", verbs, "third tutorial: C++", init);