summaryrefslogtreecommitdiff
path: root/src/sessions.c
blob: 66ec375504ecfab49cb17ecbb80b10ed4af1e756 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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;
}