/* hubSpaceKeys.c was originally generated by the autoSql program, which also 
 * generated hubSpaceKeys.h and hubSpaceKeys.sql.  This module links the database and
 * the RAM representation of objects. */

#include "common.h"
#include "linefile.h"
#include "dystring.h"
#include "jksql.h"
#include "hubSpaceKeys.h"
#include "hdb.h"
#include "hgConfig.h"
#include "htmshell.h"


char *hubSpaceKeysCommaSepFieldNames = "userName,apiKey";

void hubSpaceKeysStaticLoad(char **row, struct hubSpaceKeys *ret)
/* Load a row from hubSpaceKeys table into ret.  The contents of ret will
 * be replaced at the next call to this function. */
{

ret->userName = row[0];
ret->apiKey = row[1];
}

struct hubSpaceKeys *hubSpaceKeysLoad(char **row)
/* Load a hubSpaceKeys from row fetched with select * from hubSpaceKeys
 * from database.  Dispose of this with hubSpaceKeysFree(). */
{
struct hubSpaceKeys *ret;

AllocVar(ret);
ret->userName = cloneString(row[0]);
ret->apiKey = cloneString(row[1]);
return ret;
}

struct hubSpaceKeys *hubSpaceKeysLoadAll(char *fileName) 
/* Load all hubSpaceKeys from a whitespace-separated file.
 * Dispose of this with hubSpaceKeysFreeList(). */
{
struct hubSpaceKeys *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[2];

while (lineFileRow(lf, row))
    {
    el = hubSpaceKeysLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct hubSpaceKeys *hubSpaceKeysLoadAllByChar(char *fileName, char chopper) 
/* Load all hubSpaceKeys from a chopper separated file.
 * Dispose of this with hubSpaceKeysFreeList(). */
{
struct hubSpaceKeys *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[2];

while (lineFileNextCharRow(lf, chopper, row, ArraySize(row)))
    {
    el = hubSpaceKeysLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct hubSpaceKeys *hubSpaceKeysCommaIn(char **pS, struct hubSpaceKeys *ret)
/* Create a hubSpaceKeys out of a comma separated string. 
 * This will fill in ret if non-null, otherwise will
 * return a new hubSpaceKeys */
{
char *s = *pS;

if (ret == NULL)
    AllocVar(ret);
ret->userName = sqlStringComma(&s);
ret->apiKey = sqlStringComma(&s);
*pS = s;
return ret;
}

void hubSpaceKeysFree(struct hubSpaceKeys **pEl)
/* Free a single dynamically allocated hubSpaceKeys such as created
 * with hubSpaceKeysLoad(). */
{
struct hubSpaceKeys *el;

if ((el = *pEl) == NULL) return;
freeMem(el->userName);
freeMem(el->apiKey);
freez(pEl);
}

void hubSpaceKeysFreeList(struct hubSpaceKeys **pList)
/* Free a list of dynamically allocated hubSpaceKeys's */
{
struct hubSpaceKeys *el, *next;

for (el = *pList; el != NULL; el = next)
    {
    next = el->next;
    hubSpaceKeysFree(&el);
    }
*pList = NULL;
}

void hubSpaceKeysOutput(struct hubSpaceKeys *el, FILE *f, char sep, char lastSep) 
/* Print out hubSpaceKeys.  Separate fields with sep. Follow last field with lastSep. */
{
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->userName);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->apiKey);
if (sep == ',') fputc('"',f);
fputc(lastSep,f);
}

/* -------------------------------- End autoSql Generated Code -------------------------------- */

char *hubSpaceGetApiKey(char *userName)
/* Grab the already created api key if it exists */
{
char *tableName = cfgOptionDefault("authTableName", AUTH_TABLE_DEFAULT);
struct sqlConnection *conn = hConnectCentral();
struct dyString *query = sqlDyStringCreate("select apiKey from %s where userName='%s'", tableName, userName);
char *apiKey = sqlQuickString(conn, dyStringCannibalize(&query));
hDisconnectCentral(&conn);
return apiKey;
}

char *hubSpaceUserNameForApiKey(struct sqlConnection *conn, char *apiKey)
/* Return userName associated with apiKey else NULL. If conn is NULL, will create a connection and free it. */
{
char *tableName = cfgOptionDefault("authTableName", AUTH_TABLE_DEFAULT);

boolean doClose = FALSE;
if (conn == NULL)
    {
    conn = hConnectCentral();
    doClose = TRUE;
    }

struct dyString *query = sqlDyStringCreate("select userName from %s where apiKey = '%s'", tableName, apiKey);
char *userName = sqlQuickString(conn, dyStringCannibalize(&query));
if (doClose)
    hDisconnectCentral(&conn);
return userName;
}

void hubSpaceRevokeApiKey(char *userName)
/* Remove any api keys for userName. errAborts if userName is NULL.
 * Run in an errCatch to handle errors. */
{
if (!userName)
    errAbort("hubSpaceRevokeApiKey: no userName. You must be logged in to revoke your api key");

char *tableName = cfgOptionDefault("authTableName", AUTH_TABLE_DEFAULT);
struct sqlConnection *conn = hConnectCentral();
struct dyString *query = sqlDyStringCreate("delete from %s where userName='%s'", tableName, userName);
sqlUpdate(conn, dyStringCannibalize(&query));
hDisconnectCentral(&conn);
}

char *hubSpaceGenerateApiKey(char *userName)
/* Make a random (but not crypto-secure) api key for userName, for use of hubtools to upload
 * to hubspace or for bypassing cloudflare. errAborts if userName is NULL.
 * Run in an errCatch to handle errors. */
{
if (!userName)
    errAbort("hubSpaceGenerateApiKey: no userName. You must be logged in to generate an api key");

char *apiKey = makeRandomKey(256); // just needs some arbitrary length
// save this key to the database for this user, the 'on duplicate' part automatically revokes old keys
struct sqlConnection *conn = hConnectCentral();
char *tableName = cfgOptionDefault("authTableName", AUTH_TABLE_DEFAULT);
struct dyString *query = sqlDyStringCreate("insert into %s values ('%s', '%s') on duplicate key update apiKey='%s'", tableName, userName, apiKey, apiKey);
sqlUpdate(conn, dyStringCannibalize(&query));
hDisconnectCentral(&conn);
return apiKey;
}
