DEVELOPMENT ENVIRONMENT

~liljamo/felu

ref: 6b83684da956b580c5c32129848a1ff66f42e0c6 felu/internal/db/domains.go -rw-r--r-- 2.2 KiB
6b83684dJonni Liljamo docs: add README.md 1 year, 29 days ago
                                                                                
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */
package db

import (
	"errors"

	"git.src.quest/~skye/felu-ddns/internal/util"
	"github.com/oklog/ulid/v2"
)

type Domain struct {
	Id      string
	ApiKey  string
	Domain  string
	A       string
}

func FetchDomainsForUser(userId string) ([]Domain, error) {
	rows, err := DBConn.Query(`SELECT id, apikey, ddns_domain, a_record
		FROM domains WHERE owner = $1`, userId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var domains []Domain
	for rows.Next() {
		var domain Domain
		err = rows.Scan(&domain.Id, &domain.ApiKey, &domain.Domain, &domain.A)
		if err != nil {
			return nil, err
		}
		domains = append(domains, domain)
	}
	err = rows.Err()
	if err != nil {
		return nil, err
	}

	return domains, nil
}

func CreateDomain(domain string, aRecord string, owner string) error {
	ulid := ulid.Make().String()
	apikey := util.GenApiKey()
	_, err := DBConn.Exec(`INSERT INTO domains(id, apikey, ddns_domain, a_record, owner)
		VALUES ($1, $2, $3, $4, $5)`, ulid, apikey, domain, aRecord, owner)
	if err != nil {
		return err
	}

	return nil
}

func DeleteDomain(id string) error {
	_, err := DBConn.Exec(`DELETE FROM domains WHERE id = $1`, id)
	if err != nil {
		return err
	}
	return nil
}

func DeleteDomainsForUser(userId string) error {
	_, err := DBConn.Exec(`DELETE FROM domains WHERE owner = $1`, userId)
	if err != nil {
		return err
	}
	return nil
}

func FetchDomainARecord(ddns_domain string) (string, error) {
	var aRecord string
	err := DBConn.QueryRow(`SELECT a_record FROM domains WHERE ddns_domain = $1`,
		ddns_domain).Scan(&aRecord)
	if err != nil {
		return "", err
	}
	return aRecord, nil
}

func UpdateDomainARecord(ddns_domain string, providedApiKey string, aRecord string) error {
	var domainApiKey string
	err := DBConn.QueryRow(`SELECT apikey FROM domains WHERE ddns_domain = $1`,
		ddns_domain).Scan(&domainApiKey)
	if err != nil {
		return err
	}

	if domainApiKey != providedApiKey {
		return errors.New("API key doesn't match")
	}

	_, err = DBConn.Exec(`UPDATE domains SET a_record = $1 WHERE ddns_domain = $2`,
		aRecord, ddns_domain)
	if err != nil {
		return err
	}
	
	return nil
}