2016-01-11 20:04:57 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"errors"
|
|
|
|
"io/ioutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrInvalidCert = errors.New("Invalid certificate")
|
|
|
|
ErrCouldNotSaveCert = errors.New("Could not save certificate")
|
|
|
|
)
|
|
|
|
|
2016-01-11 23:32:40 +00:00
|
|
|
func (u *User) GetCertificate() *tls.Certificate {
|
|
|
|
u.lock.Lock()
|
|
|
|
cert := u.certificate
|
|
|
|
u.lock.Unlock()
|
|
|
|
|
|
|
|
return cert
|
|
|
|
}
|
|
|
|
|
2016-01-11 20:04:57 +00:00
|
|
|
func (u *User) SetCertificate(certPEM, keyPEM []byte) error {
|
|
|
|
cert, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
|
|
if err != nil {
|
|
|
|
return ErrInvalidCert
|
|
|
|
}
|
|
|
|
u.lock.Lock()
|
2016-01-11 23:32:40 +00:00
|
|
|
u.certificate = &cert
|
2016-01-11 20:04:57 +00:00
|
|
|
u.lock.Unlock()
|
|
|
|
|
2016-01-15 01:27:30 +00:00
|
|
|
err = ioutil.WriteFile(Path.Certificate(u.Username), certPEM, 0600)
|
2016-01-11 20:04:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return ErrCouldNotSaveCert
|
|
|
|
}
|
|
|
|
|
2016-01-15 01:27:30 +00:00
|
|
|
err = ioutil.WriteFile(Path.Key(u.Username), keyPEM, 0600)
|
2016-01-11 20:04:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return ErrCouldNotSaveCert
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u *User) loadCertificate() error {
|
2016-01-15 01:27:30 +00:00
|
|
|
certPEM, err := ioutil.ReadFile(Path.Certificate(u.Username))
|
2016-01-11 20:04:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-01-15 01:27:30 +00:00
|
|
|
keyPEM, err := ioutil.ReadFile(Path.Key(u.Username))
|
2016-01-11 20:04:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-01-11 23:32:40 +00:00
|
|
|
u.certificate = &cert
|
2016-01-11 20:04:57 +00:00
|
|
|
return nil
|
|
|
|
}
|