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

Added encryption/decryption

Former-commit-id: 4cd1a24aec45fbfeff04fab18abde8e2f9f01b16 [formerly f10b9db62ba2289af4b48b2086258b7995f16caf] [formerly d7020bfd45870f48485982fc05e671df8ffc9307 [formerly e97bfb05a9]]
Former-commit-id: f6cdb6634f8329f8d87634a86d2ff8af1f5d4c3c [formerly 6ddc94157b82f131bcfd890ab27e8021931b65cd]
Former-commit-id: 2287c335a383ed5c85b97b76459fd49e62a65f8c
This commit is contained in:
Zack Scholl 2016-03-14 09:42:19 -04:00
parent 8645d3a3ac
commit b99cb7ce70
6 changed files with 307 additions and 54 deletions

9
db.go
View File

@ -39,6 +39,7 @@ type WikiData struct {
CurrentText string
Diffs []string
Timestamps []string
Encrypted bool
}
func hasPassword(title string) (bool, error) {
@ -77,14 +78,15 @@ func hasPassword(title string) (bool, error) {
return hasPassword, nil
}
func getCurrentText(title string, version int) (string, []versionsInfo, bool, time.Duration) {
func getCurrentText(title string, version int) (string, []versionsInfo, bool, time.Duration, bool) {
title = strings.ToLower(title)
var vi []versionsInfo
totalTime := time.Now().Sub(time.Now())
isCurrent := true
currentText := ""
encrypted := false
if !open {
return currentText, vi, isCurrent, totalTime
return currentText, vi, isCurrent, totalTime, encrypted
}
err := db.View(func(tx *bolt.Tx) error {
var err error
@ -103,6 +105,7 @@ func getCurrentText(title string, version int) (string, []versionsInfo, bool, ti
return err
}
currentText = p.CurrentText
encrypted = p.Encrypted
if version > -1 && version < len(p.Diffs) {
// get that version of text instead
currentText = rebuildTextsToDiffN(p, version)
@ -115,7 +118,7 @@ func getCurrentText(title string, version int) (string, []versionsInfo, bool, ti
if err != nil {
fmt.Printf("Could not get WikiData: %s", err)
}
return currentText, vi, isCurrent, totalTime
return currentText, vi, isCurrent, totalTime, encrypted
}
func (p *WikiData) load(title string) error {

73
encryption.go Executable file
View File

@ -0,0 +1,73 @@
package main
import (
"bytes"
"errors"
"io/ioutil"
"log"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
)
var encryptionType string
func init() {
encryptionType = "PGP SIGNATURE"
}
func encryptString(encryptionText string, encryptionPassphraseString string) string {
encryptionPassphrase := []byte(encryptionPassphraseString)
encbuf := bytes.NewBuffer(nil)
w, err := armor.Encode(encbuf, encryptionType, nil)
if err != nil {
log.Fatal(err)
}
plaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)
if err != nil {
log.Fatal(err)
}
message := []byte(encryptionText)
_, err = plaintext.Write(message)
plaintext.Close()
w.Close()
return encbuf.String()
}
func decryptString(decryptionString string, encryptionPassphraseString string) (string, error) {
encryptionPassphrase := []byte(encryptionPassphraseString)
decbuf := bytes.NewBuffer([]byte(decryptionString))
result, err := armor.Decode(decbuf)
if err != nil {
return "", err
}
alreadyPrompted := false
md, err := openpgp.ReadMessage(result.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if alreadyPrompted {
return nil, errors.New("Could not decrypt using passphrase")
} else {
alreadyPrompted = true
}
return encryptionPassphrase, nil
}, nil)
if err != nil {
return "", err
}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return "", err
}
return string(bytes), nil
}
// func main() {
// test := encryptString("This is some string", "golang")
// fmt.Println(test)
// testD := decryptString(test, "golang")
// fmt.Println(testD)
//
// }

View File

@ -90,7 +90,7 @@ Options:`)
// Default page
aboutFile, _ := ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "templates/aboutpage.md"))
p := WikiData{"about", "", []string{}, []string{}}
p := WikiData{"about", "", []string{}, []string{}, false}
p.save(string(aboutFile))
// var q WikiData
@ -103,6 +103,7 @@ Options:`)
r.HEAD("/", func(c *gin.Context) { c.Status(200) })
r.GET("/:title", editNote)
r.GET("/:title/*option", everythingElse)
r.POST("/:title/*option", encryptionRoute)
r.DELETE("/listitem", deleteListItem)
r.DELETE("/deletepage", deletePage)
if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" {

116
routes.go
View File

@ -18,6 +18,74 @@ import (
"github.com/russross/blackfriday"
)
type EncryptionPost struct {
Text string `form:"text" json:"text" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func encryptionRoute(c *gin.Context) {
title := c.Param("title")
option := c.Param("option")
fmt.Println(option, title)
var jsonLoad EncryptionPost
if option == "/decrypt" {
fmt.Println("Decrypting...")
if c.BindJSON(&jsonLoad) == nil {
var err error
currentText, _, _, _, encrypted := getCurrentText(title, -1)
fmt.Println(currentText, encrypted, jsonLoad.Password)
if encrypted == true {
currentText, err = decryptString(currentText, jsonLoad.Password)
if err != nil {
c.JSON(200, gin.H{
"status": "Inorrect passphrase.",
"title": title,
"option": option,
"success": false,
})
} else {
p := WikiData{strings.ToLower(title), "", []string{}, []string{}, false}
p.save(currentText)
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"option": option,
"success": true,
})
}
}
} else {
c.JSON(200, gin.H{
"status": "Could not bind",
"title": title,
"option": option,
"success": false,
})
}
}
if option == "/encrypt" {
if c.BindJSON(&jsonLoad) == nil {
fmt.Println(jsonLoad)
p := WikiData{strings.ToLower(title), "", []string{}, []string{}, true}
p.save(encryptString(jsonLoad.Text, jsonLoad.Password))
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"option": option,
"success": true,
})
} else {
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"option": option,
"success": false,
})
}
}
}
func newNote(c *gin.Context) {
title := randomAlliterateCombo()
c.Redirect(302, "/"+title)
@ -38,7 +106,10 @@ func editNote(c *gin.Context) {
} else {
version := c.DefaultQuery("version", "-1")
versionNum, _ := strconv.Atoi(version)
currentText, versions, currentVersion, totalTime := getCurrentText(title, versionNum)
currentText, versions, currentVersion, totalTime, encrypted := getCurrentText(title, versionNum)
if encrypted {
c.Redirect(302, "/"+title+"/view")
}
if strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct") {
c.Redirect(302, "/"+title+"/view")
}
@ -81,16 +152,16 @@ func everythingElse(c *gin.Context) {
if strings.ToLower(title) == "about" {
versionNum = -1
}
currentText, versions, _, totalTime := getCurrentText(title, versionNum)
currentText, versions, _, totalTime, encrypted := getCurrentText(title, versionNum)
if (strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct")) && strings.ToLower(title) != "about" {
currentText = strings.Replace(currentText, "self-destruct\n", `> *This page has been deleted, you cannot return after closing.*`+"\n", 1)
currentText = strings.Replace(currentText, "\nself-destruct", "\n"+`> *This page has been deleted, you cannot return after closing.*`, 1)
p := WikiData{strings.ToLower(title), "", []string{}, []string{}}
p := WikiData{strings.ToLower(title), "", []string{}, []string{}, false}
p.save("")
}
renderMarkdown(c, currentText, title, versions, "", totalTime)
renderMarkdown(c, currentText, title, versions, "", totalTime, encrypted)
} else if title == "ls" && option == "/"+RuntimeArgs.AdminKey && len(RuntimeArgs.AdminKey) > 1 {
renderMarkdown(c, listEverything(), "ls", nil, RuntimeArgs.AdminKey, time.Now().Sub(time.Now()))
renderMarkdown(c, listEverything(), "ls", nil, RuntimeArgs.AdminKey, time.Now().Sub(time.Now()), false)
} else if option == "/list" {
renderList(c, title)
} else if title == "static" {
@ -109,7 +180,7 @@ func serveStaticFile(c *gin.Context, option string) {
}
}
func renderMarkdown(c *gin.Context, currentText string, title string, versions []versionsInfo, AdminKey string, totalTime time.Duration) {
func renderMarkdown(c *gin.Context, currentText string, title string, versions []versionsInfo, AdminKey string, totalTime time.Duration, encrypted bool) {
r, _ := regexp.Compile("\\[\\[(.*?)\\]\\]")
for _, s := range r.FindAllString(currentText, -1) {
currentText = strings.Replace(currentText, s, "["+s[2:len(s)-2]+"](/"+s[2:len(s)-2]+"/view)", 1)
@ -139,24 +210,16 @@ func renderMarkdown(c *gin.Context, currentText string, title string, versions [
html2 = strings.Replace(html2, "&amp;#93;", "&#93;", -1)
html2 = strings.Replace(html2, "&amp35;", "&#35;", -1)
if AdminKey == "" {
c.HTML(http.StatusOK, "view.tmpl", gin.H{
"Title": title,
"WikiName": RuntimeArgs.WikiName,
"Body": template.HTML([]byte(html2)),
"TotalTime": totalTime.String(),
"Versions": versions,
})
} else {
c.HTML(http.StatusOK, "view.tmpl", gin.H{
"Title": title,
"WikiName": RuntimeArgs.WikiName,
"Body": template.HTML([]byte(html2)),
"Versions": versions,
"TotalTime": totalTime.String(),
"AdminKey": AdminKey,
})
}
c.HTML(http.StatusOK, "view.tmpl", gin.H{
"Title": title,
"WikiName": RuntimeArgs.WikiName,
"Body": template.HTML([]byte(html2)),
"Versions": versions,
"TotalTime": totalTime.String(),
"AdminKey": AdminKey,
"Encrypted": encrypted,
})
}
func reorderList(text string) ([]template.HTML, []string) {
@ -214,6 +277,9 @@ func renderList(c *gin.Context, title string) {
if strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct") {
c.Redirect(302, "/"+title+"/view")
}
if p.Encrypted {
c.Redirect(302, "/"+title+"/view")
}
pClean := bluemonday.UGCPolicy()
pClean.AllowElements("img")
@ -277,7 +343,7 @@ func deletePage(c *gin.Context) {
fmt.Println(deleteName)
// if adminKey == RuntimeArgs.AdminKey || true == true {
if strings.ToLower(deleteName) != "about" {
p := WikiData{strings.ToLower(deleteName), "", []string{}, []string{}}
p := WikiData{strings.ToLower(deleteName), "", []string{}, []string{}, false}
p.save("")
}
// // remove from program data

View File

@ -9,7 +9,8 @@
<script src="/static/js/jquery.autogrowtextarea.min.js"></script>
{{if .NoEdit}} {{else}} <script src="/static/js/websockets.js"></script> {{end}}
{{if .NoEdit}} {{else}}
<script src="/static/js/websockets.js"></script> {{end}}
<script>
external_ip = '{{ .ExternalIP }}'
@ -41,13 +42,11 @@
margin: 0 auto;
}
@media (min-width: 1200px) {
.container{
.container {
max-width: 800px;
}
}
}
</style>
<script src="/static/js/sweetalert-dev.js"></script>
<link rel="stylesheet" href="/static/css/sweetalert.css">
@ -74,7 +73,7 @@
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" class="active"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit <span class="caret"></span></a>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" class="active"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit <span class="caret"></span></a>
<ul class="dropdown-menu">
<li class="dropdown-header">Time edited: {{ .TotalTime }}</li>
<li role="separator" class="divider"></li>
@ -85,8 +84,9 @@
{{ end }}
<li><a href="/{{ .Title }}">Current</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Options</li>
<li><a href="#" id="{{ .Title }}" class="deleteable">Erase</a></li>
<li class="dropdown-header">Options</li>
<li><a href="#" class="postencrypt">Encrypt</a></li>
<li><a href="#" id="{{ .Title }}" class="deleteable">Erase</a></li>
</ul>
</li>
<li><a href="/{{ .Title }}/view"><span class="glyphicon glyphicon-sunglasses" aria-hidden="true"></span> View</a></li>
@ -111,33 +111,94 @@
$("#emit_data").autoGrow();
});
$(document).keydown(function(e){
if( e.which === 90 && e.ctrlKey && e.shiftKey ){
console.log('control + shift + z');
window.location = "/{{ .Title }}/view";
$(document).keydown(function(e) {
if (e.which === 90 && e.ctrlKey && e.shiftKey) {
console.log('control + shift + z');
window.location = "/{{ .Title }}/view";
}
});
$(document).keydown(function(e){
if( e.which === 76 && e.ctrlKey && e.shiftKey ){
console.log('control + shift + l');
window.location = "/{{ .Title }}/list";
}
$(document).keydown(function(e) {
if (e.which === 76 && e.ctrlKey && e.shiftKey) {
console.log('control + shift + l');
window.location = "/{{ .Title }}/list";
}
});
$('.postencrypt').click(function(event) {
var pass1 = "";
var pass2 = "";
event.preventDefault();
swal({
title: "Encryption",
text: "Enter your passphrase:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
pass1 = inputValue;
swal({
title: "Encryption",
text: "Enter your passphrase again:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
pass2 = inputValue
if (pass1 == pass2) {
swal("Encryption", "Passwords match!", "success");
$.ajax({
type: "POST",
//the url where you want to sent the userName and password to
url: '/{{ .Title }}/encrypt',
dataType: 'json',
data: JSON.stringify({
text: $('#emit_data').val(),
password: pass1
}),
success: function (data) {
if (data['success'] == true) {
swal("Encryption", "Encrypted!", "success");
window.location.href = '/{{ .Title }}/view';
} else {
swal("Encryption", "Something went wrong.", "error");
}
}
});
} else {
swal("Encryption", "Passwords do not match.", "error");
}
});
});
});
$('.deleteable').click(function(event) {
event.preventDefault();
var deleteName = $(this).attr('id')
var href = $(this).attr('href')
swal({
title: "Are you sure?",
text: "You will not be able to recover /{{ .Title }}!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
title: "Are you sure?",
text: "You will not be able to recover /{{ .Title }}!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function() {
$.ajax({
url: "/deletepage" + '?' + $.param({
@ -147,7 +208,9 @@
type: 'DELETE',
success: function() {
swal("Deleted!", "/{{ .Title }} has been deleted.", "success");
setTimeout(function(){ window.location.reload(true); }, 1000);
setTimeout(function() {
window.location.reload(true);
}, 1000);
}
});

View File

@ -15,6 +15,8 @@ a.deleteable {
cursor: pointer;
}
</style>
<script src="/static/js/sweetalert-dev.js"></script>
<link rel="stylesheet" href="/static/css/sweetalert.css">
</head>
<body>
@ -44,6 +46,10 @@ a.deleteable {
<li><a href="/{{ $.Title }}/view?version={{ .VersionNum }}">{{ .VersionDate }}</a></li>
{{ end }}
<li><a href="/{{ .Title }}/view">Current</a></li>
{{ if .Encrypted }}
<li class="dropdown-header">Options</li>
<li><a href="#" class="postdecrypt">Decrypt</a></li>
{{ end }}
</ul>
</li>
<li><a href="/{{ .Title }}/list"><span class="glyphicon glyphicon-align-left" aria-hidden="true"></span> List</a></li>
@ -71,6 +77,46 @@ $( document ).ready(function() {
katex.render(el.getAttribute("data-expr"), el, { displayMode: true });
});
$('.postdecrypt').click(function(event) {
var pass1 = "";
event.preventDefault();
swal({
title: "Encryption",
text: "Enter your passphrase:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
pass1 = inputValue;
$.ajax({
type: "POST",
//the url where you want to sent the userName and password to
url: '/{{ .Title }}/decrypt',
dataType: 'json',
data: JSON.stringify({
text: " ",
password: pass1
}),
success: function (data) {
if (data['success'] == true) {
swal("Decryption", "Decrypted!", "success");
window.location.href = '/{{ .Title }}/view';
} else {
swal("Decryption", data['status'], "error");
}
}
});
});
});
});
$(document).keydown(function(e){
@ -88,6 +134,7 @@ $(document).keydown(function(e){
}
});
{{ if .AdminKey }}
$('.deleteable').click(function(event) {
event.preventDefault();