aboutsummaryrefslogtreecommitdiff
path: root/backend/db/db.go
blob: 053ba87c5f08a13ebe00a43264f111a19886d399 (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
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)
}

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

	// create new struct
	new := Paste{
		Hash:    hash,
		Content: content,
	}

	// 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 t.After(time.Now()) {
			return fmt.Errorf("err: 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 insertErr
}

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