Skip to content

Commit

Permalink
md5 hash used as authentication method
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilkabir9 committed Dec 25, 2017
1 parent 3ab55ba commit 26f1b58
Show file tree
Hide file tree
Showing 7 changed files with 335 additions and 246 deletions.
414 changes: 213 additions & 201 deletions .idea/workspace.xml

Large diffs are not rendered by default.

99 changes: 73 additions & 26 deletions LDrop.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package main

import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/dustin/go-humanize"
_ "github.com/kamilkabir9/LDrop/statik" // TODO: Replace with the absolute import path
_ "github.com/kamilkabir9/LDrop/statik" // NOTE: Replace with the absolute import path
"github.com/mdp/qrterminal"
"github.com/rakyll/statik/fs"
"github.com/skratchdot/open-golang/open"
Expand All @@ -22,6 +21,8 @@ import (
"strings"
"sync"
"time"
"crypto/md5"
"encoding/hex"
)

const (
Expand Down Expand Up @@ -146,19 +147,12 @@ var ignoreHiddenFilesFlag bool
var verboseFlag bool
var err error
var secretFlag string

var secretFlagMD5 string
func checkSecret(secretEncoded string) bool {
fmt.Println("got:", secretEncoded)
secretByte, err := base64.URLEncoding.DecodeString(secretEncoded)
if err != nil {
log.Println(err)
}
secretRecvd := string(secretByte)
if secretRecvd == secretFlag {
fmt.Printf("Passed %v==%v", secretRecvd, secretFlag)
if secretEncoded== secretFlagMD5 {
return true
}
fmt.Printf("Failed %v=!%v !!!!!!", secretRecvd, secretFlag)
verbose(fmt.Sprintf("Secret Failed %v=!%v !!!!!!", secretEncoded, secretFlagMD5))
return false
}
func main() {
Expand All @@ -180,6 +174,9 @@ func main() {
verbose = func(s string) {
}
}
hasher := md5.New()
hasher.Write([]byte(secretFlag))
secretFlagMD5=hex.EncodeToString(hasher.Sum(nil))
uploadFolder, err = filepath.Abs(uploadFolder)
if err != nil {
log.Panicln(err)
Expand All @@ -190,11 +187,11 @@ func main() {
}
http.HandleFunc("/viewFile/", viewFileHandler)
http.Handle("/", http.FileServer(statikFS))
http.HandleFunc("/upload", upLoadHandler)
http.HandleFunc("/getLastFile", getLastFileHandler)
http.HandleFunc("/getAllFiles", getAllFilesHandler)
http.HandleFunc("/getFile/", getFileHandler)
http.HandleFunc("/downLoadFile/", serveThisFileHandler)
http.HandleFunc("/upload", upLoadHandler) //api
http.HandleFunc("/getLastFile", getLastFileHandler) //api
http.HandleFunc("/getAllFiles", getAllFilesHandler) //api
http.HandleFunc("/getFile/", getFileHandler) //api
http.HandleFunc("/downLoadFile/", serveThisFileHandler) //api

//Adapted from https://stackoverflow.com/questions/43424787/how-to-use-next-available-port-in-http-listenandserve
listener, err := net.Listen("tcp", ":0")
Expand Down Expand Up @@ -246,14 +243,18 @@ func UploadStatusJson(status string, desc string) string {
func upLoadHandler(w http.ResponseWriter, r *http.Request) {

verbose(fmt.Sprintln("Downloading File....."))

file, fileHeader, err := r.FormFile("fileUpload")
if err != nil {
log.Println(err)
result := UploadStatusJson(FailedStatus, fmt.Sprint(err))
fmt.Fprint(w, result)
return
}
if !checkSecret(r.Header.Get("secret")) {
result := UploadStatusJson(FailedStatus, fmt.Sprintf("Error Uploading file %v. Secret mismatch !!!", fileHeader.Filename))
fmt.Fprint(w, result)
return
}

if _, err := os.Stat(uploadFolder); os.IsNotExist(err) {
os.Mkdir(uploadFolder, 0777)
Expand Down Expand Up @@ -309,6 +310,12 @@ func getUniqFileName(filename string) string {
}

func getLastFileHandler(w http.ResponseWriter, r *http.Request) {
if !checkSecret(r.Header.Get("secret")) {
verbose("Got wrong secret from client")
result := UploadStatusJson(FailedStatus, fmt.Sprintf("Error getting last file. Secret mismatch !!!"))
fmt.Fprint(w, result)
return
}
fileList := getAllFiles()
lastFile := fileList[0]
for _, file := range fileList {
Expand Down Expand Up @@ -384,8 +391,10 @@ func getAllFilesConcurrent(Dir string, fileNamesWithTime *[]fileInfo) {

func getAllFilesHandler(w http.ResponseWriter, r *http.Request) {
verbose(fmt.Sprint("getting All files.."))
if !checkSecret(r.Header.Get("secret")){
if !checkSecret(r.Header.Get("secret")) {
verbose("Got wrong secret from client")
result := UploadStatusJson(FailedStatus, "secret mismatch")
fmt.Fprintln(w, result)
return
}
var fileNamesWithTime = getAllFiles()
Expand All @@ -402,25 +411,63 @@ func getAllFilesHandler(w http.ResponseWriter, r *http.Request) {
}

func getFileHandler(w http.ResponseWriter, r *http.Request) {
fileName := r.URL.Path
fileName = strings.Replace(fileName, "/getFile/", "", -1)
fileName, err := url.QueryUnescape(fileName)
u, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
panic(err)
}
fileName :=u["fileName"][0]
if fileName==""{
verbose("Error getting file name !!!")
fmt.Fprint(w, fmt.Sprintf("Error getting file name from URL !!!"))
return
}
fileName, err = url.QueryUnescape(fileName)
if err != nil {
log.Println(err)
}
log.Println(fileName)
secretRcvd :=u["secret"][0]
if secretRcvd==""{
verbose("Error getting file name !!!")
fmt.Fprint(w, fmt.Sprintf("Error getting secret URL !!!"))
return
}
if !checkSecret(secretRcvd) {
verbose("Got wrong secret from client")
fmt.Fprint(w, fmt.Sprintf("Error getting file:%v. Secret mismatch !!!", fileName))
return
}
verbose(fmt.Sprintln("getting File : ", fileName))
http.ServeFile(w, r, path.Join(uploadFolder, fileName))
//http.ServeContent(w, r, path.Join(uploadFolder, fileName))

}
func serveThisFileHandler(w http.ResponseWriter, r *http.Request) {
fileName := r.URL.Path
fileName = strings.Replace(fileName, "/downLoadFile/", "", -1)
fileName, err := url.QueryUnescape(fileName)
u, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
panic(err)
}
fileName :=u["fileName"][0]
if fileName==""{
verbose("Error getting file name !!!")
fmt.Fprint(w, fmt.Sprintf("Error getting file name from URL !!!"))
return
}
fileName, err = url.QueryUnescape(fileName)
if err != nil {
log.Println(err)
}
secretRcvd :=u["secret"][0]
if secretRcvd==""{
verbose("Error getting file name !!!")
fmt.Fprint(w, fmt.Sprintf("Error getting secret URL !!!"))
return
}
if !checkSecret(secretRcvd) {
verbose("Got wrong secret from client")
result := UploadStatusJson(FailedStatus, fmt.Sprintf("Error getting file:%v. Secret mismatch !!!", fileName))
fmt.Fprint(w, result)
return
}
verbose(fmt.Sprintln("serving File : ", fileName))
//Adapted from https://stackoverflow.com/questions/31638447/how-to-server-a-file-from-a-handler-in-golang
w.Header().Set("Content-Description", "File Transfer")
Expand Down
2 changes: 1 addition & 1 deletion statik/statik.go

Large diffs are not rendered by default.

Binary file added website/favicon.ico
Binary file not shown.
40 changes: 25 additions & 15 deletions website/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<script src="/js.cookie.js"></script>
<script src="/md5.min.js"></script>
<link rel="stylesheet" href="/bootstrap.min.css" >
<body onload="listFiles()">
<h1>LocalDrop</h1>
Expand Down Expand Up @@ -44,14 +45,15 @@ <h1>LocalDrop</h1>
<td>{{this.ModTime}}</td>
<td>{{this.Size}}</td>
<td><a class="btn btn-outline-success" href="/viewFile/{{this.Name}}" role="button">View</a></td>
<td><a class="btn btn-outline-info" href="/downLoadFile/{{this.Name}}" target="_blank" role="button" download >Download</a></td>
<td><a class="btn btn-outline-info" href="/downLoadFile/?secret={{../Secret}}&fileName={{this.Name}}" target="_blank" role="button" download >Download</a></td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</script>
<script>

var getSecret=function(){
var secret=Cookies.get('secret');
if (secret===undefined){
Expand All @@ -65,8 +67,9 @@ <h1>LocalDrop</h1>
}
}
secret=Cookies.get('secret');
return secret;
return md5(secret);
};

var upload = function () {
var uploadForm=document.forms.namedItem("uploadForm");
var formData = new FormData(uploadForm);
Expand All @@ -87,7 +90,7 @@ <h1>LocalDrop</h1>
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader("secret", "007");
xhr.setRequestHeader("secret", secret);
xhr.send(formData);
};

Expand All @@ -96,30 +99,37 @@ <h1>LocalDrop</h1>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response=JSON.parse(this.responseText);
if (response.Status !=='Ok'){
var response = JSON.parse(this.responseText);
if (response.Status === 'Err' && response.Description === "secret mismatch"){
console.error(response.Status);
var secretPrompt = prompt("Secret mismatch. Please enter secret:", "");
if (secretPrompt == null || secretPrompt === "") {
console.log("plz enter secret !?");
} else {
Cookies.set('secret', secretPrompt);
console.log("set secret as " + secretPrompt);
}
return;
}
var FileTable=JSON.parse(response.Description);

var FileTable = JSON.parse(response.Description);
console.log(FileTable);
var FileTableNode = document.getElementById("FileTable");
while (FileTableNode.hasChildNodes()) {
FileTableNode.removeChild(FileTableNode.lastChild);
}
var source = document.getElementById("fileTableTemplate").innerHTML;
var source = document.getElementById("fileTableTemplate").innerHTML;
var template = Handlebars.compile(source);
var context = {FileTable:FileTable};
var html = template(context);
FileTableNode.innerHTML=html;
}
};
var context = {FileTable: FileTable,Secret:getSecret()};
var html = template(context);
FileTableNode.innerHTML = html;

}};
xhr.open('POST', '/getAllFiles', true);
var secret=btoa(getSecret());
xhr.setRequestHeader("secret", secret);
xhr.setRequestHeader("secret", getSecret());
xhr.send();
};

listFiles();

</script>
</html>
2 changes: 2 additions & 0 deletions website/md5.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 21 additions & 3 deletions website/viewFile.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<script src="/js.cookie.js"></script>
<script src="/md5.min.js"></script>
<link rel="stylesheet" href="/bootstrap.min.css" >
<style>
.col-10 {
Expand All @@ -30,13 +32,29 @@ <h2 id="fileName">File: </h2>
</body>
<script>
{{/*TODO add xhr.setRequestHeader("secret", "007"); as url param*/}}
var getSecret=function(){
var secret=Cookies.get('secret');
if (secret===undefined){
console.log("secret not Set !!!!");
var secretPrompt = prompt("Please enter secret:", "007Jb");
if (secretPrompt == null || secretPrompt === "") {
console.log("plz enter secret !?");
} else {
Cookies.set('secret',secretPrompt);
console.log("set secret as "+secretPrompt);
}
}
secret=Cookies.get('secret');
return md5(secret);
};
var requestFile=window.location.pathname;
requestFile=requestFile.replace("/viewFile/","");
requestFile=decodeURI(requestFile);
document.getElementById('fileName').innerHTML+=requestFile;
console.log(requestFile);
document.getElementById('iframe').src="/getFile/"+requestFile;
document.getElementById('download').href="/downLoadFile/"+requestFile;
requestFile=requestFile.replace("/viewFile/","");
// title=Main_page&action=raw
document.getElementById('iframe').src="/getFile/?secret="+getSecret()+"&fileName="+requestFile;
document.getElementById('download').href="/downLoadFile/?secret="+getSecret()+"&fileName="+requestFile;

</script>
</html>

0 comments on commit 26f1b58

Please sign in to comment.