2 #include <json-c/json.h>
4 #define AFB_BINDING_VERSION 3
5 #include <afb/afb-binding.h>
7 afb_event_t event_login, event_logout;
9 void login(afb_req_t req)
11 json_object *args, *user, *passwd;
14 args = afb_req_json(req);
15 if (!json_object_object_get_ex(args, "user", &user)
16 || !json_object_object_get_ex(args, "password", &passwd)) {
17 AFB_REQ_ERROR(req, "login, bad request: %s", json_object_get_string(args));
18 afb_req_reply(req, NULL, "bad-request", NULL);
19 } else if (afb_req_context_get(req)) {
20 AFB_REQ_ERROR(req, "login, bad state, logout first");
21 afb_req_reply(req, NULL, "bad-state", NULL);
22 } else if (strcmp(json_object_get_string(passwd), "please")) {
23 AFB_REQ_ERROR(req, "login, unauthorized: %s", json_object_get_string(args));
24 afb_req_reply(req, NULL, "unauthorized", NULL);
26 usr = strdup(json_object_get_string(user));
27 AFB_REQ_NOTICE(req, "login user: %s", usr);
28 afb_req_session_set_LOA(req, 1);
29 afb_req_context_set(req, usr, free);
30 afb_req_reply(req, NULL, NULL, NULL);
31 afb_event_push(event_login, json_object_new_string(usr));
35 void action(afb_req_t req)
37 json_object *args, *val;
40 args = afb_req_json(req);
41 usr = afb_req_context_get(req);
42 AFB_REQ_NOTICE(req, "action for user %s: %s", usr, json_object_get_string(args));
43 if (json_object_object_get_ex(args, "subscribe", &val)) {
44 if (json_object_get_boolean(val)) {
45 AFB_REQ_NOTICE(req, "user %s subscribes to events", usr);
46 afb_req_subscribe(req, event_login);
47 afb_req_subscribe(req, event_logout);
49 AFB_REQ_NOTICE(req, "user %s unsubscribes to events", usr);
50 afb_req_unsubscribe(req, event_login);
51 afb_req_unsubscribe(req, event_logout);
54 afb_req_reply(req, json_object_get(args), NULL, NULL);
57 void logout(afb_req_t req)
61 usr = afb_req_context_get(req);
62 AFB_REQ_NOTICE(req, "login user %s out", usr);
63 afb_event_push(event_logout, json_object_new_string(usr));
64 afb_req_session_set_LOA(req, 0);
65 afb_req_context_clear(req);
66 afb_req_reply(req, NULL, NULL, NULL);
69 int preinit(afb_api_t api)
71 AFB_API_NOTICE(api, "preinit");
75 int init(afb_api_t api)
77 AFB_API_NOTICE(api, "init");
78 event_login = afb_api_make_event(api, "login");
79 event_logout = afb_api_make_event(api, "logout");
80 if (afb_event_is_valid(event_login) && afb_event_is_valid(event_logout))
82 AFB_API_ERROR(api, "Can't create events");
86 const afb_verb_t verbs[] = {
87 { .verb="login", .callback=login },
88 { .verb="action", .callback=action, .session=AFB_SESSION_LOA_1 },
89 { .verb="logout", .callback=logout, .session=AFB_SESSION_LOA_1 },
93 const afb_binding_t afbBindingExport = {
95 .specification = NULL,