57 lines
2.6 KiB
Go
57 lines
2.6 KiB
Go
package repository
|
|
|
|
import (
|
|
"ca-mini/internal/model"
|
|
"database/sql"
|
|
"time"
|
|
)
|
|
|
|
type CertificateRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewCertificateRepository(db *sql.DB) *CertificateRepository {
|
|
return &CertificateRepository{db: db}
|
|
}
|
|
|
|
func (r *CertificateRepository) AddCert(cert *model.CertInfo) error {
|
|
createdAt := time.Now()
|
|
updatedAt := time.Now()
|
|
_, err := r.db.Exec(
|
|
"INSERT INTO certificates (id, serial_number, cert_cn, cert_dn, cert_version, public_key_alg, signature_alg, issuer_cn, issuer_dn, cert_sub_alt_name, algorithm, key_length, csr, private_key, certificate, valid_from, valid_to, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
cert.CertId, cert.SerialNumber, cert.CertCn, cert.CertDn, cert.Version, cert.PublicKeyAlg, cert.SignatureAlg, cert.IssuerCn, cert.IssuerDn, cert.CertSubAltName, cert.PublicKeyAlg, 2048, cert.Csr, cert.PrivateKey, cert.Cert, cert.BeforeTime, cert.AfterTime, createdAt, updatedAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (r *CertificateRepository) SelectCertById(id string) (*model.CertInfo, error) {
|
|
var cert model.CertInfo
|
|
err := r.db.QueryRow(
|
|
"SELECT id, serial_number, cert_cn, cert_dn, cert_version, public_key_alg, signature_alg, issuer_cn, issuer_dn, cert_sub_alt_name, algorithm, key_length, csr, private_key, certificate, valid_from, valid_to FROM certificates WHERE id = ?",
|
|
id,
|
|
).Scan(
|
|
&cert.CertId, &cert.SerialNumber, &cert.CertCn, &cert.CertDn, &cert.Version, &cert.PublicKeyAlg, &cert.SignatureAlg, &cert.IssuerCn, &cert.IssuerDn, &cert.CertSubAltName, &cert.PublicKeyAlg, &cert.KeyLength, &cert.Csr, &cert.PrivateKey, &cert.Cert, &cert.BeforeTime, &cert.AfterTime,
|
|
)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return nil, nil // 未找到记录
|
|
}
|
|
return nil, err
|
|
}
|
|
return &cert, nil
|
|
}
|
|
|
|
func (r *CertificateRepository) UpdateCert(cert *model.CertInfo) error {
|
|
updatedAt := time.Now()
|
|
_, err := r.db.Exec(
|
|
"UPDATE certificates SET serial_number = ?, cert_cn = ?, cert_dn = ?, cert_version = ?, public_key_alg = ?, signature_alg = ?, issuer_cn = ?, issuer_dn = ?, cert_sub_alt_name = ?, algorithm = ?, key_length = ?, csr = ?, private_key = ?, certificate = ?, valid_from = ?, valid_to = ?, updated_at = ? WHERE id = ?",
|
|
cert.SerialNumber, cert.CertCn, cert.CertDn, cert.Version, cert.PublicKeyAlg, cert.SignatureAlg, cert.IssuerCn, cert.IssuerDn, cert.CertSubAltName, cert.PublicKeyAlg, cert.KeyLength, cert.Csr, cert.PrivateKey, cert.Cert, cert.BeforeTime, cert.AfterTime, updatedAt, cert.CertId,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (r *CertificateRepository) DeleteCert(id string) error {
|
|
_, err := r.db.Exec("DELETE FROM certificates WHERE id = ?", id)
|
|
return err
|
|
}
|