summaryrefslogtreecommitdiff
path: root/db/bearer.go
blob: b16d5061d24593305c48cc457337f5cb12ea5c9e (plain) (blame)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package db

import (
	"errors"
	"time"

	_ "github.com/mattn/go-sqlite3"
)

type Bearer struct {
	id, accountId uint
	Token         string
	ValidUpTo     time.Time
}

func (b *Bearer) FromToken(safe *SafeDB, Token string) error {
	const sqlStatementBearer string = `
		SELECT id, ValidUpTo, accountId
		FROM Bearer
		WHERE Bearer.Token = ?
	`

	b.Token = Token
	var ValidUpToString string
	safe.mu.Lock()
	row := safe.db.QueryRow(sqlStatementBearer, Token)
	safe.mu.Unlock()

	err := row.Scan(
		&b.id,
		&ValidUpToString,
		&b.accountId,
	)
	if err != nil {
		return err
	}

	layout := "2006-01-02 15:04:05.999999999-07:00"
	b.ValidUpTo, err = time.Parse(layout, ValidUpToString)
	if err != nil {
		return err
	}

	timeNow := time.Now()
	if timeNow.After(b.ValidUpTo) {
		return errors.New("Outdated Bearer Token")
	}

	return err
}

func (b *Bearer) Update(safe *SafeDB) error {
	const sqlStatementBearer string = `
		UPDATE Bearer
		SET ValidUpTo = ?
		WHERE id = ?
	`

	validUpTo := time.Now().Add(time.Hour * 24)
	safe.mu.Lock()
	_, err := safe.db.Exec(sqlStatementBearer, validUpTo, b.id)
	safe.mu.Unlock()
	if err != nil {
		return err
	}
	b.ValidUpTo = validUpTo

	return nil
}

func (b *Bearer) VerifyAndUpdate(safe *SafeDB, token string) error {
	err := b.FromToken(safe, token)
	if err != nil {
		return err
	}

	err = b.Update(safe)
	if err != nil {
		return err
	}

	return nil
}

func (b *Bearer) Generate(safe *SafeDB, lg *Login) error {
	const sqlGenBearer string = `
		INSERT INTO Bearer (
			id,
			Token,
			ValidUpTo,
			accountId
		)
		VALUES (NULL, ?, ?, ?);
	`

	Token, err := GenRandomString(128)
	if err != nil {
		return err
	}

	timeNow := time.Now()
	ValidUpTo := timeNow.Add(time.Hour * 24)
	safe.mu.Lock()
	res, err := safe.db.Exec(
		sqlGenBearer,
		Token,
		ValidUpTo,
		lg.id,
	)
	safe.mu.Unlock()
	if err != nil {
		return err
	}

	id, err := res.LastInsertId()
	if err != nil {
		return err
	}

	b.id = uint(id)
	b.accountId = lg.id
	b.Token = Token
	b.ValidUpTo = ValidUpTo
	lg.Bearer = b

	return err
}