1
0
Fork 0
forked from jriou/coller

feat: Add password protection

Fixes #37.

BREAKING CHANGE: API routes are prefixed by /api/note.

Signed-off-by: Julien Riou <julien@riou.xyz>
This commit is contained in:
Julien Riou 2025-09-27 08:35:26 +02:00
commit 9e0254c0b5
Signed by: jriou
GPG key ID: 9A099EDA51316854
16 changed files with 713 additions and 135 deletions

View file

@ -8,6 +8,7 @@ import (
"time"
"github.com/bwmarrin/snowflake"
"golang.org/x/crypto/bcrypt"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
@ -122,7 +123,7 @@ func (d *Database) Get(id string) (*Note, error) {
return nil, nil
}
func (d *Database) Create(content []byte, encryptionKey string, encrypted bool, expiration int, deleteAfterRead bool, language string) (note *Note, err error) {
func (d *Database) Create(content []byte, password string, encryptionKey string, encrypted bool, expiration int, deleteAfterRead bool, language string) (note *Note, err error) {
if expiration == 0 {
expiration = d.expiration
}
@ -148,6 +149,7 @@ func (d *Database) Create(content []byte, encryptionKey string, encrypted bool,
DeleteAfterRead: deleteAfterRead,
Language: language,
}
if encryptionKey != "" {
if err = internal.ValidateEncryptionKey(encryptionKey); err != nil {
return nil, err
@ -158,12 +160,22 @@ func (d *Database) Create(content []byte, encryptionKey string, encrypted bool,
}
note.Encrypted = true
}
if password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
note.PasswordHash = hash
}
trx := d.db.Create(note)
defer trx.Commit()
if trx.Error != nil {
d.logger.Warn("could not create note", slog.Any("error", trx.Error))
return nil, trx.Error
}
return note, nil
}