Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add generate token #157

Merged
merged 1 commit into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .bicep/webapp/parameters.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"ORGANIZATION_NAME": "",
"COMMUNITY_PORTAL_APP_ID": "",
"CALLBACK_RETRY_FREQ": "",
"SESSION_KEY": ""
"SESSION_KEY": "",
"SCOPE":""
}
}
}
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/setup-appservice-resource.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ jobs:
parameters.appServiceSettings.value.COMMUNITY_PORTAL_APP_ID : ${{ vars.COMMUNITY_PORTAL_APP_ID }}
parameters.appServiceSettings.value.CALLBACK_RETRY_FREQ: ${{ vars.CALLBACK_RETRY_FREQ }}
parameters.appServiceSettings.value.SESSION_KEY: ${{ secrets.SESSION_KEY }}
parameters.appServiceSettings.value.SCOPE: ${{ secrets.SCOPE}}

- name: Deploy App Service Plan and Web App
uses: azure/arm-deploy@v1
Expand Down
3 changes: 2 additions & 1 deletion src/goapp/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ EMAIL_USER_ID=<Email user id>
LINK_FOOTERS=""
ORGANIZATION_NAME=""
COMMUNITY_PORTAL_APP_ID=""
SESSION_KEY=""
SESSION_KEY=""
SCOPE=""
1 change: 1 addition & 0 deletions src/goapp/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ type ConfigManager interface {
GetCallbackRetryFreq() string
GetPort() string
GetSessionKey() string
GetScope() string
}
4 changes: 4 additions & 0 deletions src/goapp/config/env-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ func (ecm *envConfigManager) GetPort() string {
func (ecm *envConfigManager) GetSessionKey() string {
return os.Getenv("SESSION_KEY")
}

func (ecm *envConfigManager) GetScope() string {
return os.Getenv("SCOPE")
}
40 changes: 38 additions & 2 deletions src/goapp/controller/item/item-controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"main/service"
"net/http"
"strconv"
"time"

"github.com/gorilla/mux"
)
Expand Down Expand Up @@ -260,10 +261,28 @@ func (c *itemController) postCallback(id string) {

jsonReq, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshalling response callback: ", err)
return
}

res, err := http.Post(item.CallbackUrl, "application/json", bytes.NewBuffer(jsonReq))
token, err := c.Authenticator.GenerateToken()
if err != nil {
fmt.Println("Error generating token: ", err)
return
}

req, err := http.NewRequest("POST", item.CallbackUrl, bytes.NewBuffer(jsonReq))
if err != nil {
return
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)

client := &http.Client{
Timeout: time.Second * 90,
}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error posting callback: ", err)
return
Expand All @@ -288,7 +307,24 @@ func (c *itemController) postCallbackReassignItem(data ReassignItemCallback) {
return
}

_, err = http.Post(res.ReassignCallbackUrl, "application/json", bytes.NewBuffer(jsonReq))
token, err := c.Authenticator.GenerateToken()
if err != nil {
fmt.Println("Error generating token: ", err)
return
}

req, err := http.NewRequest("POST", res.ReassignCallbackUrl, bytes.NewBuffer(jsonReq))
if err != nil {
return
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)

