Skip to content

Commit 0c2c768

Browse files
committed
Fixes
1 parent aa9993c commit 0c2c768

14 files changed

+97
-133
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.env
2+
13
.idea/
24

35
npm-debug.log

.vscode/launch.json

-18
This file was deleted.

cmd/tornote/main.go

+2-6
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,14 @@ var (
5353
func main() {
5454
// Configuration settings.
5555
v := viper.New()
56-
5756
v.SetDefault("PORT", 8000)
58-
v.SetDefault("DATABASE_URL", "psql://postgres:postgres@localhost/postgres")
57+
v.SetDefault("DATABASE_URL", "postgres://postgres:postgres@localhost/postgres")
5958
v.SetDefault("VERSION", GitCommit)
6059

61-
v.SetConfigName("")
62-
v.SetConfigType("env")
63-
_ = v.ReadInConfig()
64-
6560
v.SetConfigName(".env")
6661
v.SetConfigType("dotenv")
6762
v.AddConfigPath(".")
63+
v.ReadInConfig()
6864
v.AutomaticEnv()
6965

7066
// Server init and run.

db.schema

-4
This file was deleted.

go.mod

-2
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@ module github.com/osminogin/tornote
33
go 1.14
44

55
require (
6-
github.com/go-pg/pg v8.0.7+incompatible // indirect
76
github.com/go-pg/pg/v10 v10.0.0-beta.2
87
github.com/google/uuid v1.1.1
98
github.com/gorilla/mux v1.7.4
10-
github.com/mattn/go-sqlite3 v2.0.3+incompatible
119
github.com/segmentio/encoding v0.1.14 // indirect
1210
github.com/spf13/viper v1.7.0
1311
golang.org/x/sys v0.0.0-20200620081246-981b61492c35 // indirect

go.sum

+25-5
Large diffs are not rendered by default.

handlers.go

+21-49
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,12 @@
1717
package tornote
1818

1919
import (
20-
"crypto/rand"
2120
"encoding/base64"
2221
"fmt"
23-
"github.com/google/uuid"
24-
"log"
2522
"net/http"
2623

24+
"github.com/google/uuid"
2725
"github.com/gorilla/mux"
28-
"github.com/go-pg/pg/v10"
2926
)
3027

3128
// frontPageHandler render home page.
@@ -36,79 +33,54 @@ func frontPageHandler(w http.ResponseWriter, r *http.Request) {
3633
// publicFileHandler get file from bindata or return not found error.
3734
func publicFileHandler(w http.ResponseWriter, r *http.Request) {
3835
uri := r.URL.Path[1:]
39-
log.Print(uri)
4036
http.ServeFile(w, r, uri)
41-
42-
//data, err := Asset()
43-
//if err != nil {
44-
// http.Error(w, err.Error(), http.StatusNotFound)
45-
// return
46-
//}
47-
48-
// Set headers by file extension
49-
//switch filepath.Ext(r.URL.Path[1:]) {
50-
//case ".js":
51-
// w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
52-
//case ".css":
53-
// w.Header().Set("Content-Type", "text/css")
54-
//}
55-
//
56-
//w.Write(data)
5737
}
5838

5939
// readNoteHandler print encrypted data for client-side decrypt and destroy note.
60-
func readNoteHandler(db *pg.DB) http.Handler {
40+
func readNoteHandler(s *server) http.Handler {
6141
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
6242
vars := mux.Vars(r)
63-
64-
// Valid UUID required.
65-
id, err := uuid.Parse(vars["id"])
43+
raw, _ := base64.RawURLEncoding.DecodeString(vars["id"])
44+
id, err := uuid.FromBytes(raw)
6645
if err != nil {
67-
http.Error(w, "", http.StatusBadRequest)
46+
http.NotFound(w, r)
6847
return
6948
}
7049

71-
note := &Note{ID: id}
50+
n := &Note{UUID: id}
7251

73-
// Get encrypted note or return 404
74-
err = db.Select(note)
52+
// Get encrypted n or return 404
53+
err = s.db.Select(n)
7554
if err != nil {
7655
http.NotFound(w, r)
7756
return
7857
}
79-
// Deferred note deletion
58+
// Deferred n deletion
8059
defer func() {
81-
db.Delete(note)
60+
s.db.Delete(n)
8261
}()
8362

84-
// Print encrypted note to user
85-
renderTemplate(w, "note.html", note.Data)
63+
// Print encrypted n to user
64+
renderTemplate(w, "note.html", string(n.Data))
8665
})
8766
}
8867

89-
// saveNoteHandler save secret note to persistent datastore and return note ID.
90-
func saveNoteHandler(db *pg.DB) http.Handler {
68+
// createNoteHandler save secret note to persistent datastore and return note ID.
69+
func createNoteHandler(s *server) http.Handler {
9170
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
92-
encrypted := r.FormValue("body")
93-
secret := make([]byte, 11)
94-
95-
// Generate random data for note id
96-
_, err := rand.Read(secret)
97-
if err != nil {
98-
http.Error(w, err.Error(), http.StatusInternalServerError)
99-
return
71+
n := &Note{
72+
UUID: uuid.New(),
73+
Data: []byte(r.FormValue("body")),
10074
}
10175

102-
// Encode note id with URL safe format
103-
id := base64.RawURLEncoding.EncodeToString(secret)
104-
105-
// Save data to database
106-
_, err = db.Exec("INSERT INTO notes (id, encrypted) VALUES (?, ?)", id, encrypted)
76+
err := s.db.Insert(n)
10777
if err != nil {
10878
http.Error(w, err.Error(), http.StatusBadRequest)
10979
return
11080
}
11181

112-
fmt.Fprint(w, id)
82+
b, _ := n.UUID.MarshalBinary()
83+
marshalled := base64.RawURLEncoding.EncodeToString(b)
84+
fmt.Fprint(w, marshalled)
11385
})
11486
}

note.go

+3-4
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@ package tornote
22

33
import (
44
"fmt"
5-
65
"github.com/google/uuid"
76
)
87

98
type Note struct {
10-
ID uuid.UUID `json:"-" sql:",type:uuid"`
11-
Data []byte `json:"data"`
9+
UUID uuid.UUID `json:"-" pg:",pk,type:uuid"`
10+
Data []byte `json:"data"`
1211
}
1312

1413
type Encrypter interface {
@@ -20,5 +19,5 @@ type Decrypter interface {
2019
}
2120

2221
func (u *Note) String() string {
23-
return fmt.Sprintf("%v", u.ID)
22+
return fmt.Sprintf("%v %d bytes", u.UUID, len(u.Data))
2423
}

public/main.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ $(document).ready(function() {
66
$("#note").submit(function(event) {
77
var form = $(this);
88
var text = form.find("textarea").val();
9-
var secret = sjcl.codec.base64url.fromBits(sjcl.random.randomWords(3));
9+
var secret = sjcl.codec.base64url.fromBits(sjcl.random.randomWords(5));
1010
var encrypted = sjcl.encrypt(secret, text);
1111

1212
$.ajax({

server.go

+8-34
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,12 @@ import (
2020
"fmt"
2121
"log"
2222
"net/http"
23-
"html/template"
24-
"strings"
2523

26-
"github.com/gorilla/mux"
2724
"github.com/go-pg/pg/v10"
2825
"github.com/go-pg/pg/v10/orm"
29-
_ "github.com/mattn/go-sqlite3"
26+
"github.com/gorilla/mux"
3027
)
3128

32-
// XXX: Move inside server struct.
33-
var Templates map[string]*template.Template
34-
3529
type server struct {
3630
// Listen port
3731
Port uint64
@@ -64,10 +58,10 @@ func (s *server) connectDB() error {
6458
}
6559
s.db = pg.Connect(opt)
6660

67-
// Ping postgres connection
68-
if err = s.db.Ping(nil); err != nil {
69-
return err
70-
}
61+
// XXX: Ping postgres connection
62+
//if err = s.db.Ping(); err != nil {
63+
// return err
64+
//}
7165
return nil
7266
}
7367

@@ -82,36 +76,16 @@ func (s *server) createSchema() error {
8276
return nil
8377
}
8478

85-
// Compiles templates from templates/ dir into global map.
86-
func compileTemplates() (err error) {
87-
if Templates == nil {
88-
Templates = make(map[string]*template.Template)
89-
}
90-
// XXX:
91-
layout := "templates/base.html"
92-
pages := []string{
93-
"templates/index.html",
94-
"templates/note.html",
95-
}
96-
for _, file := range pages {
97-
baseName := strings.TrimLeft(file, "templates/")
98-
Templates[baseName], err = template.New("").ParseFiles(file, layout)
99-
if err != nil {
100-
return err
101-
}
102-
}
103-
return nil
104-
}
105-
10679
// Running daemon process.
10780
func (s *server) Run() error {
10881
r := mux.NewRouter().StrictSlash(true)
10982

11083
// HTTP handlers
11184
r.HandleFunc("/", frontPageHandler).Methods("GET")
85+
//r.PathPrefix("/favicon.ico").HandlerFunc(publicFileHandler).Methods("GET")
11286
r.PathPrefix("/public/").HandlerFunc(publicFileHandler).Methods("GET")
113-
r.Handle("/note", saveNoteHandler(s.db)).Methods("POST")
114-
r.Handle("/{id}", readNoteHandler(s.db)).Methods("GET")
87+
r.Handle("/note", createNoteHandler(s)).Methods("POST")
88+
r.Handle("/{id}", readNoteHandler(s)).Methods("GET")
11589

11690
// Connecting to database
11791
if err := s.connectDB(); err != nil {

utils.go templates.go

+25
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,34 @@ package tornote
1818

1919
import (
2020
"errors"
21+
"html/template"
2122
"net/http"
23+
"strings"
2224
)
2325

26+
var Templates map[string]*template.Template
27+
28+
29+
// Compiles templates from templates/ dir into global map.
30+
func compileTemplates() (err error) {
31+
if Templates == nil {
32+
Templates = make(map[string]*template.Template)
33+
}
34+
// XXX:
35+
layout := "templates/base.html"
36+
pages := []string{
37+
"templates/index.html",
38+
"templates/note.html",
39+
}
40+
for _, file := range pages {
41+
baseName := strings.TrimLeft(file, "templates/")
42+
Templates[baseName], err = template.New("").ParseFiles(file, layout)
43+
if err != nil {
44+
return err
45+
}
46+
}
47+
return nil
48+
}
2449

2550
// Wrapper around template.ExecuteTemplate method.
2651
func renderTemplate(w http.ResponseWriter, name string, data interface{}) error {

templates/base.html

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@
4343
</footer>
4444

4545
<!-- User scripts -->
46-
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
47-
integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs="
46+
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
47+
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
4848
crossorigin="anonymous"></script>
4949
<script src="https://cdnjs.cloudflare.com/ajax/libs/sjcl/1.0.8/sjcl.min.js"
5050
integrity="sha256-nIoG9XIePM1QNttI6KAGLYGNxc4DNinxxmOZW0/Z7uA="

templates/index.html

+4-4
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
</div>
2727
<div class="form-group text-center">
2828
<button type="submit" class="btn btn-lg btn-success">
29-
<span class="glyphicon glyphicon-record small"></span>
29+
<span class="glyphicon glyphicon-ok small"></span>
3030
Create note
3131
</button>
3232
</div>
@@ -44,9 +44,9 @@
4444
<span class="glyphicon glyphicon-fire small"></span>
4545
Read and destroy
4646
</a>
47-
<a href="/" class="btn btn-lg btn-success">
48-
<span class="glyphicon glyphicon-record small"></span>
49-
Create another note
47+
<a href="/" class="btn btn-lg btn-default">
48+
<span class="glyphicon glyphicon-share-alt small"></span>
49+
Another note
5050
</a>
5151
</div>
5252
</div>

templates/note.html

+4-4
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@
44
<div class="form-group">
55
<label for="secret_note">
66
This note permanently deleted after reading
7-
<span class="glyphicon glyphicon-fire"></span>:
7+
<span class="glyphicon glyphicon-fire text-danger"></span>:
88
</label>
99
<pre id="secret_note" class="hidden">{{.}}</pre>
1010
</div>
1111
<div class="form-group text-center">
12-
<a href="/" class="btn btn-lg btn-success">
13-
<span class="glyphicon glyphicon-record small"></span>
14-
Create another note
12+
<a href="/" class="btn btn-lg btn-default">
13+
<span class="glyphicon glyphicon-share-alt small"></span>
14+
Another note
1515
</a>
1616
</div>
1717
{{ end }}

0 commit comments

Comments
 (0)