This repository has been archived by the owner on Nov 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
91 lines (79 loc) · 1.94 KB
/
db.go
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
package main
import (
"fmt"
"strings"
"math/big"
"crypto/rand"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
// NewDBConnection creates and tests a new db connection and returns it.
func NewDBConnection(dbHost, dbUser, dbPassword, dbName string) (*DBConnection, error) {
connStr := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s sslmode=disable",
dbHost,
dbUser,
dbPassword,
dbName,
)
db, err := sqlx.Connect("postgres", connStr)
if err != nil {
fmt.Printf("Failed to connect to Postgres database: %s\n", err.Error())
return nil, err
}
return &DBConnection{db}, err
}
// DBConnection implements several functions for fetching and manipulation
// of reports in the database.
type DBConnection struct {
*sqlx.DB
}
const tokenRunes = "abcdefghijklmnopqrstuvwxyz0123456789"
const tokenLength = 8 // keep in sync with db.sql
func (db *DBConnection) createToken() (string, error) {
// TODO handle collisions (unique constraint violation)
var tokenBuilder strings.Builder
for i := 0; i < tokenLength; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(tokenRunes))))
if err != nil {
fmt.Printf("Failed to generate random number: %s\n", err.Error())
return "", err
}
tokenBuilder.WriteRune(rune(tokenRunes[num.Int64()]))
}
token := tokenBuilder.String()
_, err := db.Exec(
`
INSERT INTO
tokens(token)
VALUES($1);
`,
token,
)
if err != nil {
fmt.Printf("Failed to insert token into database: %s\n", err.Error())
return "", err
}
return token, nil
}
func (db *DBConnection) checkAndRemoveToken(token string) (bool, error) {
result, err := db.Exec(
`
DELETE FROM
tokens
WHERE
token = $1;
`,
token,
)
if err != nil {
fmt.Printf("Failed to delete token from database: %s\n", err.Error())
return false, err
}
rows, err := result.RowsAffected()
if err != nil {
fmt.Printf("Failed to get rows affected: %s\n", err.Error())
return false, err
}
return rows == 1, nil
}