allowances/db.go

69 lines
1.3 KiB
Go
Raw Normal View History

2013-02-21 00:19:21 -08:00
package main
import (
"code.google.com/p/go.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
func loadChildren(filename string) (children []Child) {
dbMutex.RLock()
defer dbMutex.RUnlock()
b, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(b, &children)
if err != nil {
log.Fatal(err)
}
return
}