allowances/db.go

80 lines
1.5 KiB
Go
Raw Normal View History

2013-02-21 00:19:21 -08:00
package main
import (
"golang.org/x/crypto/bcrypt"
2013-02-26 22:30:23 -08:00
"encoding/json"
"io/ioutil"
2013-02-21 00:19:21 -08:00
"log"
2013-03-04 21:56:39 -08:00
"sync"
2013-02-21 00:19:21 -08:00
)
2013-03-04 21:56:39 -08:00
var dbMutex = sync.RWMutex{}
2013-02-26 22:30:23 -08:00
func get_passes(filename string) (cur_passes []string, err error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(b, &cur_passes)
if err != nil {
log.Fatal(err)
}
return
}
func add_password(filename, new_pw string) (err error) {
cur_passes, err := get_passes(filename)
if err != nil {
log.Fatal(err)
}
hpass, err := bcrypt.GenerateFromPassword(
[]byte(*add_pw), bcrypt.DefaultCost)
cur_passes = append(cur_passes, string(hpass))
b, err := json.Marshal(cur_passes)
err = ioutil.WriteFile(filename, b, 0644)
if err != nil {
log.Fatal(err)
}
return
}
2013-02-21 00:19:21 -08:00
2013-02-26 22:30:23 -08:00
func check_password(filename, attempt string) (result bool) {
hashes, err := get_passes(filename)
2013-02-21 00:19:21 -08:00
if err != nil {
log.Fatal(err)
}
for _, hash := range hashes {
2013-02-21 00:36:32 -08:00
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(attempt))
2013-02-21 00:19:21 -08:00
if err == nil {
result = true
return
}
}
return
}
2013-03-04 21:56:39 -08:00
2013-03-08 22:28:24 -08:00
func loadChildren(filename string) (children map[string]int) {
2013-03-06 12:31:30 -08:00
dbMutex.RLock()
defer dbMutex.RUnlock()
2013-03-04 21:56:39 -08:00
b, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(b, &children)
if err != nil {
log.Fatal(err)
}
return
}
2013-03-08 22:28:24 -08:00
func dumpChildren(filename string, children map[string]int) {
dbMutex.Lock()
defer dbMutex.Unlock()
b, err := json.Marshal(children)
err = ioutil.WriteFile(filename, b, 0644)
if err != nil {
log.Fatal("serious issue writing children db file", err)
}
return
}