This repository has been archived on 2024-04-07. You can view files and clone it, but cannot push or open issues or pull requests.
summer-utils/tables/certificate/certificate.go
2023-04-16 11:56:17 +01:00

77 lines
1.9 KiB
Go

package certificate
import (
"code.mrmelon54.com/melon/summer/pkg/utils"
"github.com/pkg/errors"
"xorm.io/xorm"
)
var ErrFailedToGetCertificate = errors.New("failed to get certificate")
type Certificate struct {
Id uint64 `xorm:"pk autoincr"`
Owner uint64
LetsEncrypt uint64
Namesilo uint64
AutoRenew *bool
Active *bool
Renewing *bool
RenewFailed *bool
}
func (c *Certificate) SortOutDefaultValues() {
if c.Active == nil {
c.Active = utils.PBool(false)
}
if c.Renewing == nil {
c.Renewing = utils.PBool(false)
}
if c.RenewFailed == nil {
c.RenewFailed = utils.PBool(false)
}
}
//goland:noinspection GoNameStartsWithPackageName
type CertificateMetaDomainJoiner struct {
Certificate `xorm:"extends"`
CertificateData `xorm:"extends"`
CertificateDomain `xorm:"extends"`
}
func (c *CertificateMetaDomainJoiner) TableName() string { return "certificate" }
func (c *CertificateMetaDomainJoiner) SortOutDefaultValues() {
c.Certificate.SortOutDefaultValues()
c.CertificateData.SortOutDefaultValues()
}
func GetCertForDomain(db *xorm.Engine, a string) (*CertificateMetaDomainJoiner, error) {
b, ok := utils.GetBaseDomain(a)
if !ok {
return nil, errors.New("no idea what domain name you are using")
}
// Time for a massive SQL query
var c []CertificateMetaDomainJoiner
//goland:noinspection SqlDialectInspection,SqlNoDataSourceInspection
err := db.SQL(`
select * from certificate
inner join certificate_data on id = meta_id and ready = 1 and not_after > now()
inner join certificate_domain on id = cert_id
where (domain = ? and wildcard = 0) or (domain = ? and wildcard = 1) and active = 1
order by ready DESC, wildcard ASC, not_after DESC
limit 1
`, a, b).Find(&c)
if err != nil {
return nil, err
}
if len(c) < 1 {
return nil, ErrFailedToGetCertificate
}
// If there is at least 1 certificate then use for first and ignore the rest
d := c[0]
d.SortOutDefaultValues()
return &d, nil
}