Skip to content

Commit

Permalink
Merge pull request #14 from shoy160/main
Browse files Browse the repository at this point in the history
feat: 添加认证侧以及管理侧事件发布订阅相关方法
  • Loading branch information
liaochangjiang committed Apr 10, 2023
2 parents 1822226 + baefb1a commit 5f97c51
Show file tree
Hide file tree
Showing 13 changed files with 469 additions and 14 deletions.
66 changes: 62 additions & 4 deletions authentication/authentication_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"

"github.com/Authing/authing-golang-sdk/v3/constant"
"github.com/Authing/authing-golang-sdk/v3/dto"
"github.com/Authing/authing-golang-sdk/v3/util"
"strings"

keyfunc "github.com/MicahParks/compatibility-keyfunc"
"github.com/dgrijalva/jwt-go"
Expand All @@ -25,8 +26,9 @@ var commonHeaders = map[string]string{
}

type AuthenticationClient struct {
options *AuthenticationClientOptions
jwks *keyfunc.JWKS
options *AuthenticationClientOptions
jwks *keyfunc.JWKS
eventHub *util.WebSocketEventHub
}

func NewAuthenticationClient(options *AuthenticationClientOptions) (*AuthenticationClient, error) {
Expand All @@ -39,6 +41,9 @@ func NewAuthenticationClient(options *AuthenticationClientOptions) (*Authenticat
if options.AppHost == "" {
return nil, errors.New("AppHost 不能为空")
}
if options.WssHost == "" {
options.WssHost = constant.WebSocketHost
}
if options.RedirectUri == "" {
return nil, errors.New("RedirectUri 不能为空")
}
Expand All @@ -56,7 +61,8 @@ func NewAuthenticationClient(options *AuthenticationClientOptions) (*Authenticat
}

client := &AuthenticationClient{
options: options,
options: options,
eventHub: util.NewWebSocketEvent(),
}

return client, nil
Expand Down Expand Up @@ -2204,3 +2210,55 @@ func (client *AuthenticationClient) getUserAuthResourceStruct(reqDto *dto.GetUse
}
return &response
}

/*
* @summary 事件发布
* @description 根据事件编码发布一个自定义事件
* @param eventCode 事件编码
* @param body 事件消息
* @returns IsSuccessRespDto
*/
func (client *AuthenticationClient) PubEvent(eventCode string, data interface{}) *dto.IsSuccessRespDto {
var reqDto = dto.NewEventReqDto(eventCode, data)
b, err := client.SendHttpRequest("/api/v3/pub-userEvent", fasthttp.MethodPost, reqDto)
var response dto.IsSuccessRespDto
if err != nil {
fmt.Println(err)
return nil
}
err = json.Unmarshal(b, &response)
if err != nil {
fmt.Println(err)
return nil
}
return &response
}

/*
* @summary 事件订阅
* @description 根据事件编码订阅一个自定义事件
* @param eventCode 事件编码
* @param onSuccess 成功的消息
* @param onError 异常处理
*/
func (client *AuthenticationClient) SubEvent(eventCode string, onSuccess func(msg []byte), onError func(err error)) {
var options = client.options
token := options.AccessToken
// fmt.Println(token)
if !client.eventHub.CreateAuthentication(eventCode, options.WssHost, token) {
return
}
client.eventHub.AddReceiver(eventCode, onSuccess, onError)
// recv message exec corresponding callback function
go client.eventHub.StartReceive(eventCode)
}

/*
* @summary 事件订阅
* @description 根据事件编码订阅一个自定义事件
* @param eventCode 事件编码
* @param receiver 消息处理器
*/
func (client *AuthenticationClient) SubEventByReceiver(eventCode string, receiver util.EventReceiver) {
client.SubEvent(eventCode, receiver.OnSuccess, receiver.OnError)
}
56 changes: 51 additions & 5 deletions authentication/authentication_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package authentication

import (
"fmt"

"github.com/Authing/authing-golang-sdk/v3/constant"
"github.com/Authing/authing-golang-sdk/v3/dto"

Expand All @@ -14,11 +15,12 @@ import (

var authenticationClient *AuthenticationClient
var options = AuthenticationClientOptions{
AppId: "",
AppSecret: "",
AppHost: "",
RedirectUri: "http://localhost:8989",
InsecureSkipVerify: true,
AppId: "",
AppSecret: "",
AppHost: "",
WssHost: "ws://localhost:88",
RedirectUri: "http://localhost:8989",
AccessToken: "",
}

const idToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2M2IzZWE3Mzk0MDc0YWE1ZTE5YmIzMGMiLCJhdWQiOiI2M2IzZWE1YmM5NjY0YzlkMDhkMTkwYzgiLCJpYXQiOjE2NzI3MzY2NjcsImV4cCI6MTY3Mzk0NjI2NywiaXNzIjoiaHR0cHM6Ly9nby11c2VyLXBlcm1pc3Npb24tYXV0aC5hdXRoaW5nLmNuL29pZGMiLCJub25jZSI6InJtZ0pab3RxNGkiLCJuYW1lIjpudWxsLCJnaXZlbl9uYW1lIjpudWxsLCJtaWRkbGVfbmFtZSI6bnVsbCwiZmFtaWx5X25hbWUiOm51bGwsIm5pY2tuYW1lIjpudWxsLCJwcmVmZXJyZWRfdXNlcm5hbWUiOm51bGwsInByb2ZpbGUiOm51bGwsInBpY3R1cmUiOiJodHRwczovL2ZpbGVzLmF1dGhpbmcuY28vYXV0aGluZy1jb25zb2xlL2RlZmF1bHQtdXNlci1hdmF0YXIucG5nIiwid2Vic2l0ZSI6bnVsbCwiYmlydGhkYXRlIjpudWxsLCJnZW5kZXIiOiJVIiwiem9uZWluZm8iOm51bGwsImxvY2FsZSI6bnVsbCwidXBkYXRlZF9hdCI6IjIwMjMtMDEtMDNUMDg6NTQ6NDUuMzMwWiIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicGhvbmVfbnVtYmVyIjpudWxsLCJwaG9uZV9udW1iZXJfdmVyaWZpZWQiOmZhbHNlfQ.3awp567aJ3wBXR0mh0l1oBTugTNsDqYpJVIaDTeHXbI\n"
Expand Down Expand Up @@ -262,3 +264,47 @@ func TestAuthenticationClient_GetUserAuthResourceStruct(t *testing.T) {
fmt.Println(response)

}

type UserEvent struct {
Id string `json:"id"`
Name string `json:"name"`
}

func TestClient_PubEvent(t *testing.T) {
var data = &UserEvent{
Id: "232323232",
Name: "golang-authentication-test",
}
var resp = authenticationClient.PubEvent("custom_xrgu.user_create", data)
fmt.Println(resp)
}

type Receiver1 struct{}

func (receiver *Receiver1) OnSuccess(msg []byte) {
fmt.Println(string(msg))
}
func (receiver *Receiver1) OnError(err error) {
fmt.Println(err)
}

func TestClient_SubEvent(t *testing.T) {
ErrChan := make(chan error, 1)
receiver := &Receiver1{}
authenticationClient.SubEventByReceiver("custom_xrgu.user_create", receiver)

authenticationClient.SubEvent("custom_xrgu.user_create", func(msg []byte) {
fmt.Println(string(msg) + "222")
}, func(err error) {
fmt.Println(err)
ErrChan <- err
})

authenticationClient.SubEvent("custom_xrgu.user_create", func(msg []byte) {
fmt.Println(string(msg) + "333")
}, func(err error) {
fmt.Println(err)
ErrChan <- err
})
<-ErrChan
}
4 changes: 4 additions & 0 deletions authentication/authentication_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ type AuthenticationClientOptions struct {
是否跳过 HTTPS 证书检测,默认为 false;如果是私有化部署的场景且证书不被信任,可以设置为 true
*/
InsecureSkipVerify bool
/**
* 订阅事件 WebSocket 地址
*/
WssHost string
}

type AuthUrlResult struct {
Expand Down
2 changes: 2 additions & 0 deletions constant/base_constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ const (
StringEmpty = ""

None = "none"

WebSocketHost = "wss://events.authing.com"
)
19 changes: 19 additions & 0 deletions dto/EventReqDto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package dto

import "encoding/json"

type EventReqDto struct {
EventType string `json:"eventType"`
EventData string `json:"eventData"`
}

func NewEventReqDto(eventCode string, eventData interface{}) *EventReqDto {
data, err := json.Marshal(eventData)
if err != nil {
panic(err)
}
return &EventReqDto{
EventType: eventCode,
EventData: string(data),
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.8
require (
github.com/MicahParks/compatibility-keyfunc v0.14.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gorilla/websocket v1.5.0 // indirect
github.com/klauspost/compress v1.15.2 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/valyala/fasthttp v1.36.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumC
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/form3tech-oss/jwt-go v3.2.5+incompatible h1:/l4kBbb4/vGSsdtB5nUe8L7B9mImVMaBPw9L/0TBHU8=
github.com/form3tech-oss/jwt-go v3.2.5+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.15.2 h1:3WH+AG7s2+T8o3nrM/8u2rdqUEcQhmga7smjrT41nAw=
github.com/klauspost/compress v1.15.2/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
Expand Down
56 changes: 56 additions & 0 deletions management/management_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package management
import (
"encoding/json"
"fmt"

"github.com/Authing/authing-golang-sdk/v3/dto"
"github.com/Authing/authing-golang-sdk/v3/util"
"github.com/valyala/fasthttp"
)

Expand Down Expand Up @@ -6547,3 +6549,57 @@ func (client *ManagementClient) UpdateAccessKey(reqDto *dto.UpdateAccessKeyDto)
}
return &response
}

/*
* @summary 事件发布
* @description 根据事件编码发布一个自定义事件
* @param eventCode 事件编码
* @param body 事件消息
* @returns IsSuccessRespDto
*/
func (client *ManagementClient) PubEvent(eventCode string, data interface{}) *dto.IsSuccessRespDto {
var reqDto = dto.NewEventReqDto(eventCode, data)
b, err := client.SendHttpRequest("/api/v3/pub-event", fasthttp.MethodPost, reqDto)
var response dto.IsSuccessRespDto
if err != nil {
fmt.Println(err)
return nil
}
err = json.Unmarshal(b, &response)
if err != nil {
fmt.Println(err)
return nil
}
return &response
}

/*
* @summary 事件订阅
* @description 根据事件编码订阅一个自定义事件
* @param eventCode 事件编码
* @param onSuccess 成功的消息
* @param onError 失败处理
*/
func (client *ManagementClient) SubEvent(eventCode string, onSuccess func(msg []byte), onError func(err error)) {
var options = client.options
defMap := make(map[string]string, 0)
stringToSign := util.ComposeStringToSign("websocket", "", defMap, defMap)
token := util.GetAuthorization(client.options.AccessKeyId, client.options.AccessKeySecret, stringToSign)
// fmt.Println(token)
if !client.eventHub.CreateManagement(eventCode, options.WssHost, token) {
return
}
client.eventHub.AddReceiver(eventCode, onSuccess, onError)
// recv message exec corresponding callback function
go client.eventHub.StartReceive(eventCode)
}

/*
* @summary 事件订阅
* @description 根据事件编码订阅一个自定义事件
* @param eventCode 事件编码
* @param receiver 消息处理器
*/
func (client *ManagementClient) SubEventByReceiver(eventCode string, receiver util.EventReceiver) {
client.SubEvent(eventCode, receiver.OnSuccess, receiver.OnError)
}
10 changes: 9 additions & 1 deletion management/management_client_options.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package management

import (
"github.com/Authing/authing-golang-sdk/v3/constant"
"net/http"

"github.com/Authing/authing-golang-sdk/v3/constant"
"github.com/Authing/authing-golang-sdk/v3/util"
)

type ManagementClient struct {
HttpClient *http.Client
options *ManagementClientOptions
userPoolId string
eventHub *util.WebSocketEventHub
}

type ManagementClientOptions struct {
Expand All @@ -22,12 +25,16 @@ type ManagementClientOptions struct {
是否跳过 HTTPS 证书检测,默认为 false;如果是私有化部署的场景且证书不被信任,可以设置为 true
*/
InsecureSkipVerify bool
WssHost string
}

func NewManagementClient(options *ManagementClientOptions) (*ManagementClient, error) {
if options.Host == "" {
options.Host = constant.ApiServiceUrl
}
if options.WssHost == "" {
options.WssHost = constant.WebSocketHost
}
c := &ManagementClient{
options: options,
}
Expand All @@ -42,5 +49,6 @@ func NewManagementClient(options *ManagementClientOptions) (*ManagementClient, e
)
c.HttpClient = oauth2.NewManagementClient(context.Background(), src)*/
}
c.eventHub = util.NewWebSocketEvent()
return c, nil
}
Loading

0 comments on commit 5f97c51

Please sign in to comment.