Skip to content

Commit

Permalink
Add Authentication to NOT FOUND Page
Browse files Browse the repository at this point in the history
Signed-off-by: Jerrico Dela Cruz <[email protected]>
  • Loading branch information
jerricotandelacruz committed Oct 28, 2024
1 parent 05276d0 commit aa4823b
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 25 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/docker-build-and-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ jobs:
username: ${{ secrets.CONTAINER_REGISTRY_SERVER_USERNAME }}
password: ${{ secrets.CONTAINER_REGISTRY_SERVER_PASSWORD }}
- run: |
docker build . -t ${{ secrets.CONTAINER_REGISTRY_SERVER }}/${{ vars.APPSERVICE_NAME }}:${{ github.sha }} -t ${{ secrets.CONTAINER_REGISTRY_SERVER }}/${{ vars.APPSERVICE_NAME }}:latest
docker build . -t ${{ secrets.CONTAINER_REGISTRY_SERVER }}/${{ vars.APPSERVICE_NAME }}:${{ github.sha }} -t ${{ secrets.CONTAINER_REGISTRY_SERVER }}/${{ vars.APPSERVICE_NAME }}:${{ github.sha }}
docker push ${{ secrets.CONTAINER_REGISTRY_SERVER }}/${{ vars.APPSERVICE_NAME }}
17 changes: 12 additions & 5 deletions src/goapp/router/mux-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import (
"net/http"
"os"

rtPages "main/routes/pages"

"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/unrolled/secure"
)

type muxRouter struct{}
type muxRouter struct {
NotFoundHandler http.HandlerFunc
}

func NewMuxRouter() Router {
return &muxRouter{}
Expand All @@ -38,7 +38,11 @@ func (*muxRouter) DELETE(uri string, f func(resp http.ResponseWriter, req *http.
muxDispatcher.HandleFunc(uri, f).Methods("DELETE")
}

func (*muxRouter) SERVE(port string) {
func (mr *muxRouter) NOTFOUND(f func(resp http.ResponseWriter, req *http.Request)) {
mr.NotFoundHandler = http.HandlerFunc(f)
}

func (mr *muxRouter) SERVE(port string) {
secureOptions := secure.Options{
SSLRedirect: true, // Strict-Transport-Security
SSLHost: os.Getenv("SSL_HOST"), // Strict-Transport-Security
Expand Down Expand Up @@ -73,7 +77,10 @@ func (*muxRouter) SERVE(port string) {
)
http.Handle("/", muxDispatcher)

muxDispatcher.NotFoundHandler = http.HandlerFunc(rtPages.NotFoundHandler)
if mr.NotFoundHandler != nil {
muxDispatcher.NotFoundHandler = mr.NotFoundHandler
}

muxDispatcher.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir("./public/"))))

fmt.Printf("Mux HTTP server running on port %v", port)
Expand Down
1 change: 1 addition & 0 deletions src/goapp/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ type Router interface {
POST(uri string, f func(resp http.ResponseWriter, req *http.Request))
PUT(uri string, f func(resp http.ResponseWriter, req *http.Request))
DELETE(uri string, f func(resp http.ResponseWriter, req *http.Request))
NOTFOUND(f func(resp http.ResponseWriter, req *http.Request))
SERVE(port string)
}
2 changes: 2 additions & 0 deletions src/goapp/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
)

func setPageRoutes() {
httpRouter.NOTFOUND(m.Chain(rtPages.NotFoundHandler))

httpRouter.GET("/", m.Chain(rtPages.HomeHandler, m.AzureAuth()))
httpRouter.GET("/error/ghlogin", m.Chain(rtPages.GHLoginRequire, m.AzureAuth()))

Expand Down
32 changes: 13 additions & 19 deletions src/goapp/routes/login/azure/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,56 +3,54 @@ package routes
import (
"context"
"fmt"
"log"
"net/http"
"os"

"github.com/coreos/go-oidc"
"github.com/gorilla/sessions"

"main/pkg/appinsights_wrapper"
auth "main/pkg/authentication"
db "main/pkg/ghmgmtdb"
"main/pkg/msgraph"
"main/pkg/session"
)

func CallbackHandler(w http.ResponseWriter, r *http.Request) {

logger := appinsights_wrapper.NewClient()
defer logger.EndOperation()
// Check session
session, err := session.Store.Get(r, "auth-session")
if err != nil {
log.Println(err.Error())
// http.Error(w, err.Error(), http.StatusInternalServerError)
logger.LogException(err)
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}

if r.URL.Query().Get("state") != session.Values["state"] {
// http.Error(w, "Invalid state parameter", http.StatusBadRequest)
logger.LogException(fmt.Errorf("invalid state parameter"))
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}

//Retrieve token
authenticator, err := auth.NewAuthenticator(r.Host)
if err != nil {
log.Println(err.Error())
// http.Error(w, err.Error(), http.StatusInternalServerError)
logger.LogException(err)
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}

token, err := authenticator.Config.Exchange(context.TODO(), r.URL.Query().Get("code"))
if err != nil {
log.Printf("no token found: %v", err)
// w.WriteHeader(http.StatusUnauthorized)
logger.LogException(fmt.Errorf("no token found: %v", err))
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}

rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
// http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
logger.LogException(fmt.Errorf("no id_token field in oauth2 token"))
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}
Expand All @@ -64,16 +62,15 @@ func CallbackHandler(w http.ResponseWriter, r *http.Request) {
idToken, err := authenticator.Provider.Verifier(oidcConfig).Verify(context.TODO(), rawIDToken)

if err != nil {
// http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
logger.LogException(fmt.Errorf("failed to verify ID Token: %v", err))
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}

// Get the userInfo
var profile map[string]interface{}
if err := idToken.Claims(&profile); err != nil {
log.Println(err.Error())
// http.Error(w, err.Error(), http.StatusInternalServerError)
logger.LogException(err)
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}
Expand All @@ -89,8 +86,7 @@ func CallbackHandler(w http.ResponseWriter, r *http.Request) {
session.Values["isUserAdmin"] = isAdmin
hasPhoto, userPhoto, err := msgraph.GetUserPhoto(fmt.Sprintf("%s", profile["oid"]))
if err != nil {
log.Println(err.Error())
// http.Error(w, err.Error(), http.StatusInternalServerError)
logger.LogException(err)
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}
Expand All @@ -108,8 +104,7 @@ func CallbackHandler(w http.ResponseWriter, r *http.Request) {
}
err = session.Save(r, w)
if err != nil {
log.Println(err.Error())
// http.Error(w, err.Error(), http.StatusInternalServerError)
logger.LogException(err)
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}
Expand All @@ -118,8 +113,7 @@ func CallbackHandler(w http.ResponseWriter, r *http.Request) {
name := fmt.Sprint(profile["name"])
err = db.InsertUser(userPrincipalName, name, "", "", "")
if err != nil {
log.Println(err.Error())
// http.Error(w, err.Error(), http.StatusInternalServerError)
logger.LogException(err)
http.Redirect(w, r, "/authentication/azure/failed", http.StatusSeeOther)
return
}
Expand Down

0 comments on commit aa4823b

Please sign in to comment.