Compare commits
31 Commits
482c293dec
...
multiuser
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46da56d9f8 | ||
|
|
16722eb9bf | ||
|
|
0cdc6bec24 | ||
|
|
a6510b34a4 | ||
|
|
c6b79938ea | ||
|
|
fc4c269ddc | ||
|
|
3ef4dfaa48 | ||
|
|
3aab4827fe | ||
|
|
64b7fa4f50 | ||
|
|
f5ace34852 | ||
|
|
22229fc5bc | ||
|
|
ae86204c84 | ||
|
|
4ae49b5db6 | ||
|
|
b1d0bc826f | ||
|
|
7c63223aa0 | ||
|
|
9f99aad680 | ||
|
|
bca1735393 | ||
|
|
bc1095fc61 | ||
|
|
8661c0081d | ||
|
|
300d49874e | ||
|
|
526a1c4faa | ||
|
|
ab43f732fe | ||
|
|
c23c781c63 | ||
|
|
b7bad122e6 | ||
|
|
48051a5874 | ||
|
|
2449e9b96a | ||
|
|
6e69f90b4e | ||
|
|
b79b82798d | ||
|
|
1f82bd4bcb | ||
|
|
25503867f9 | ||
|
|
268b488fea |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,2 +1,4 @@
|
||||
.env
|
||||
test.txt
|
||||
ledger-quicknote
|
||||
.htpasswd
|
||||
data
|
||||
|
||||
94
README.md
Normal file
94
README.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Ledger Quick Note
|
||||
|
||||

