aboutsummaryrefslogtreecommitdiff
path: root/backend/cache/cache.go
blob: 1bbec7833c3408337e97e3df6f0e768d8de9a7bd (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
package cache

import (
	"errors"
	"github.com/jackyzha0/ctrl-v/hashing"
	"sync"

	"github.com/jackyzha0/ctrl-v/db"
)

type Cache struct {
	m    map[string]db.Paste
	lock sync.RWMutex
}

var C *Cache

var PasteNotFound = errors.New("could not find a paste with that hash")
var UserUnauthorized = errors.New("paste is password protected")

func init() {
	C = &Cache{
		m: map[string]db.Paste{},
	}
}

func (c *Cache) Get(hash, userPassword string) (db.Paste, error) {
	c.lock.RLock()

	// check if hash in cache
	v, ok := c.m[hash]
	c.lock.RUnlock()

	if ok {
		// validate password
		passErr := checkPassword(v.Password, userPassword)
		if passErr != nil {
			return db.Paste{}, passErr
		} else {
			return v, nil
		}
	}

	// if it doesnt, lookup from db
	p, err := db.Lookup(hash)
	if err != nil {
		return p, PasteNotFound
	}

	// validate password
	passErr := checkPassword(p.Password, userPassword)
	if passErr != nil {
		return db.Paste{}, passErr
	}

	c.add(p)
	return p, err
}

func checkPassword(dbPassword, parsedPassword string) error {
	// if there is a password, check the provided one against it
	if dbPassword != "" {
		// if passwords do not match, the user is unauthorized
		if !hashing.PasswordsEqual(dbPassword, parsedPassword) {
			return UserUnauthorized
		}
	}

	return nil
}

func (c *Cache) add(p db.Paste) {
	c.lock.Lock()
	defer c.lock.Unlock()

	c.m[p.Hash] = p
}