client := &http.Client{
Timeout: time.Second * 90,
}
_, err = client.Do(req)
if err != nil {
fmt.Println("Error posting callback: ", err)
return
Expand Down
2 changes: 1 addition & 1 deletion src/goapp/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ var (
timedJobs = t.NewTimedJobs(svc, conf)

m middleware.Middleware = middleware.NewMiddleware(svc)
httpRouter router.Router = router.NewMuxRouter(ctrl, conf)
httpRouter router.Router = router.NewMuxRouter(ctrl, conf, &m)
)
7 changes: 5 additions & 2 deletions src/goapp/router/mux-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"main/config"
"main/controller"
"main/middleware"

"github.com/gorilla/mux"
"github.com/unrolled/secure"
Expand All @@ -15,12 +16,14 @@ import (
type muxRouter struct {
*controller.Controller
Port string
m middleware.Middleware
}

func NewMuxRouter(c *controller.Controller, conf config.ConfigManager) Router {
func NewMuxRouter(c *controller.Controller, conf config.ConfigManager, m *middleware.Middleware) Router {
return &muxRouter{
Controller: c,
Port: conf.GetPort(),
m: *m,
}
}

Expand Down Expand Up @@ -64,7 +67,7 @@ func (r *muxRouter) SERVE() {
muxDispatcher.Use(secureMiddleware.Handler)
http.Handle("/", muxDispatcher)

muxDispatcher.NotFoundHandler = http.HandlerFunc(r.Controller.Fallback.NotFound)
muxDispatcher.NotFoundHandler = http.HandlerFunc(r.m.Chain(r.Controller.Fallback.NotFound, r.m.AzureAuth()))
muxDispatcher.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir("./public/"))))

fmt.Printf("Mux HTTP server running on port %v", r.Port)
Expand Down
4 changes: 2 additions & 2 deletions src/goapp/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ func setPageRoutes() {

func setApiRoutes() {
httpRouter.GET("/api/request/types", m.Chain(ctrl.ApplicationModule.GetRequestTypes, m.AzureAuth()))
httpRouter.POST("/api/request", ctrl.Item.CreateItem)
httpRouter.POST("/api/process", ctrl.Item.ProcessResponse)
httpRouter.POST("/api/request", m.Chain(ctrl.Item.CreateItem, m.ManagedIdentityAuth()))
httpRouter.POST("/api/process", m.Chain(ctrl.Item.ProcessResponse, m.AzureAuth()))
httpRouter.GET("/api/items/type/{type:[0-2]+}/status/{status:[0-3]+}", m.Chain(ctrl.Item.GetItems, m.AzureAuth()))
httpRouter.GET("/api/search/users/{search}", m.Chain(ctrl.User.SearchUserFromActiveDirectory, m.AzureAuth()))
httpRouter.GET("/api/responsereassignedapi/{itemGuid}/{approver}/{ApplicationId}/{ApplicationModuleId}/{ApproveText}/{RejectText}", m.Chain(ctrl.Item.ReassignItem, m.AzureAuth()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
type AuthenticatorService interface {
AccessTokenIsValid(r *http.Request) bool
ClearFromSession(w *http.ResponseWriter, r *http.Request, session string) error
GenerateToken() (string, error)
GetAuthCodeURL(state string) string
GetAuthenticatedUser(r *http.Request) (*model.AzureUser, error)
GetLogoutURL() (string, error)
Expand Down
41 changes: 41 additions & 0 deletions src/goapp/service/authenticator/authenticator-service.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"main/model"
"net/http"
"net/url"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -102,6 +103,46 @@ func (a *authenticatorService) ClearFromSession(w *http.ResponseWriter, r *http.
return nil
}

func (a *authenticatorService) GenerateToken() (string, error) {
urlPath := fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", a.Config.GetTenantID())
client := &http.Client{
Timeout: time.Second * 10,
}

data := url.Values{}
data.Set("client_id", a.Config.GetClientID())
data.Set("scope", a.Config.GetScope())
data.Set("client_secret", a.Config.GetClientSecret())
data.Set("grant_type", "client_credentials")
ecodedData := data.Encode()

req, err := http.NewRequest("POST", urlPath, strings.NewReader(ecodedData))
if err != nil {
return "", err
}

req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
response, err := client.Do(req)
if err != nil {
return "", err
}
defer response.Body.Close()

var token struct {
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
ExtExpiresIn int `json:"ext_expires_in"`
AccessToken string `json:"access_token"`
}
err = json.NewDecoder(response.Body).Decode(&token)
if err != nil {
return "", err
}

return token.AccessToken, nil
}

func (a *authenticatorService) GetAuthCodeURL(state string) string {
return a.OAuthConfig.AuthCodeURL(state)
}
Expand Down
19 changes: 18 additions & 1 deletion src/goapp/timed-jobs/timed-jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,24 @@ func (t *timedJobs) postCallback(id string) {
return
}

res, err := http.Post(item.CallbackUrl, "application/json", bytes.NewBuffer(jsonReq))
token, err := t.Service.Authenticator.GenerateToken()
if err != nil {
fmt.Println("Error generating token: ", err)
return
}

req, err := http.NewRequest("POST", item.CallbackUrl, bytes.NewBuffer(jsonReq))
if err != nil {
return
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)

client := &http.Client{
Timeout: time.Second * 90,
}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error posting callback: ", err)
return
Expand Down
Loading