allowances/db.go

52 lines
1021 B
Go

package main
import (
"code.google.com/p/go.crypto/bcrypt"
"encoding/json"
"io/ioutil"
"log"
)
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
}
func check_password(filename, attempt string) (result bool) {
hashes, err := get_passes(filename)
if err != nil {
log.Fatal(err)
}
for _, hash := range hashes {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(attempt))
if err == nil {
result = true
return
}
}
return
}