|
||||
|
||||
**Add ledger transactions on the fly!**
|
||||
|
||||
## Feature
|
||||
|
||||
### Create Transaction from Template
|
||||
|
||||
Add your transaction template in `tx/` (in Go's template syntax), and create transaction from them in the browser.
|
||||
|
||||
Examples:
|
||||
|
||||
Take some cash
|
||||
```
|
||||
{{ .Date }} * cash
|
||||
expenses:cash ${{ .Amount }}
|
||||
assets:cash
|
||||
|
||||
```
|
||||
|
||||
Cash expenses
|
||||
```
|
||||
{{ .Date }} {{ with .Name }}{{ . }}{{ else }}{{ .Account }}{{ end }}
|
||||
{{ .Account }} ${{ .Amount }}
|
||||
expenses:cash
|
||||
|
||||
```
|
||||
|
||||
Checkout `tx/` folder for more examples.
|
||||
|
||||

|
||||
|
||||
Adjust your transaction
|
||||
|
||||

|
||||
|
||||
Result page
|
||||
|
||||

|
||||
|
||||
### Ledger Scripts
|
||||
|
||||
Run some commonly used ledger commands.
|
||||
|
||||
Define your commands in config.go
|
||||
|
||||
```go
|
||||
var SCRIPTS = map[string][]string{
|
||||
"balance assets": {"b", "assets", "-X", "$"},
|
||||
"register": {"r", "--tail", "10"},
|
||||
"balance this month": {"b", "-b", "this month"},
|
||||
}
|
||||
```
|
||||
|
||||
Rebuild binary everytime you make a change to `config.go`
|
||||
|
||||
Execute them and see the result in the browser.
|
||||
|
||||

|
||||
|
||||
## Install
|
||||
|
||||
Requirements:
|
||||
* go
|
||||
* ledger (Only required when you use scripts)
|
||||
|
||||
Install requirements on Debian / Ubuntu based distro:
|
||||
```
|
||||
sudo apt install golang ledger
|
||||
```
|
||||
|
||||
Install requirements on Arch based distro:
|
||||
```
|
||||
sudo pacman -S golang ledger
|
||||
```
|
||||
|
||||
Clone the repo
|
||||
|
||||
```
|
||||
git clone https://github.com/lancatlin/ledger-quicknote.git
|
||||
```
|
||||
|
||||
```
|
||||
go build
|
||||
```
|
||||
|
||||
```
|
||||
./ledger-quicknote
|
||||
```
|
||||
|
||||
Checkout `deployment/` for Nginx & Systemd example configuration.
|
||||
|
||||
1
archetypes/.ledgerrc
Normal file
1
archetypes/.ledgerrc
Normal file
@@ -0,0 +1 @@
|
||||
--file ledger.txt
|
||||
4
archetypes/default.tpl
Normal file
4
archetypes/default.tpl
Normal file
@@ -0,0 +1,4 @@
|
||||
{{ .Date }} {{ with .Name }}{{ . }}{{ else }}{{ .Destination }}{{ end }}
|
||||
{{ .Destination }} ${{ .Amount }}
|
||||
{{ with .Source }}{{ . }}{{ else }}cash{{ end }}
|
||||
|
||||
13
archetypes/ledger.txt
Normal file
13
archetypes/ledger.txt
Normal file
@@ -0,0 +1,13 @@
|
||||
account assets
|
||||
account liabilities
|
||||
account income
|
||||
account expenses
|
||||
account equity
|
||||
account assets:savings
|
||||
alias savings
|
||||
account assets:checking
|
||||
alias checking
|
||||
account expenses:cash
|
||||
alias cash
|
||||
account expenses:food
|
||||
alias food
|
||||
5
archetypes/queries.txt
Normal file
5
archetypes/queries.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
資產餘額:b assets
|
||||
本月開支:b -b "this month"
|
||||
上月開支:b -b "last month" -e "this month"
|
||||
記錄列表:r
|
||||
過去七天:r -b "last 7 days"
|
||||
129
auth/auth.go
Normal file
129
auth/auth.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/securecookie"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type AuthStore interface {
|
||||
Get(user string) bool
|
||||
Register(user, pass string) error
|
||||
Login(user, pass string) (token string, err error)
|
||||
Verify(token string) (session Session, err error)
|
||||
Remove(user string) error
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
User string
|
||||
Expiry time.Time
|
||||
}
|
||||
|
||||
type Htpasswd struct {
|
||||
accounts map[string]string
|
||||
filePath string
|
||||
cookie *securecookie.SecureCookie
|
||||
}
|
||||
|
||||
func New(path string, hashKey []byte) (AuthStore, error) {
|
||||
s := Htpasswd{
|
||||
filePath: path,
|
||||
cookie: securecookie.New(hashKey, nil),
|
||||
}
|
||||
err := s.read()
|
||||
return s, err
|
||||
}
|
||||
|
||||
func (s Htpasswd) Get(user string) bool {
|
||||
_, ok := s.accounts[user]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s Htpasswd) Register(user, pass string) (err error) {
|
||||
if _, ok := s.accounts[user]; ok {
|
||||
return errors.New("user already exists")
|
||||
}
|
||||
s.accounts[user], err = hash(pass)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return s.write()
|
||||
}
|
||||
|
||||
func (s Htpasswd) Login(user, pass string) (token string, err error) {
|
||||
hashed, ok := s.accounts[user]
|
||||
if !ok {
|
||||
return "", errors.New("user not found")
|
||||
}
|
||||
err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(pass))
|
||||
if err != nil {
|
||||
return "", errors.New("wrong password")
|
||||
}
|
||||
session := Session{
|
||||
User: user,
|
||||
Expiry: time.Now().AddDate(0, 0, 7),
|
||||
}
|
||||
token, err = s.cookie.Encode("session", session)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s Htpasswd) Verify(token string) (session Session, err error) {
|
||||
err = s.cookie.Decode("session", token, &session)
|
||||
return
|
||||
}
|
||||
|
||||
func (s Htpasswd) Remove(user string) (err error) {
|
||||
delete(s.accounts, user)
|
||||
return s.write()
|
||||
}
|
||||
|
||||
func (s *Htpasswd) read() (err error) {
|
||||
file, err := os.OpenFile(s.filePath, os.O_RDONLY|os.O_CREATE, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileScanner := bufio.NewScanner(file)
|
||||
fileScanner.Split(bufio.ScanLines)
|
||||
|
||||
s.accounts = make(map[string]string)
|
||||
for fileScanner.Scan() {
|
||||
arr := strings.SplitN(fileScanner.Text(), ":", 2)
|
||||
if len(arr) < 2 {
|
||||
return fmt.Errorf("invalid data %s", arr)
|
||||
}
|
||||
s.accounts[arr[0]] = arr[1]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Htpasswd) write() (err error) {
|
||||
file, err := os.OpenFile(s.filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open htpasswd file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
for u, p := range s.accounts {
|
||||
_, err = fmt.Fprintf(file, "%s:%s\n", u, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hash(pass string) (string, error) {
|
||||
output, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
|
||||
return string(output), err
|
||||
}
|
||||
77
auth/auth_test.go
Normal file
77
auth/auth_test.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/securecookie"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
user string
|
||||
pass string
|
||||
hashed string
|
||||
}
|
||||
|
||||
func TestHtpasswdSuccess(t *testing.T) {
|
||||
hashKey := securecookie.GenerateRandomKey(32)
|
||||
path := "/tmp/.htpasswd"
|
||||
user1 := User{
|
||||
user: "user",
|
||||
pass: "password",
|
||||
hashed: "$2a$14$SQSscaF4fVO3e5dp2/.VPuVQDPKqxSagLQnN6OncTRtoQw0ie9ByK",
|
||||
}
|
||||
err := ioutil.WriteFile(path,
|
||||
[]byte(fmt.Sprintf("%s:%s", user1.user, user1.hashed)), 0640)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := New(path, hashKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := store.Login(user1.user, user1.pass)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
session, err := store.Verify(token)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if session.User != user1.user {
|
||||
t.Fatalf("expected %s, got %s", user1.user, session.User)
|
||||
}
|
||||
|
||||
user2 := User{
|
||||
user: "foo",
|
||||
pass: "bar",
|
||||
}
|
||||
err = store.Register(user2.user, user2.pass)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
data, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
for _, u := range []User{user1, user2} {
|
||||
if !strings.Contains(string(data), u.user) {
|
||||
t.Errorf("%s not found in htpasswd file: %s", u.user, string(data))
|
||||
}
|
||||
}
|
||||
err = store.Remove(user1.user)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
data, err = ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if strings.Contains(string(data), user1.user) {
|
||||
t.Errorf("%s is found in htpasswd file but should be removed: %s", user1.user, string(data))
|
||||
}
|
||||
}
|
||||
12
config.go
Normal file
12
config.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package main
|
||||
|
||||
var SCRIPTS = map[string]string{
|
||||
"balance assets": "b assets -X $",
|
||||
"register": "r --tail 10",
|
||||
"balance this month": "b -b \"this month\"",
|
||||
}
|
||||
|
||||
const QUERIES_FILE = "queries.txt"
|
||||
const HTPASSWD_FILE = ".htpasswd"
|
||||
const DEFAULT_JOURNAL = "ledger.txt"
|
||||
const ARCHETYPES_DIR = "archetypes"
|
||||
12
deployment/nginx.conf
Normal file
12
deployment/nginx.conf
Normal file
@@ -0,0 +1,12 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name ledger.example.com;
|
||||
|
||||
location / {
|
||||
auth_basic "private zone";
|
||||
auth_basic_user_file /etc/nginx/myusers;
|
||||
|
||||
proxy_pass http://127.0.0.1:8000;
|
||||
}
|
||||
}
|
||||
12
deployment/systemd.service
Normal file
12
deployment/systemd.service
Normal file
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Ledger Quick Note
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory=/path/to/ledger-quicknote
|
||||
ExecStart=/path/to/ledger-quicknote/ledger-quicknote -f /path/to/ledger/journal.txt -w /path/to/ledger
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
28
go.mod
Normal file
28
go.mod
Normal file
@@ -0,0 +1,28 @@
|
||||
module github.com/lancatlin/ledger-quicknote
|
||||
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/multitemplate v0.0.0-20220829131020-8c2a8441bc2b // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/gin-gonic/gin v1.8.1 // indirect
|
||||
github.com/go-playground/locales v0.14.0 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.0 // indirect
|
||||
github.com/go-playground/validator/v10 v10.10.0 // indirect
|
||||
github.com/goccy/go-json v0.9.7 // indirect
|
||||
github.com/gorilla/securecookie v1.1.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/otiai10/copy v1.9.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.7 // indirect
|
||||
golang.org/x/crypto v0.1.0 // indirect
|
||||
golang.org/x/net v0.1.0 // indirect
|
||||
golang.org/x/sys v0.1.0 // indirect
|
||||
golang.org/x/text v0.4.0 // indirect
|
||||
google.golang.org/protobuf v1.28.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
93
go.sum
Normal file
93
go.sum
Normal file
@@ -0,0 +1,93 @@
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gin-contrib/multitemplate v0.0.0-20220829131020-8c2a8441bc2b h1:WMas4AhGwZLRBAYGikjEzx02gk5SbAn3xbbxhnGrgao=
|
||||
github.com/gin-contrib/multitemplate v0.0.0-20220829131020-8c2a8441bc2b/go.mod h1:XLLtIXoP9+9zGcEDc7gAGV3AksGPO+vzv4kXHMJSdU0=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.8.1 h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8=
|
||||
github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
|
||||
github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
|
||||
github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=
|
||||
github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
|
||||
github.com/go-playground/validator/v10 v10.10.0 h1:I7mrTYv78z8k8VXa/qJlOlEXn/nBh+BF8dHX5nt/dr0=
|
||||
github.com/go-playground/validator/v10 v10.10.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos=
|
||||
github.com/goccy/go-json v0.9.7 h1:IcB+Aqpx/iMHu5Yooh7jEzJk1JZ7Pjtmys2ukPr7EeM=
|
||||
github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
||||
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/otiai10/copy v1.9.0 h1:7KFNiCgZ91Ru4qW4CWPf/7jqtxLagGRmIxWldPP9VY4=
|
||||
github.com/otiai10/copy v1.9.0/go.mod h1:hsfX19wcn0UWIHUQ3/4fHuehhk2UyArQ9dVFAn3FczI=
|
||||
github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
|
||||
github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=
|
||||
github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=
|
||||
github.com/otiai10/mint v1.4.0/go.mod h1:gifjb2MYOoULtKLqUAEILUG/9KONW6f7YsJ6vQLTlFI=
|
||||
github.com/pelletier/go-toml/v2 v2.0.1 h1:8e3L2cCQzLFi2CR4g7vGFuFxX7Jl1kKX8gW+iV0GUKU=
|
||||
github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=
|
||||
github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
|
||||
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
|
||||
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
|
||||
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
|
||||
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
|
||||
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
79
main.go
79
main.go
@@ -1,71 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"encoding/base64"
|
||||
"flag"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/securecookie"
|
||||
"github.com/lancatlin/ledger-quicknote/auth"
|
||||
)
|
||||
|
||||
var tpl *template.Template
|
||||
var htmlTpl *template.Template
|
||||
|
||||
const LEDGER_FILE = "test.txt"
|
||||
var DATA_DIR string
|
||||
var HOST string
|
||||
|
||||
type TxData struct {
|
||||
Date string
|
||||
Amount string
|
||||
}
|
||||
var store auth.AuthStore
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&DATA_DIR, "d", "data", "data folder")
|
||||
flag.StringVar(&HOST, "b", "127.0.0.1:8000", "binding address")
|
||||
var hashKeyString string
|
||||
flag.StringVar(&hashKeyString, "s", "", "session secret")
|
||||
flag.Parse()
|
||||
|
||||
var hashKey []byte
|
||||
var err error
|
||||
tpl, err = template.ParseGlob("templates/*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Println(tpl.DefinedTemplates())
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hi")
|
||||
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
tpl.ExecuteTemplate(w, "index.html", tpl)
|
||||
})
|
||||
|
||||
http.HandleFunc("/action", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println(r.Form)
|
||||
err := renderTx(w, r.Form)
|
||||
if hashKeyString == "" {
|
||||
hashKey = securecookie.GenerateRandomKey(32)
|
||||
log.Printf("Generate random session key: %s", base64.StdEncoding.EncodeToString(hashKey))
|
||||
} else {
|
||||
hashKey, err = base64.StdEncoding.DecodeString(hashKeyString)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8000", nil))
|
||||
}
|
||||
|
||||
func renderTx(w io.Writer, params url.Values) (err error) {
|
||||
name := params.Get("action")
|
||||
data := TxData{
|
||||
Date: time.Now().Format("2006/01/02"),
|
||||
Amount: params.Get("amount"),
|
||||
}
|
||||
f, err := os.OpenFile(LEDGER_FILE, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
|
||||
store, err = auth.New(path.Join(DATA_DIR, HTPASSWD_FILE), hashKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if err = tpl.ExecuteTemplate(f, name, data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tpl.ExecuteTemplate(w, name, data); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := router()
|
||||
|
||||
log.Fatal(r.Run(HOST))
|
||||
}
|
||||
|
||||
166
models.go
Normal file
166
models.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
cp "github.com/otiai10/copy"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
IsLogin bool
|
||||
Email string `form:"email" binding:"required"`
|
||||
Password string `form:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func (u *User) Dir() string {
|
||||
dir := path.Join(DATA_DIR, u.Email)
|
||||
return dir
|
||||
}
|
||||
|
||||
func (u *User) Mkdir() error {
|
||||
return cp.Copy(ARCHETYPES_DIR, u.Dir())
|
||||
}
|
||||
|
||||
func (u *User) FilePath(name string) string {
|
||||
return path.Join(u.Dir(), name)
|
||||
}
|
||||
|
||||
func (u *User) File(name string, mode int) (*os.File, error) {
|
||||
return os.OpenFile(u.FilePath(name), mode, 0644)
|
||||
}
|
||||
|
||||
func (u *User) AppendFile(name string) (*os.File, error) {
|
||||
return u.File(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND)
|
||||
}
|
||||
|
||||
func (u *User) ReadFile(name string) (*os.File, error) {
|
||||
return u.File(name, os.O_RDONLY|os.O_CREATE)
|
||||
}
|
||||
|
||||
func (u *User) WriteFile(name string) (*os.File, error) {
|
||||
return u.File(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||
}
|
||||
|
||||
func (u *User) List() ([]string, error) {
|
||||
files, err := os.ReadDir(u.Dir())
|
||||
if err != nil {
|
||||
return []string{}, fmt.Errorf("Failed to open directory: %w", err)
|
||||
}
|
||||
result := make([]string, len(files))
|
||||
for i, v := range files {
|
||||
result[i] = v.Name()
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *User) readAllFile(name string) (data []byte, err error) {
|
||||
f, err := u.ReadFile(name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
data, err = ioutil.ReadAll(f)
|
||||
return
|
||||
}
|
||||
|
||||
func (u *User) appendToFile(tx string) (err error) {
|
||||
f, err := u.AppendFile(DEFAULT_JOURNAL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
buf := strings.NewReader(strings.ReplaceAll(tx, "\r", "")) // Remove CR generated from browser
|
||||
_, err = io.Copy(f, buf)
|
||||
return err
|
||||
}
|
||||
|
||||
func (u *User) overwriteFile(filename string, tx string) (err error) {
|
||||
f, err := u.WriteFile(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
buf := strings.NewReader(strings.ReplaceAll(tx, "\r", "")) // Remove CR generated from browser
|
||||
_, err = io.Copy(f, buf)
|
||||
return err
|
||||
}
|
||||
|
||||
func (u *User) query(query string) (result string, err error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
cmd := exec.Command("ledger")
|
||||
cmd.Dir = u.Dir()
|
||||
cmd.Stdin = strings.NewReader(query)
|
||||
cmd.Stdout = &buf
|
||||
cmd.Stderr = &buf
|
||||
err = cmd.Run()
|
||||
return buf.String(), err
|
||||
}
|
||||
|
||||
func (u *User) queries() (queries [][2]string, err error) {
|
||||
f, err := u.ReadFile(QUERIES_FILE)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to read queries file: %w", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
fileScanner := bufio.NewScanner(f)
|
||||
fileScanner.Split(bufio.ScanLines)
|
||||
|
||||
queries = make([][2]string, 0)
|
||||
for fileScanner.Scan() {
|
||||
arr := strings.SplitN(fileScanner.Text(), ":", 2)
|
||||
if len(arr) < 2 {
|
||||
continue
|
||||
}
|
||||
queries = append(queries, [2]string{arr[0], arr[1]})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (u *User) templates() (templates []string, err error) {
|
||||
files, err := u.List()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, v := range files {
|
||||
if strings.HasSuffix(v, ".tpl") {
|
||||
templates = append(templates, v)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type TxData struct {
|
||||
Action string `form:"action" binding:"required"`
|
||||
Name string `form:"name"`
|
||||
Date string
|
||||
Amount string `form:"amount" binding:"required"`
|
||||
Destination string `form:"dest"`
|
||||
Source string `form:"src"`
|
||||
}
|
||||
|
||||
func (u *User) newTx(data TxData) (result string, err error) {
|
||||
data.Date = time.Now().Format("2006/01/02")
|
||||
var buf bytes.Buffer
|
||||
tpl, err := template.ParseFiles(u.FilePath(data.Action))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = tpl.ExecuteTemplate(&buf, data.Action, data)
|
||||
result = buf.String()
|
||||
return
|
||||
}
|
||||
148
route.go
Normal file
148
route.go
Normal file
@@ -0,0 +1,148 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func router() *gin.Engine {
|
||||
r := gin.Default()
|
||||
r.HTMLRender = loadTemplates("templates")
|
||||
|
||||
r.GET("/", func(c *gin.Context) {
|
||||
c.Redirect(303, "/dashboard")
|
||||
})
|
||||
|
||||
r.GET("/signup", func(c *gin.Context) {
|
||||
HTML(c, 200, "signup.html", nil)
|
||||
})
|
||||
|
||||
r.GET("/signin", func(c *gin.Context) {
|
||||
HTML(c, 200, "signin.html", nil)
|
||||
})
|
||||
|
||||
r.POST("/signup", signup)
|
||||
|
||||
r.POST("/signin", signin)
|
||||
|
||||
authZone := r.Group("", authenticate)
|
||||
|
||||
authZone.GET("/dashboard", func(c *gin.Context) {
|
||||
user := getUser(c)
|
||||
queries, err := user.queries()
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
templates, err := user.templates()
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
HTML(c, 200, "dashboard.html", gin.H{
|
||||
"Queries": queries,
|
||||
"Templates": templates,
|
||||
})
|
||||
})
|
||||
|
||||
authZone.POST("/new", func(c *gin.Context) {
|
||||
var data TxData
|
||||
if err := c.ShouldBind(&data); err != nil {
|
||||
c.AbortWithError(400, err)
|
||||
return
|
||||
}
|
||||
user := getUser(c)
|
||||
tx, err := user.newTx(data)
|
||||
if err != nil {
|
||||
c.AbortWithError(400, err)
|
||||
log.Println(err, c.Request.Form)
|
||||
return
|
||||
}
|
||||
HTML(c, 200, "new.html", gin.H{
|
||||
"Tx": tx,
|
||||
})
|
||||
})
|
||||
authZone.POST("/submit", func(c *gin.Context) {
|
||||
user := getUser(c)
|
||||
tx := c.PostForm("tx")
|
||||
if err := user.appendToFile(tx); err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(303, "/dashboard")
|
||||
})
|
||||
|
||||
authZone.GET("/edit", func(c *gin.Context) {
|
||||
user := getUser(c)
|
||||
filename := c.Query("filename")
|
||||
list, err := user.List()
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
exists := contain(list, filename)
|
||||
var data []byte
|
||||
if exists {
|
||||
data, err = user.readAllFile(filename)
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
}
|
||||
}
|
||||
|
||||
HTML(c, 200, "edit.html", gin.H{
|
||||
"Data": string(data),
|
||||
"FileName": filename,
|
||||
"FileList": list,
|
||||
"Exists": exists,
|
||||
})
|
||||
})
|
||||
|
||||
authZone.POST("/edit", func(c *gin.Context) {
|
||||
user := getUser(c)
|
||||
filename := c.PostForm("filename")
|
||||
data := c.PostForm("data")
|
||||
err := user.overwriteFile(filename, data)
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
HTML(c, 200, "success.html", gin.H{
|
||||
"FileName": filename,
|
||||
"Tx": data,
|
||||
})
|
||||
})
|
||||
|
||||
authZone.GET("/download", func(c *gin.Context) {
|
||||
user := getUser(c)
|
||||
c.FileAttachment(user.FilePath(DEFAULT_JOURNAL), DEFAULT_JOURNAL)
|
||||
})
|
||||
|
||||
authZone.GET("/query", func(c *gin.Context) {
|
||||
user := getUser(c)
|
||||
response := struct {
|
||||
Query string
|
||||
Result string
|
||||
Queries [][2]string
|
||||
}{}
|
||||
var ok bool
|
||||
var err error
|
||||
response.Queries, err = user.queries()
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
response.Query, ok = c.GetQuery("query")
|
||||
if ok && response.Query != "" {
|
||||
response.Result, err = user.query(response.Query)
|
||||
if err != nil {
|
||||
c.AbortWithError(500, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
HTML(c, 200, "query.html", response)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
BIN
screenshots/action.png
Normal file
BIN
screenshots/action.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
screenshots/confirm.png
Normal file
BIN
screenshots/confirm.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
BIN
screenshots/exec.png
Normal file
BIN
screenshots/exec.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
screenshots/home.png
Normal file
BIN
screenshots/home.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
screenshots/success.png
Normal file
BIN
screenshots/success.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
59
session.go
Normal file
59
session.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func authenticate(c *gin.Context) {
|
||||
cookie, err := c.Cookie("session")
|
||||
if err == http.ErrNoCookie {
|
||||
c.Redirect(303, "/signin")
|
||||
return
|
||||
}
|
||||
session, err := store.Verify(cookie)
|
||||
if err != nil {
|
||||
c.Redirect(303, "/signin")
|
||||
return
|
||||
}
|
||||
c.Set("user", User{
|
||||
Email: session.User,
|
||||
})
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func getUser(c *gin.Context) User {
|
||||
return c.MustGet("user").(User)
|
||||
}
|
||||
|
||||
func signup(c *gin.Context) {
|
||||
var user User
|
||||
if err := c.ShouldBind(&user); err != nil {
|
||||
HTML(c, 400, "signup.html", err)
|
||||
return
|
||||
}
|
||||
if err := store.Register(user.Email, user.Password); err != nil {
|
||||
HTML(c, 400, "signup.html", err)
|
||||
return
|
||||
}
|
||||
if err := user.Mkdir(); err != nil {
|
||||
return
|
||||
}
|
||||
signin(c)
|
||||
}
|
||||
|
||||
func signin(c *gin.Context) {
|
||||
var user User
|
||||
if err := c.ShouldBind(&user); err != nil {
|
||||
HTML(c, 400, "signin.html", err)
|
||||
return
|
||||
}
|
||||
token, err := store.Login(user.Email, user.Password)
|
||||
if err != nil {
|
||||
HTML(c, 401, "signin.html", err)
|
||||
return
|
||||
}
|
||||
c.SetCookie("session", token, 60*60*24*7, "", "", false, false)
|
||||
c.Redirect(303, "/dashboard")
|
||||
}
|
||||
46
template.go
Normal file
46
template.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gin-contrib/multitemplate"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func loadTemplates(templatesDir string) multitemplate.Renderer {
|
||||
r := multitemplate.NewRenderer()
|
||||
|
||||
layouts, err := filepath.Glob(path.Join(templatesDir, "layouts", "*.html"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
includes, err := filepath.Glob(path.Join(templatesDir, "*.html"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
for _, include := range includes {
|
||||
r.AddFromFiles(filepath.Base(include), append(layouts, include)...)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type Data interface{}
|
||||
|
||||
type Page struct {
|
||||
Data
|
||||
User User
|
||||
}
|
||||
|
||||
func HTML(c *gin.Context, status int, name string, data interface{}) {
|
||||
output := Page{
|
||||
Data: data,
|
||||
}
|
||||
_, ok := c.Get("user")
|
||||
if ok {
|
||||
output.User = c.MustGet("user").(User)
|
||||
}
|
||||
c.HTML(status, name, output)
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{{ .Date }} * cash
|
||||
cash ${{ .Amount }}
|
||||
assets:cash
|
||||
|
||||
16
templates/dashboard.html
Normal file
16
templates/dashboard.html
Normal file
@@ -0,0 +1,16 @@
|
||||
{{ define "main" }}
|
||||
<h1>Ledger 速記</h1>
|
||||
<form action="/new" method="POST">
|
||||
<label>選擇模板:
|
||||
{{ range .Templates }}
|
||||
<input type="radio" name="action" value="{{ . }}">{{ . }}</option>
|
||||
{{ end }}
|
||||
</label><br>
|
||||
<label>金額:<input name="amount" type="number"></label><br>
|
||||
<label>目的帳戶:<input name="dest" type="text"></label></br>
|
||||
<label>來源帳戶:<input name="src" type="text"></label></br>
|
||||
<label>名稱:<input name="name" type="text"></label></br>
|
||||
<input type="submit" value="新增記錄">
|
||||
</form>
|
||||
{{ template "queries" .Queries }}
|
||||
{{ end }}
|
||||
18
templates/edit.html
Normal file
18
templates/edit.html
Normal file
@@ -0,0 +1,18 @@
|
||||
{{ define "title" }}編輯{{ end }}
|
||||
{{ define "main" }}
|
||||
<h1>編輯檔案</h1>
|
||||
<aside>
|
||||
<ul>
|
||||
{{ range .FileList }}
|
||||
<li><a href="/edit?filename={{ . }}">{{ . }}</a></li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
<p><a href="/edit">新檔案</a></p>
|
||||
</aside>
|
||||
|
||||
<form action="/edit" method="POST">
|
||||
<label>Filename: <input type="text" name="filename" value="{{ .FileName }}"></label><br>
|
||||
<textarea name="data" rows="15" cols="40">{{ .Data }}</textarea><br>
|
||||
<input type="submit" value="{{ if .Exists }}儲存{{ else }}新增{{ end }}">
|
||||
</form>
|
||||
{{ end }}
|
||||
4
templates/error.html
Normal file
4
templates/error.html
Normal file
@@ -0,0 +1,4 @@
|
||||
{{ define "title" }}Error{{ end }}
|
||||
{{ define "main" }}
|
||||
<p class="error">{{ .Error }}</p>
|
||||
{{ end }}
|
||||
@@ -1,20 +1,3 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Ledger Quick Note</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Ledger Quick Note</h1>
|
||||
<form action="/action" method="POST">
|
||||
<label>Action: <select name="action">
|
||||
{{ range .Templates }}
|
||||
{{ if ne .Name "index.html" }}
|
||||
<option value="{{ .Name }}">{{ .Name }}</option>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
</select></label>
|
||||
<label>Amount: <input name="amount" type="number"></label>
|
||||
<input type="submit">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
{{ define "main" }}
|
||||
<h1>Ledger 速記</h1>
|
||||
{{ end }}
|
||||
|
||||
22
templates/layouts/base.html
Normal file
22
templates/layouts/base.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{ block "title" . }}Ledger 速記{{ end }}</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
</head>
|
||||
<body>
|
||||
<nav>
|
||||
<ul>
|
||||
{{ with .User }}
|
||||
{{ .Email }}
|
||||
<li><a href="/dashboard">儀表板</a></li>
|
||||
<li><a href="/edit">編輯</a></li>
|
||||
<li><a href="/download">下載</a></li>
|
||||
<li><a href="/query">查詢</a></li>
|
||||
{{ end }}
|
||||
</nav>
|
||||
{{ block "main" .Data }}
|
||||
|
||||
{{ end }}
|
||||
</body>
|
||||
</html>
|
||||
8
templates/layouts/queries.html
Normal file
8
templates/layouts/queries.html
Normal file
@@ -0,0 +1,8 @@
|
||||
{{ define "queries" }}
|
||||
<h3>快速查詢</h3>
|
||||
<ul>
|
||||
{{ range . }}
|
||||
<li><a href="/query?query={{ index . 1 | urlquery }}">{{ index . 0 }}</a></li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
{{ end }}
|
||||
8
templates/new.html
Normal file
8
templates/new.html
Normal file
@@ -0,0 +1,8 @@
|
||||
{{ define "title" }}Confirm{{ end }}
|
||||
{{ define "main" }}
|
||||
<h1>Confirm new Tx</h1>
|
||||
<form action="/submit" method="POST">
|
||||
<textarea name="tx" rows="15" cols="40">{{ .Tx }}</textarea><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
{{ end }}
|
||||
12
templates/query.html
Normal file
12
templates/query.html
Normal file
@@ -0,0 +1,12 @@
|
||||
{{ define "title" }}查詢{{ end }}
|
||||
{{ define "main" }}
|
||||
<h1>查詢</h1>
|
||||
{{ with .Result }}
|
||||
<pre><code>{{ . }}</code></pre>
|
||||
{{ end }}
|
||||
<form action="/query" method="GET">
|
||||
<input type="text" name="query" value="{{ .Query }}" autofocus>
|
||||
<input type="submit" value="查詢">
|
||||
</form>
|
||||
{{ template "queries" .Queries }}
|
||||
{{ end }}
|
||||
11
templates/signin.html
Normal file
11
templates/signin.html
Normal file
@@ -0,0 +1,11 @@
|
||||
{{ define "title" }}登入{{ end }}
|
||||
{{ define "main" }}
|
||||
<h1>登入</h1>
|
||||
<form action="/signin" method="POST">
|
||||
<label>Email: <input type="text" name="email"></label><br>
|
||||
<label>Password: <input type="password" name="password"></label><br>
|
||||
{{ with .Error }}<p class="error">{{ . }}</p>{{ end }}
|
||||
<input type="submit" value="登入">
|
||||
</form>
|
||||
<a href="signup">沒有帳號嗎?註冊</a>
|
||||
{{ end }}
|
||||
11
templates/signup.html
Normal file
11
templates/signup.html
Normal file
@@ -0,0 +1,11 @@
|
||||
{{ define "title" }}註冊{{ end }}
|
||||
{{ define "main" }}
|
||||
<h1>註冊</h1>
|
||||
<form action="/signup" method="POST">
|
||||
<label>Email: <input type="text" name="email"></label><br>
|
||||
<label>Password: <input type="password" name="password"></label><br>
|
||||
{{ with .Error }}<p class="error">{{ . }}</p>{{ end }}
|
||||
<input type="submit" value="註冊">
|
||||
</form>
|
||||
<a href="signin">已有帳號嗎?登入</a>
|
||||
{{ end }}
|
||||
6
templates/success.html
Normal file
6
templates/success.html
Normal file
@@ -0,0 +1,6 @@
|
||||
{{ define "title" }}Success{{ end }}
|
||||
{{ define "main" }}
|
||||
<p><strong>Success</strong></p>
|
||||
{{ with .FileName }}<p><a href="/edit?filename={{ . }}">繼續編輯</a></p>{{ end }}
|
||||
<pre><code>{{ .Tx }}</code></pre>
|
||||
{{ end }}
|
||||
@@ -1,4 +0,0 @@
|
||||
{{ .Date }} * withdraw
|
||||
assets:cash ${{ .Amount }}
|
||||
assets:checking
|
||||
|
||||
Reference in New Issue
Block a user