summaryrefslogtreecommitdiff
path: root/auth.c
blob: 7c20f9dc1bc3081399be960926a0445c4d463425 (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
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "blog.h"

int authenticate(const char *username, const char *password)
{
	int authenticated = 0;

	char *pwline = NULL;
	FILE *pwfile = fopen(PASSWORD_FILE, "r");

	if (!pwfile) {
		goto end;
	}

	size_t ulen = strlen(username);

	while (pwline == NULL) {
		char *line = NULL;
		size_t n = 0;

		if (getline(&line, &n, pwfile) == -1) {
			goto end;
		}

		if (strncmp(username, line, ulen) == 0 && line[ulen] == ':') {
			pwline = line;
			break;
		}

		free(line);
	}

	if (pwline == NULL) {
		goto end;
	}

	char *stored_password = pwline + ulen + 1;
	char *match = crypt(password, stored_password);
	if (!strncmp(match, stored_password, strlen(match))) {
		authenticated = 1;
	}

end:
	if (pwline) {
		free(pwline);
	}

	if (pwfile) {
		fclose(pwfile);
	}
	return authenticated;
}