aboutsummaryrefslogtreecommitdiff
path: root/backend/db/db.go
blob: 9bfe55a102582d7f092d299fefae155dd4d7c8e9 (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
package db

import (
	"fmt"
	"os"
	"time"

	"github.com/jackyzha0/ctrl-v/hashing"
	"github.com/joho/godotenv"
	log "github.com/sirupsen/logrus"
)

func init() {
	// load .env file
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file: %s", err.Error())
	}

	mUser := os.Getenv("MONGO_USER")
	mPass := os.Getenv("MONGO_PASS")
	mIP := os.Getenv("MONGO_SHARD_URL")

	initSessions(mUser, mPass, mIP)
}

const TitleLimit = 100
const ContentLimit = 100000

// creates a new paste with title, content and hash, returns the hash of the created paste
func New(ip, content, expiry, title, password string) (string, error) {
	// generate hash from ip
	hash := hashing.GenerateURI(ip)

	// check for size of title and content
	errs := checkLengths(title, content)
	if errs != nil {
		return "", errs
	}

	// hash given password
	hashedPass, err := hashing.HashPassword(password)
	if err != nil {
		return "", fmt.Errorf("could not hash password: %s", err.Error())
	}

	// create new struct
	new := Paste{
		Hash:     hash,
		Content:  content,
		Title:    title,
		Password: hashedPass,
	}

	// check if expiry
	if expiry != "" {
		t, err := time.Parse(time.RFC3339, expiry)

		// if time format not current
		if err != nil {
			return "", err
		}

		// time is in the past
		if time.Now().After(t) {
			return "", fmt.Errorf("time %s is in the past", t.String())
		}

		new.Expiry = t

	} else {
		// 5 year expiry
		new.Expiry = time.Now().Add(time.Hour * 43800)
	}

	// insert struct
	log.Infof("create new paste with hash %s", hash)
	insertErr := insert(new)
	return hash, insertErr
}

func checkLengths(title string, content string) error {
	errs := ""
	if len(title) > TitleLimit {
		errs += fmt.Sprintf("title is longer than character limit of %d\n", TitleLimit)
	}
	if len(content) > ContentLimit {
		errs += fmt.Sprintf("content is longer than character limit of %d\n", ContentLimit)
	}
	// if any errors were found
	if errs != "" {
		return fmt.Errorf(errs)
	}

	return nil
}

// lookup
func Lookup(hash string) (Paste, error) {
	return fetch(hash)
}