From b38dd6b7373d6a05b7c09f38f39ac2059ce04e9c Mon Sep 17 00:00:00 2001
From: Jakob Kaivo <jkk@ung.org>
Date: Wed, 17 Jul 2019 21:49:40 -0400
Subject: implement authenticate()

---
 auth.c | 51 ++++++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 48 insertions(+), 3 deletions(-)

(limited to 'auth.c')

diff --git a/auth.c b/auth.c
index fb6db13..7c20f9d 100644
--- a/auth.c
+++ b/auth.c
@@ -2,10 +2,55 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.h>
 #include "blog.h"
 
-int verify_creds(const char *username, const char *password)
+int authenticate(const char *username, const char *password)
 {
-	printf("verifying '%s'/'%s'\n", username ? username : "", password ? password : "");
-	return 1;
+	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;
 }
-- 
cgit v1.2.1