#define _POSIX_C_SOURCE 200809L #include #include #include #include "string-util.h" #include "auth.h" #include "http.h" #define CLIENT_NAME "ap_client" char *instance_domain; char *auth_token; char *req_data; char *client_id; char *client_secret; static char *protocol = "https://"; static char *app_register_url = "/api/v1/apps"; static void register_callback(char *data) { if (req_data) free(req_data); if (!data) { fprintf(stderr, "register_callback(): null data\n"); return; } json_t *root; root = json_loads(data, 0, NULL); free(data); if (!root) { fprintf(stderr, "register_callback(): failed to parse json\n"); return; } if (!json_is_object(root)) { fprintf(stderr, "register_callback(): json root is not object\n"); json_decref(root); return; } json_t *cid = json_object_get(root, "client_id"); json_t *csec = json_object_get(root, "client_secret"); if (!json_is_string(cid) || !json_is_string(csec)) { fprintf(stderr, "register_callback(): invalid client_id or client_secret\n"); json_decref(root); return; } client_id = strdup(json_string_value(cid)); client_secret = strdup(json_string_value(csec)); json_decref(root); if (strlen(client_id) < 1 || strlen(client_secret) < 1) { fprintf(stderr, "register_callback(): invalid client_id or client_secret\n"); return; } printf("cid: %s\ncsec: %s\n", client_id, client_secret); } int register_app(char *instance) { json_t *root; json_error_t error; char *url; root = json_pack_ex(&error, 1, "{s:s, s:s, s:s}", "client_name", CLIENT_NAME, "redirect_uris", "urn:ietf:wg:oauth:2.0:oob", "scopes", "read write push"); if (!root) { fprintf(stderr, "register_app(): json pack error: line %d: %s\n", error.line, error.text); return -1; } req_data = json_dumps(root, 0); json_decref(root); if (!req_data) { fprintf(stderr, "register_app(): failed to dump json\n"); return -1; } size_t s = strlen(protocol) + strlen(instance) + strlen(app_register_url) + 1; url = malloc(s); if (!url) { err(1, "register_app(): "); } sprintf(url, "%s%s%s", protocol, instance, app_register_url); if (http_post_async(url, req_data, ®ister_callback)) { fprintf(stderr, "register_app(): failed to send http request\n"); free(req_data); return -1; } return 0; } void auth_cleanup() { if (instance_domain) free(instance_domain); if (auth_token) free(auth_token); if (req_data) free(req_data); if (client_id) free(client_id); if (client_secret) free(client_secret); }