1
0
Fork 0
httpserver/modules/saml/funcs.go

98 Zeilen
2.0 KiB
Go

2021-01-09 20:39:05 +00:00
package saml
import (
"bytes"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"github.com/crewjam/saml"
"github.com/phuslu/log"
"gopkg.in/dgrijalva/jwt-go.v3"
)
func initcert(file string, verify func(interface{}) bool) (key interface{}, err error) {
var blocks []*pem.Block
if file == "" {
err = errors.New("SPPrivatekey empty")
return
}
blocks, err = loadcerts(file)
if err != nil {
return nil, err
}
for _, b := range blocks {
var key interface{}
key, err = x509.ParsePKCS8PrivateKey(b.Bytes)
if err != nil {
key, err = x509.ParseCertificate(b.Bytes)
if err != nil {
2021-01-11 20:56:29 +00:00
log.Warn().AnErr("parsingerror", err).Msgf("could not parse file %s as publickey or as an privatekey", file)
2021-01-09 20:39:05 +00:00
continue
}
}
if key == nil {
return nil, fmt.Errorf("Cannot find an Key in %s", file)
}
if verify(key) {
return key, nil
}
}
return nil, errors.New("No key found")
}
func loadcerts(filename string) (blocks []*pem.Block, err error) {
var file *os.File
if file, err = os.Open(filename); err != nil {
return
}
var buffer bytes.Buffer
read, err := buffer.ReadFrom(file)
log.Debug().Int64("read bytes", read).Err(err).Msgf("Read file %s", filename)
if err != nil {
return
}
data := buffer.Bytes()
var block *pem.Block
for {
if len(data) == 0 {
return
}
block, data = pem.Decode(data)
if block != nil {
blocks = append(blocks, block)
}
}
}
func empty(data []string) bool {
for _, t := range data {
if t == "" {
return true
}
}
return false
}
func jwttoken(claim jwt.Claims, privatekey interface{}) (string, error) {
token := jwt.NewWithClaims(
jwt.SigningMethodPS512,
claim,
)
return token.SignedString(privatekey)
}
func attributeStatementstomap(a []saml.AttributeStatement) map[string][]string {
var output = map[string][]string{}
for _, b := range a {
for _, c := range b.Attributes {
output[c.FriendlyName] = []string{}
for _, d := range c.Values {
output[c.FriendlyName] = append(output[c.FriendlyName], d.Value)
}
}
}
return output
}