You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
2.7 KiB
C

#include "client_app.h"
#include "json/json.h"
#include "json/layout.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#define OBJ_TYPE struct client_app
static struct json_object_field client_app_layout[] = {
{
.key = "name",
.offset = offsetof( struct client_app, client.name ),
.required = false,
.type = &json_field_string
},
JSON_FIELD_STRING( auth_code, false ),
JSON_FIELD_STRING( access_token, false ),
JSON_FIELD_STRING( redirect_uri, false ),
{
.key = "secret",
.offset = offsetof( struct client_app, client.secret ),
.required = true,
.type = &json_field_string },
JSON_FIELD_END,
};
#undef OBJ_TYPE
struct client_app* client_app_from_id( const char* client_id )
{
char filename[512];
snprintf( filename, 512, "data/client_apps/%s.json", client_id );
struct client_app* app = malloc(sizeof(struct client_app));
app->client.name = NULL;
app->client.id = strdup(client_id);
app->client.secret = NULL;
app->auth_code = NULL;
app->redirect_uri = NULL;
app->access_token = NULL;
if( !json_read_object_layout_from_file( filename, client_app_layout, app ) ) {
client_app_free(app);
return NULL;
}
return app;
}
struct client_app* client_app_new( const char* client_name )
{
char id[33];
for( int i = 0; i < 32; ++i ) {
id[i] = 'a' + (rand() % 26);
}
id[32] = '\0';
char secret[65];
for( int i = 0; i < 64; ++i ) {
secret[i] = 'a' + (rand() % 26);
}
secret[64] = '\0';
struct client_app* app = malloc(sizeof(struct client_app));
app->client.id = strdup(id);
app->client.name = strdup(client_name);
app->client.secret = strdup(secret);
app->auth_code = NULL;
app->redirect_uri = NULL;
app->access_token = NULL;
client_app_save(app);
return app;
}
void client_app_save( struct client_app* app )
{
char filename[512];
snprintf( filename, 512, "data/client_apps/%s.json", app->client.id );
json_write_object_layout_to_file( filename, "\t", client_app_layout, app );
}
void client_app_free( struct client_app* app )
{
if( !app ) { return; }
free(app->client.name);
free(app->client.secret);
free(app->client.id);
free(app->auth_code);
free(app->redirect_uri);
free(app->access_token);
free(app);
}
void client_app_gen_auth_code( struct client_app* app )
{
char* auth_code = app->auth_code = malloc(65);
for( int i = 0; i < 64; ++i ) {
auth_code[i] = 'a'+(rand()%26);
}
auth_code[64] = '\0';
client_app_save(app);
}
void client_app_generate_access_token( struct client_app* app )
{
char code[33];
char* access_token = app->access_token = malloc(32+1+32+1);
for( int i = 0; i < 32; ++i ) {
code[i] = 'a'+(rand()%26);
}
code[32] = '\0';
snprintf( access_token, 32+1+32+1, "%s-%s", app->client.id, code );
client_app_save(app);
}