#define _POSIX_C_SOURCE 200809L #include "jwt.h" #include #include #include #include #include #include #include char *gencookie(const char *const name, const char *const key) { char *ret = NULL, *sname = NULL, *c = NULL, *jwt = NULL; unsigned char dkey[crypto_auth_hmacsha256_KEYBYTES]; size_t len; cJSON *j = NULL; time_t t = time(NULL); struct tm tm; if (t == (time_t)-1) { fprintf(stderr, "%s: time(2): %s\n", __func__, strerror(errno)); goto end; } /* Set 5-year lifetime for cookies. */ t += 5 * 365 * 24 * 60 * 60; if (!localtime_r(&t, &tm)) { fprintf(stderr, "%s: localtime_r(3): %s\n", __func__, strerror(errno)); goto end; } else if (!(j = cJSON_CreateObject())) { fprintf(stderr, "%s: cJSON_CreateObject failed\n", __func__); goto end; } else if (!cJSON_AddStringToObject(j, "name", name)) { fprintf(stderr, "%s: cJSON_AddStringToObject failed\n", __func__); goto end; } else if (sodium_hex2bin(dkey, sizeof dkey, key, strlen(key), NULL, &len, NULL)) { fprintf(stderr, "%s: sodium_hex2bin failed\n", __func__); goto end; } else if (!(jwt = jwt_encode(j, dkey, sizeof dkey))) { fprintf(stderr, "%s: jwt_encode failed\n", __func__); goto end; } else if (!(c = http_cookie_create(name, jwt, &tm))) { fprintf(stderr, "%s: http_cookie_create failed\n", __func__); goto end; } ret = c; end: if (!ret) free(c); free(jwt); free(sname); cJSON_Delete(j); return ret; }