Subversion Repositories RepoView

Rev

Rev 3 | Rev 6 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 nishi 1
/* $Id: cookie.c 5 2024-08-20 22:43:56Z nishi $ */
3 nishi 2
 
3
#include "rv_auth.h"
4
 
5
#include "rv_util.h"
5 nishi 6
#include "rv_db.h"
3 nishi 7
 
5 nishi 8
#include <string.h>
3 nishi 9
#include <stdio.h>
10
#include <stdlib.h>
11
 
12
extern char** environ;
13
 
14
struct cookie_entry {
15
	char* key;
16
	char* value;
17
};
18
 
19
struct cookie_entry** cookie_entries;
20
 
21
void parse_cookie(void) {
22
	cookie_entries = malloc(sizeof(*cookie_entries));
23
	cookie_entries[0] = NULL;
24
	char* cookie = getenv("HTTP_COOKIE");
25
	if(cookie != NULL) {
26
		cookie = rv_strdup(cookie);
27
		int i;
28
		int incr = 0;
29
		for(i = 0;; i++) {
30
			if(cookie[i] == 0 || cookie[i] == ';') {
31
				char oldc = cookie[i];
32
				cookie[i] = 0;
33
 
34
				char* key = cookie + incr;
35
				char* value = "";
36
 
37
				int j;
38
				for(j = 0; key[j] != 0; j++) {
39
					if(key[j] == '=') {
40
						key[j] = 0;
41
						value = key + j + 1;
42
						break;
43
					}
44
				}
45
				struct cookie_entry* entry = malloc(sizeof(*entry));
46
				entry->key = rv_strdup(key);
47
				entry->value = rv_strdup(value);
48
 
49
				struct cookie_entry** old_entries = cookie_entries;
50
				for(j = 0; old_entries[j] != NULL; j++)
51
					;
52
				cookie_entries = malloc(sizeof(*cookie_entries) * (j + 2));
53
				for(j = 0; old_entries[j] != NULL; j++) {
54
					cookie_entries[j] = old_entries[j];
55
				}
56
				cookie_entries[j] = entry;
57
				cookie_entries[j + 1] = NULL;
58
 
59
				int oldi = i;
60
				i++;
61
				for(; cookie[i] != 0 && (cookie[i] == ' ' || cookie[i] == '\t'); i++)
62
					;
63
				i--;
64
				incr = i + 1;
65
				if(oldc == 0) break;
66
			}
67
		}
68
		free(cookie);
69
	}
70
}
71
 
72
char* rv_logged_in(void) {
5 nishi 73
	int i;
74
	for(i = 0; cookie_entries[i] != NULL; i++) {
75
		if(strcmp(cookie_entries[i]->key, "token") == 0) {
76
			return rv_who_has_token(cookie_entries[i]->value);
77
			break;
78
		}
79
	}
3 nishi 80
	return NULL;
81
}
82
 
5 nishi 83
void rv_save_login(const char* username) {
84
	char* token = rv_new_token(username);
85
	printf("Set-Cookie: token=%s; HttpOnly\r\n", token);
86
	free(token);
87
}
88
 
89
void rv_init_auth(void) { parse_cookie(); }
90
 
3 nishi 91
void rv_free_auth(void) {
92
	int i;
93
	for(i = 0; cookie_entries[i] != NULL; i++) {
94
		free(cookie_entries[i]->key);
95
		free(cookie_entries[i]->value);
96
		free(cookie_entries[i]);
97
	}
98
	free(cookie_entries);
99
}