Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions file-encryption/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require (

require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/go-chi/cors v1.2.1 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/spec v0.21.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions file-encryption/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0=
github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
Expand Down
9 changes: 9 additions & 0 deletions file-encryption/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
httpSwagger "github.com/swaggo/http-swagger"
"log"
"net/http"
Expand All @@ -34,6 +35,14 @@ func main() {
r.Use(middleware.Heartbeat("/ping"))
r.Use(middleware.Recoverer)
r.Use(middleware.Logger)
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"http://localhost*", "https://localhost*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))

r.Post("/encrypt", handler.Encrypt)
r.Post("/decrypt", handler.Decrypt)
Expand Down
16 changes: 14 additions & 2 deletions frontend/src/components/AccountDashboard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,25 @@ const onDelete = async (event: FormSubmitEvent) => {
return;
}
console.log("Starting deletion procedure...");
// TODO: Implement file deletion and remove the if statement below
// TODO: Remove this when file-transfer starts working
if (1 == 1) {
console.log("Not yet implemented");
toast.add({severity: 'error', summary: 'Operation not yet implemented', life: 3000});
return;
}
// TODO: Delete user files first
// Delete user files first
let filesToDelete = user._value.ownedFiles;
for (const file of filesToDelete) {
console.log("Deleting "+file);
let response = await fetch ("http://localhost:8080/"+file, {
method: "DELETE"
});
if (!response.ok) {
this.toast.add({severity: 'error', summary: 'Could not delete files.', life: 3000});
return;
}
}

let response = fetch(`http://localhost:2024/accounts/`+user._value.id, {method: 'DELETE'})
if ((await response).status === 200) {
await store.clearUser();
Expand Down
251 changes: 251 additions & 0 deletions frontend/src/components/AddFile.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
<template>
<Button
type="button"
label="Open Upload Form"
icon="pi pi-upload"
class="p-button-primary"
@click="showPopup = true"
/>
<div v-if="showPopup" class="popup-overlay">
<div class="popup-content">
<h3>Upload File</h3>

<Form class="form">
<!-- File Input -->
<FormField label="Choose a file:" required>
<input type="file" @change="handleFileSelection" class="file-input" />
</FormField>

<!-- Password Input -->
<FormField label="Password (optional):">
<InputText v-model="password" type="password" placeholder="Enter password to encrypt file" />
</FormField>

<!-- Tags Input -->
<FormField label="Tags:">
<div class="tags-container">
<div class="tag" v-for="(tag, index) in tags" :key="index">
{{ tag }} <button type="button" class="remove-tag" @click="removeTag(index)">&times;</button>
</div>
</div>
<InputText
v-model="newTag"
@keyup.enter="addTag"
placeholder="Press Enter to add a tag"
/>
</FormField>

<!-- Buttons -->
<Divider />
<div class="form-buttons">
<Button
type="button"
label="Upload"
icon="pi pi-upload"
class="p-button-primary"
@click="uploadFile"
/>
<Button type="button" label="Close" icon="pi pi-times" class="p-button-secondary" @click="closePopup" />
</div>
</Form>
</div>
<Toast />
</div>
</template>

<script>
import { Form, FormField } from '@primevue/forms';
import { InputText, Button, Divider } from 'primevue';
import Toast from 'primevue/toast';
import { useToast } from 'primevue/usetoast';
import {hashPassword} from "@/utils/password.ts";
import {userStore} from "@/user";

export default {
components: { Form, FormField, InputText, Button, Divider, Toast },
data() {
return {
showPopup: false,
selectedFile: null,
password: '',
tags: [],
newTag: '',
toast: useToast(),
};
},
methods: {
handleFileSelection(event) {
this.selectedFile = event.target.files[0];
},
addTag() {
if (this.newTag.trim()) {
this.tags.push(this.newTag.trim());
this.newTag = '';
}
},
removeTag(index) {
this.tags.splice(index, 1);
},
async uploadFile() {
if (!this.selectedFile) {
this.toast.add({ severity: 'warn', summary: 'No File Selected', detail: 'Please select a file to upload.', life: 3000 });
return;
}

try {
let fileData = this.selectedFile;
let fileName = this.selectedFile.name;
let passwordSalt = null;
let passwordHash = null;
// Encrypt the file if password is provided
if (this.password) {
passwordSalt = Array.prototype.map.call(crypto.getRandomValues(new Uint8Array(16)), x=>(('00'+x.toString(16)).slice(-2))).join('');
passwordHash = hashPassword(this.password, passwordSalt);
fileData = await this.encryptFile(this.selectedFile, passwordHash);
}

// Upload file
console.log('Uploading file:', fileData);
console.log('Tags:', this.tags);
const fileID = Array.prototype.map.call(crypto.getRandomValues(new Uint8Array(16)), x=>(('00'+x.toString(16)).slice(-2))).join('');
let user = userStore().getUser;
console.log(user);
const uid = user.id;
let response = await fetch('http://localhost:8080/files', {
method: "POST",
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"data": fileData,
"file_name": fileName,
"has_access": [],
"id": fileID,
"tags": this.tags,
"user_id": uid,
"password_salt": passwordSalt,
"passwod_hash": passwordHash
})
});
if (!(await response).ok) {
this.toast.add({ severity: 'error', summary: 'Error', detail: 'Failed to upload file.', life: 3000 });
} else {
this.toast.add({ severity: 'success', summary: 'Success', detail: 'File uploaded successfully!', life: 3000 });
}

// set user info about file
user.ownedFiles.push(fileID);
userStore().setUser(user);
response = await fetch('http://localhost:2024/accounts/'+uid, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: user.email,
passwordHash: user.passwordHash,
passwordSalt: user.passwordSalt,
sharedFiles: user.sharedFiles,
ownedFiles: user.ownedFiles
})
});
if (!(await response).ok) {
this.toast.add({ severity: 'error', summary: 'Error', detail: 'Failed to update user.', life: 3000 });
console.log("Update failed: " + await response.text());
} else {
console.log("User updated successfully");
}
// Reset the form
this.resetForm();
} catch (error) {
console.error('Error uploading file:', error);
}
},
async encryptFile(file, passwordHash) {
const formData = new FormData();
formData.append('file',file);
formData.append('password-hash',passwordHash);
let response = await fetch('http://localhost:7780/encrypt', {
method: 'POST',
headers: {
accept: 'application/octet-stream',
},
body: formData,
});
if (!(await response).ok) {
this.toast.add({severity: 'error', summary: 'Error', detail: 'Could not encrypt file.', life: 3000})
}
return response.blob();
},
resetForm() {
this.selectedFile = null;
this.password = '';
this.tags = [];
this.newTag = '';
},
closePopup() {
this.showPopup = false;
},
},
};
</script>

<style scoped>
.popup-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}

.popup-content {
background: #222222;
color: white;
padding: 20px;
border-radius: 8px;
width: 400px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
text-align: center;
}

.file-input {
width: 100%;
margin-top: 8px;
}

.tags-container {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-bottom: 5px;
}

.tag {
background: #e3f2fd;
color: #0d47a1;
padding: 5px 10px;
border-radius: 15px;
display: flex;
align-items: center;
}

.remove-tag {
background: none;
border: none;
margin-left: 5px;
cursor: pointer;
color: #f44336;
}

.form-buttons {
display: flex;
justify-content: space-between;
margin-top: 20px;
}
</style>