unified-push-xmpp/gateway/token.go

50 lines
1.2 KiB
Go
Raw Permalink Normal View History

2021-09-14 01:32:37 +02:00
package main
import (
"github.com/golang-jwt/jwt"
"mellium.im/xmpp/jid"
)
// JWTSecret the secret
type JWTSecret string
// JWTToken data field
type JWTToken struct {
jwt.StandardClaims
2021-09-14 21:55:21 +02:00
PublicToken string `json:"token"`
JID string `json:"jid"`
2021-09-14 01:32:37 +02:00
}
2021-09-14 21:55:21 +02:00
// Generate an endpoint token by public token and jid
func (s JWTSecret) Generate(jid jid.JID, publicToken string) (string, error) {
2021-09-14 01:32:37 +02:00
jwtToken := JWTToken{
2021-09-14 21:55:21 +02:00
PublicToken: publicToken,
JID: jid.String(),
2021-09-14 01:32:37 +02:00
}
claim := jwt.NewWithClaims(jwt.SigningMethodHS512, jwtToken)
2021-09-14 21:55:21 +02:00
endpointToken, err := claim.SignedString([]byte(s))
2021-09-14 01:32:37 +02:00
if err != nil {
return "", err
}
2021-09-14 21:55:21 +02:00
return endpointToken, nil
2021-09-14 01:32:37 +02:00
}
2021-09-14 21:55:21 +02:00
// Read endpoint token to public token and jid
func (s JWTSecret) Read(endpointToken string) (jid.JID, string, error) {
token, err := jwt.ParseWithClaims(endpointToken, &JWTToken{}, func(token *jwt.Token) (interface{}, error) {
2021-09-14 01:32:37 +02:00
return []byte(s), nil
})
if err != nil {
return jid.JID{}, "", err
}
claims, ok := token.Claims.(*JWTToken)
if !ok {
return jid.JID{}, "", jwt.ErrInvalidKey
}
addr, err := jid.Parse(claims.JID)
if err != nil {
return jid.JID{}, "", err
}
2021-09-14 21:55:21 +02:00
return addr, claims.PublicToken, nil
2021-09-14 01:32:37 +02:00
}