#include "sessions.h" #include #include #include #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; }