74 lines
2.2 KiB
Go
74 lines
2.2 KiB
Go
package v1
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/controllers"
|
|
accounts "gitea.badhouseplants.net/softplayer/softplayer-go-proto/pkg/accounts/v1"
|
|
"github.com/coreos/go-oidc/v3/oidc"
|
|
"github.com/golang/protobuf/ptypes/empty"
|
|
"golang.org/x/oauth2"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
)
|
|
|
|
func NewAccountNoAuthRPCImpl(ctrl *controllers.AccountController) *AccountsNoAuthServer {
|
|
return &AccountsNoAuthServer{
|
|
ctrl: ctrl,
|
|
}
|
|
}
|
|
|
|
type AccountsNoAuthServer struct {
|
|
accounts.UnimplementedAccountsNoAuthServiceServer
|
|
ctrl *controllers.AccountController
|
|
}
|
|
|
|
func (a *AccountsNoAuthServer) SignIn(ctx context.Context, in *accounts.SignInRequest) (*empty.Empty, error) {
|
|
provider, err := oidc.NewProvider(ctx, "https://authentik.badhouseplants.net")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Configure an OpenID Connect aware OAuth2 client.
|
|
oauth2Config := oauth2.Config{
|
|
ClientID: "softplayer-localhost",
|
|
ClientSecret: "pRpe3scGUE2jNH6t5rqI9R4OROeQHs4eO6ku957mYjDumKhQGX8QJcO0BMJ2FG4sUpvFrqccEqWgc3wKMp94tC8LyvTnkPF0Tg0CaldAEHuoQQdNKAzXVxwrHE6kNyBC",
|
|
RedirectURL: "http://localhost:8080/#/auth/callback",
|
|
|
|
// Discovery returns the OAuth2 endpoints.
|
|
Endpoint: provider.Endpoint(),
|
|
|
|
// "openid" is a required scope for OpenID Connect flows.
|
|
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
|
}
|
|
verifier := provider.Verifier(&oidc.Config{ClientID: "softplayer-localhost"})
|
|
|
|
oauth2Token, err := oauth2Config.Exchange(ctx, in.Code)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Extract the ID Token from OAuth2 token.
|
|
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
|
if !ok {
|
|
return nil, status.Error(codes.Unauthenticated, "Couldn't parse oauth token")
|
|
}
|
|
|
|
// Parse and verify ID Token payload.
|
|
idToken, err := verifier.Verify(ctx, rawIDToken)
|
|
if err != nil {
|
|
return nil, status.Error(codes.Unauthenticated, "Couldn't verify oauth token")
|
|
}
|
|
|
|
// Extract custom claims
|
|
var claims struct {
|
|
Email string `json:"email"`
|
|
Verified bool `json:"email_verified"`
|
|
}
|
|
if err := idToken.Claims(&claims); err != nil {
|
|
// handle error
|
|
}
|
|
return &emptypb.Empty{}, nil
|
|
}
|