Skip to content

Commit

Permalink
Merge pull request #603 from taiwonaf/Feat/BE-14-implement-Video-call…
Browse files Browse the repository at this point in the history
…-feature-Agora-token-generator

Feat- implelented Agora token generator for Agora engine authentication
  • Loading branch information
Aminujb authored Nov 25, 2022
2 parents d73e553 + aa90b8b commit 296953f
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 0 deletions.
15 changes: 15 additions & 0 deletions agora/models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package agora

import "zuri.chat/zccore/utils"

type AgoraToken struct {
Token string `json:"token"`
}

type AgoraHandler struct {
configs *utils.Configurations
}

func NewAgoraHandler(c *utils.Configurations) *AgoraHandler {
return &AgoraHandler{configs: c}
}
77 changes: 77 additions & 0 deletions agora/rtctoken.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package agora

import (
"fmt"
"net/http"
"strconv"
"time"

"github.com/AgoraIO-Community/go-tokenbuilder/rtctokenbuilder"
"github.com/gorilla/mux"
"zuri.chat/zccore/utils"
)

func (a *AgoraHandler) GetRtcToken(w http.ResponseWriter, r *http.Request) {

// get param values
channelName, tokentype, uidStr, role := ParseRtcParams(r)
appId := a.configs.AppId
appCertificate := a.configs.AppCerificate
rtcToken, tokenErr := generateRtcToken(appId, appCertificate, channelName, uidStr, tokentype, role)

if tokenErr != nil {
utils.GetError(tokenErr, http.StatusBadRequest, w)
return
}
response := AgoraToken{
Token: rtcToken,
}
utils.GetSuccess("Token generated successfully", response, w)

}

func ParseRtcParams(r *http.Request) (channelName, tokentype, uidStr string, role rtctokenbuilder.Role) {
channelName = mux.Vars(r)["channelName"]
tokentype = mux.Vars(r)["tokentype"]
roleStr := mux.Vars(r)["role"]
uidStr = mux.Vars(r)["uid"]

if roleStr == "publisher" {
role = rtctokenbuilder.RolePublisher
} else {
role = rtctokenbuilder.RoleSubscriber
}

return channelName, tokentype, uidStr, role
}

func generateRtcToken(appId, appCertificate, channelName, uidStr, tokentype string, role rtctokenbuilder.Role) (string, error) {
expireTimestamp := time.Now().Add(2 * time.Hour).Unix()
expireTime := uint32(expireTimestamp)
if tokentype == "userAccount" {
rtcToken, err := rtctokenbuilder.BuildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, role, expireTime)
if err != nil {
return "", err
}
return rtcToken, nil

} else if tokentype == "uid" {
uid64, parseErr := strconv.ParseUint(uidStr, 10, 64)
// check if conversion fails
if parseErr != nil {
err := fmt.Errorf("failed to parse uidStr: %s, to uint causing error: %s", uidStr, parseErr)
return "", err
}

uid := uint32(uid64) // convert uid from uint64 to uint 32
rtcToken, err := rtctokenbuilder.BuildTokenWithUID(appId, appCertificate, channelName, uid, role, expireTime)
if err != nil {
return "", err
}
return rtcToken, nil

} else {
err := fmt.Errorf("failed to generate RTC token for Unknown Tokentype: %s", tokentype)
return "", err
}
}
3 changes: 3 additions & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ MAILGUN_DOMAIN=ng.hng.tech
MAILGUN_EMAIL=Zuri Chat <hngi8@hng.tech>
CENTRIFUGO_KEY = find-your-key
CENTRIFUGO_ENDPOINT = https://realtime.zuri.chat/api
# Agora APP ID and APP CERTIFICATE
APP_ID=f910a1fb4cfe4c5996c979c54e570ba7
APP_CERTIFICATE=04c4146b729d4bddaf9ce4ae107c9ff0
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.16

require (
github.com/AfterShip/email-verifier v1.3.0
github.com/AgoraIO-Community/go-tokenbuilder v1.0.0
github.com/anthonynsimon/bild v0.13.0
github.com/felixge/httpsnoop v1.0.2 // indirect
github.com/getsentry/sentry-go v0.11.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/AfterShip/email-verifier v1.3.0 h1:RhRLm3v2Iui5ZmWg6e+Q0xQU2Bai3mgINkY2t2p9u0g=
github.com/AfterShip/email-verifier v1.3.0/go.mod h1:XeRhBrlxgnon6zOZ05EBNNanuxSy5uXl22RRBd5Jcug=
github.com/AgoraIO-Community/go-tokenbuilder v1.0.0 h1:R6L8a5u+p1qGpY5lNyQ19vRyDzIwhhqQnRlg9AAbqmA=
github.com/AgoraIO-Community/go-tokenbuilder v1.0.0/go.mod h1:xqPdaiFG00M1hNN/CCYh8j+NTmkiJsQtqYdf4YAlncA=
github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
Expand Down
7 changes: 7 additions & 0 deletions internal/transport/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/graphql-go/graphql"
gqlHandler "github.com/graphql-go/handler"

"zuri.chat/zccore/agora"
"zuri.chat/zccore/auth"
"zuri.chat/zccore/blog"
"zuri.chat/zccore/contact"
Expand Down Expand Up @@ -48,6 +49,9 @@ func (h *Handler) SetupRoutes() {
us := user.NewUserHandler(configs, mailService)
gql := utils.NewGraphQlHandler(configs)

// Agora
ah := agora.NewAgoraHandler(configs)

client := utils.GetDefaultMongoClient()
ps := plugin.NewMongoService(client)
ph := plugin.NewHandler(ps)
Expand Down Expand Up @@ -205,6 +209,9 @@ func (h *Handler) SetupRoutes() {
h.Router.HandleFunc("/delete/file/{plugin_id}", au.IsAuthenticated(service.DeleteFile)).Methods("DELETE")
h.Router.PathPrefix("/files/").Handler(http.StripPrefix("/files/", http.FileServer(http.Dir("./files/"))))

// Agora token generator
h.Router.HandleFunc("/rtc/{channelName}/{role}/{tokentype}/{uid}/", ah.GetRtcToken).Methods("GET")

// graphql
schema, _ := graphql.NewSchema(gql.LoadGraphQlSchema())
gh := gqlHandler.New(&gqlHandler.Config{
Expand Down
8 changes: 8 additions & 0 deletions utils/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ type Configurations struct {
FacebookOAuthURL string

HmacSampleSecret string

// Agora details
AppId string
AppCerificate string
}

func NewConfigurations() *Configurations {
Expand Down Expand Up @@ -111,6 +115,10 @@ func NewConfigurations() *Configurations {
FacebookOAuthURL: viper.GetString("FACEBOOK_OAUTH"),

HmacSampleSecret: viper.GetString("HMAC_SECRET"),

// Agora details
AppId: viper.GetString("APP_ID"),
AppCerificate: viper.GetString("APP_CERTIFICATE"),
}

return configs
Expand Down

0 comments on commit 296953f

Please sign in to comment.