diff options
Diffstat (limited to 'src/sessions.c')
| -rw-r--r-- | src/sessions.c | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/src/sessions.c b/src/sessions.c new file mode 100644 index 0000000..66ec375 --- /dev/null +++ b/src/sessions.c @@ -0,0 +1,86 @@ +#include "sessions.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "util.h" + +static struct session *g_sessions; +static long g_ttl = 8 * 3600; + +void sessions_init(long ttl_seconds) +{ + if (ttl_seconds > 0) + g_ttl = ttl_seconds; +} + +struct session *sessions_create(int64_t user_id, int is_admin, + int64_t active_org, int64_t bound_org, + const char *scopes) +{ + struct session *s = xcalloc(1, sizeof *s); + char *id = util_random_id("s_", 18); + snprintf(s->id, sizeof s->id, "%s", id); + free(id); + s->user_id = user_id; + s->is_admin = is_admin; + s->active_org = active_org; + s->bound_org = bound_org; + snprintf(s->scopes, sizeof s->scopes, "%s", scopes ? scopes : "read"); + s->created = s->last_seen = s->expires = util_now(); + s->expires = s->created + g_ttl; + s->next = g_sessions; + g_sessions = s; + return s; +} + +struct session *sessions_get(const char *id) +{ + if (!id) + return NULL; + int64_t now = util_now(); + struct session **pp = &g_sessions; + while (*pp) { + struct session *s = *pp; + if (s->expires <= now) { + *pp = s->next; + free(s); + continue; + } + if (strcmp(s->id, id) == 0) { + s->last_seen = now; + s->expires = now + g_ttl; + return s; + } + pp = &s->next; + } + return NULL; +} + +void sessions_destroy(const char *id) +{ + if (!id) + return; + struct session **pp = &g_sessions; + while (*pp) { + struct session *s = *pp; + if (strcmp(s->id, id) == 0) { + *pp = s->next; + free(s); + return; + } + pp = &s->next; + } +} + +void sessions_free_all(void) +{ + struct session *s = g_sessions; + while (s) { + struct session *next = s->next; + free(s); + s = next; + } + g_sessions = NULL; +} |
