1
0
mirror of https://github.com/lus/pasty.git synced 2023-08-10 21:13:09 +03:00

Implement basic configuration and storage structure

This commit is contained in:
Lukas SP
2020-08-22 23:24:38 +02:00
parent 9bd6044e39
commit ba0aebdb62
8 changed files with 132 additions and 20 deletions

View File

@@ -0,0 +1,27 @@
package pastes
import (
"github.com/Lukaesebrot/pasty/internal/env"
"math/rand"
"strconv"
)
// deletionTokenContents represents the characters a deletion token may contain
const deletionTokenContents = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#+-.,"
// generateDeletionToken generates a new deletion token
func generateDeletionToken() (string, error) {
// Read the deletion token length
rawLength := env.Get("DELETION_TOKEN_LENGTH", "12")
length, err := strconv.Atoi(rawLength)
if err != nil {
return "", err
}
// Generate the deletion token
bytes := make([]byte, length)
for i := range bytes {
bytes[i] = deletionTokenContents[rand.Int63()%int64(len(deletionTokenContents))]
}
return string(bytes), nil
}

View File

@@ -1,6 +1,16 @@
package pastes
import "github.com/bwmarrin/snowflake"
import (
"github.com/alexedwards/argon2id"
"github.com/bwmarrin/snowflake"
)
func init() {
snowflakeNode, _ = snowflake.NewNode(1)
}
// snowflakeNode holds the current snowflake node
var snowflakeNode *snowflake.Node
// Paste represents a saved paste
type Paste struct {
@@ -9,3 +19,39 @@ type Paste struct {
SuggestedSyntaxType string `json:"suggestedSyntaxType" bson:"suggestedSyntaxType"`
DeletionToken string `json:"deletionToken" bson:"deletionToken"`
}
// Create creates a new paste object using the given content
func Create(content string) (*Paste, error) {
// TODO: Generate the suggested syntax type
suggestedSyntaxType := ""
// Generate the deletion token
deletionToken, err := generateDeletionToken()
if err != nil {
return nil, err
}
// Return the paste object
return &Paste{
ID: snowflakeNode.Generate(),
Content: content,
SuggestedSyntaxType: suggestedSyntaxType,
DeletionToken: deletionToken,
}, nil
}
// HashDeletionToken hashes the current deletion token of a paste
func (paste *Paste) HashDeletionToken() error {
hash, err := argon2id.CreateHash(paste.DeletionToken, argon2id.DefaultParams)
if err != nil {
return err
}
paste.DeletionToken = hash
return nil
}
// CheckDeletionToken checks whether or not the given deletion token is correct
func (paste *Paste) CheckDeletionToken(deletionToken string) bool {
match, err := argon2id.ComparePasswordAndHash(deletionToken, paste.DeletionToken)
return err != nil && match
}