server/libfic/key.go

91 lines
2.0 KiB
Go
Raw Normal View History

2016-01-13 19:25:25 +00:00
package fic
2016-01-07 17:43:02 +00:00
import (
"crypto/sha512"
)
type Key struct {
2016-01-13 19:25:25 +00:00
Id int64 `json:"id"`
IdExercice int64 `json:"idExercice"`
Type string `json:"type"`
2016-01-19 12:09:36 +00:00
Value []byte `json:"value"`
2016-01-07 17:43:02 +00:00
}
func (e Exercice) GetKeys() ([]Key, error) {
2016-01-19 12:09:36 +00:00
if rows, err := DBQuery("SELECT id_key, id_exercice, type, value FROM exercice_keys WHERE id_exercice = ?", e.Id); err != nil {
2016-01-07 17:43:02 +00:00
return nil, err
} else {
defer rows.Close()
var keys = make([]Key, 0)
for rows.Next() {
var k Key
k.IdExercice = e.Id
2016-01-19 12:09:36 +00:00
if err := rows.Scan(&k.Id, &k.IdExercice, &k.Type, &k.Value); err != nil {
2016-01-07 17:43:02 +00:00
return nil, err
}
keys = append(keys, k)
}
if err := rows.Err(); err != nil {
return nil, err
}
return keys, nil
}
}
2016-01-19 12:09:36 +00:00
func getHashedKey(raw_value string) []byte {
hash := sha512.Sum512([]byte(raw_value))
return hash[:]
2016-01-15 11:57:35 +00:00
}
2016-01-07 17:43:02 +00:00
func (e Exercice) AddRawKey(name string, raw_value string) (Key, error) {
2016-01-15 11:57:35 +00:00
return e.AddKey(name, getHashedKey(raw_value))
2016-01-07 17:43:02 +00:00
}
2016-01-19 12:09:36 +00:00
func (e Exercice) AddKey(name string, value []byte) (Key, error) {
if res, err := DBExec("INSERT INTO exercice_keys (id_exercice, type, value) VALUES (?, ?, ?)", e.Id, name, value); err != nil {
2016-01-07 17:43:02 +00:00
return Key{}, err
} else if kid, err := res.LastInsertId(); err != nil {
return Key{}, err
} else {
return Key{kid, e.Id, name, value}, nil
2016-01-07 17:43:02 +00:00
}
}
func (k Key) Update() (int64, error) {
if res, err := DBExec("UPDATE exercice_keys SET id_exercice = ?, type = ?, value = ? WHERE id_key = ?", k.IdExercice, k.Type, k.Value, k.Id); err != nil {
2016-01-07 17:43:02 +00:00
return 0, err
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
} else {
return nb, err
}
}
func (k Key) Delete() (int64, error) {
if res, err := DBExec("DELETE FROM exercice_keys WHERE id_key = ?", k.Id); err != nil {
2016-01-07 17:43:02 +00:00
return 0, err
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
} else {
return nb, err
}
}
2016-01-15 11:57:35 +00:00
func (k Key) Check(val string) bool {
2016-01-19 12:09:36 +00:00
hash := getHashedKey(val)
if len(k.Value) != len(hash) {
return false
}
for i := range hash {
if k.Value[i] != hash[i] {
return false
}
}
return true
2016-01-15 11:57:35 +00:00
}