1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
#define _POSIX_C_SOURCE 200809L
#include <err.h>
#include <string.h>
#include <jansson.h>
#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);
}
|