commit 428c887f8cd2fce624928aefdb007582e939c893
parent 474cb6125ccd6c07958e9b6edf185849f11a7eaa
Author: n0tr1v <n0tr1v@protonmail.com>
Date: Thu, 22 Dec 2022 16:01:03 -0800
move some code & handle errors
Diffstat:
3 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/pkg/database/tableUploads.go b/pkg/database/tableUploads.go
@@ -1,6 +1,7 @@
package database
import (
+ "dkforest/pkg/config"
"dkforest/pkg/utils"
"io/ioutil"
"os"
@@ -25,10 +26,18 @@ type Upload struct {
// CreateUpload create file on disk in "uploads" folder, and save upload in database as well.
func CreateUpload(fileName string, content []byte, userID UserID) (*Upload, error) {
- return CreateUploadWithSize(fileName, content, userID, int64(len(content)))
+ return createUploadWithSize(fileName, content, userID, int64(len(content)))
}
-func CreateUploadWithSize(fileName string, content []byte, userID UserID, size int64) (*Upload, error) {
+func CreateEncryptedUploadWithSize(fileName string, content []byte, userID UserID, size int64) (*Upload, error) {
+ encryptedContent, err := utils.EncryptAES(content, []byte(config.Global.MasterKey()))
+ if err != nil {
+ return nil, err
+ }
+ return createUploadWithSize(fileName, encryptedContent, userID, size)
+}
+
+func createUploadWithSize(fileName string, content []byte, userID UserID, size int64) (*Upload, error) {
newFileName := utils.MD5([]byte(utils.GenerateToken32()))
if err := ioutil.WriteFile(filepath.Join("uploads", newFileName), content, 0644); err != nil {
return nil, err
diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go
@@ -323,6 +323,9 @@ func Dot(in int64) string {
// EncryptAES ...
func EncryptAES(plaintext []byte, key []byte) ([]byte, error) {
gcm, ns, err := getGCMKeyBytes(key)
+ if err != nil {
+ return nil, err
+ }
nonce := make([]byte, ns)
if _, err = io.ReadFull(cryptoRand.Reader, nonce); err != nil {
return nil, err
diff --git a/pkg/web/handlers/api/v1/uploadInterceptor.go b/pkg/web/handlers/api/v1/uploadInterceptor.go
@@ -1,7 +1,6 @@
package v1
import (
- "dkforest/pkg/config"
"dkforest/pkg/database"
"dkforest/pkg/utils"
hutils "dkforest/pkg/web/handlers/utils"
@@ -60,9 +59,7 @@ func handleUploadedFile(file multipart.File, handler *multipart.FileHeader, auth
}
// Uploaded files are encrypted on disk
- fileBytes, _ = utils.EncryptAES(fileBytes, []byte(config.Global.MasterKey()))
-
- upload, err := database.CreateUploadWithSize(origFileName, fileBytes, authUser.ID, handler.Size)
+ upload, err := database.CreateEncryptedUploadWithSize(origFileName, fileBytes, authUser.ID, handler.Size)
if err != nil {
logrus.Error(err)
return nil, err