2024-02-15 12:41:39 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-05-17 21:40:31 +01:00
|
|
|
"context"
|
2024-02-15 12:41:39 +00:00
|
|
|
"github.com/1f349/lavender/database"
|
|
|
|
"github.com/1f349/mjwt"
|
|
|
|
"github.com/go-oauth2/oauth2/v4"
|
|
|
|
"github.com/go-oauth2/oauth2/v4/server"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2024-07-27 21:46:58 +01:00
|
|
|
func addIdTokenSupport(srv *server.Server, db *database.Queries, key *mjwt.Issuer) {
|
2024-02-15 12:41:39 +00:00
|
|
|
srv.SetExtensionFieldsHandler(func(ti oauth2.TokenInfo) (fieldsValue map[string]interface{}) {
|
|
|
|
scope := ti.GetScope()
|
|
|
|
if containsScope(scope, "openid") {
|
|
|
|
idToken, err := generateIDToken(ti, db, key)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fieldsValue = map[string]interface{}{}
|
|
|
|
fieldsValue["id_token"] = idToken
|
|
|
|
}
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// IdTokenClaims contains the JWT claims for an access token
|
2024-02-15 14:44:58 +00:00
|
|
|
type IdTokenClaims struct {
|
|
|
|
Subject string `json:"subject"`
|
|
|
|
}
|
2024-02-15 12:41:39 +00:00
|
|
|
|
|
|
|
func (a IdTokenClaims) Valid() error { return nil }
|
2024-02-15 14:44:58 +00:00
|
|
|
func (a IdTokenClaims) Type() string { return "id-token" }
|
2024-02-15 12:41:39 +00:00
|
|
|
|
2024-07-27 21:46:58 +01:00
|
|
|
func generateIDToken(ti oauth2.TokenInfo, us *database.Queries, key *mjwt.Issuer) (token string, err error) {
|
2024-05-17 21:40:31 +01:00
|
|
|
user, err := us.GetUser(context.Background(), ti.GetUserID())
|
2024-02-15 12:41:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2024-05-16 22:46:32 +01:00
|
|
|
token, err = key.GenerateJwt(user.Subject, "", jwt.ClaimStrings{ti.GetClientID()}, ti.GetAccessExpiresIn(), &IdTokenClaims{Subject: user.Subject})
|
2024-02-15 12:41:39 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func containsScope(scopes, s string) bool {
|
|
|
|
_scopes := strings.Split(scopes, " ")
|
|
|
|
for _, _s := range _scopes {
|
|
|
|
if _s == s {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|