all repos — flounder @ d105e77524d5c2cb84c198b364de43d0e83cb8f1

A small site builder for the Gemini protocol

auth.go (view raw)

 1package main
 2
 3import (
 4	"bufio"
 5	"fmt"
 6	"golang.org/x/crypto/bcrypt"
 7	"os"
 8	"strings"
 9)
10
11func addUser(username string, password string) error {
12	file, err := os.OpenFile(c.PasswdFile, os.O_APPEND|os.O_CREATE, 0644)
13	if err != nil {
14		return err
15	}
16	defer file.Close()
17	hash, err := bcrypt.GenerateFromPassword([]byte(password), -1)
18	if err != nil {
19		return err
20	}
21	newUser := fmt.Sprintf("%s:%s\n", username, hash)
22	file.WriteString(newUser)
23	return nil
24}
25func checkAuth(username string, password string) error {
26	file, err := os.OpenFile(c.PasswdFile, os.O_CREATE, 0644)
27	if err != nil {
28		return err
29	}
30	defer file.Close()
31	scanner := bufio.NewScanner(file)
32	for scanner.Scan() {
33		line := scanner.Text()
34		parts := strings.Split(line, ":")
35		if len(parts) != 2 {
36			return fmt.Errorf("malformed line, no colon: %s", line)
37		}
38		if username == parts[0] {
39			return bcrypt.CompareHashAndPassword([]byte(parts[1]), []byte(password))
40		}
41	}
42	return fmt.Errorf("User not found")
43}