Skip to content
This repository has been archived by the owner on Apr 11, 2023. It is now read-only.

Commit

Permalink
feat: setup UI endpoint to serve the UI
Browse files Browse the repository at this point in the history
closes #39

Signed-off-by: talwinder.kaur <[email protected]>
  • Loading branch information
talwinder50 committed Jul 30, 2020
1 parent 439e45a commit a67a122
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 11 deletions.
28 changes: 27 additions & 1 deletion cmd/auth-rest/startcmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ const (
" For CouchDB, include the username:password@ text if required." +
" Alternatively, this can be set with the following environment variable: " + databaseURLEnvKey

staticFilesPathFlagName = "static-path"
staticFilesPathFlagUsage = "Path to the folder where the static files are to be hosted under " + uiEndpoint + "." +
"Alternatively, this can be set with the following environment variable: " + staticFilesPathEnvKey
staticFilesPathEnvKey = "AUTH_REST_STATIC_FILES"

databasePrefixFlagName = "database-prefix"
databasePrefixEnvKey = "AUTH_REST_DATABASE_PREFIX"
databasePrefixFlagShorthand = "p"
Expand Down Expand Up @@ -129,6 +134,7 @@ const (

const (
// api
uiEndpoint = "/ui"
healthCheckEndpoint = "/healthcheck"
)

Expand All @@ -143,6 +149,7 @@ type authRestParameters struct {
tlsParams *tlsParams
oidcParams *oidcParams
bootstrapParams *bootstrapParams
staticFiles string
}

type tlsParams struct {
Expand Down Expand Up @@ -311,6 +318,7 @@ func createFlags(startCmd *cobra.Command) {
startCmd.Flags().StringP(tlsServeCertPathFlagName, "", "", tlsServeCertPathFlagUsage)
startCmd.Flags().StringP(tlsServeKeyPathFlagName, "", "", tlsServeKeyPathFlagUsage)
startCmd.Flags().StringP(logLevelFlagName, logLevelFlagShorthand, "", logLevelPrefixFlagUsage)
startCmd.Flags().StringP(staticFilesPathFlagName, "", "", staticFilesPathFlagUsage)
startCmd.Flags().StringP(databaseTypeFlagName, databaseTypeFlagShorthand, "", databaseTypeFlagUsage)
startCmd.Flags().StringP(databaseURLFlagName, databaseURLFlagShorthand, "", databaseURLFlagUsage)
startCmd.Flags().StringP(databasePrefixFlagName, databasePrefixFlagShorthand, "", databasePrefixFlagUsage)
Expand Down Expand Up @@ -340,7 +348,6 @@ func startAuthService(parameters *authRestParameters, srv server) error {
logger.Debugf("root ca's %v", rootCAs)

router := mux.NewRouter()

// health check
router.HandleFunc(healthCheckEndpoint, healthCheckHandler).Methods(http.MethodGet)

Expand Down Expand Up @@ -374,6 +381,12 @@ Database type: %s
Database URL: %s
Database prefix: %s`, parameters.hostURL, parameters.databaseType, parameters.databaseURL, parameters.databasePrefix)

// static frontend
router.PathPrefix(uiEndpoint).
Subrouter().
Methods(http.MethodGet).
HandlerFunc(uiHandler(parameters.staticFiles, http.ServeFile))

return srv.ListenAndServeTLS(
parameters.hostURL,
parameters.tlsParams.serveCertPath,
Expand All @@ -382,6 +395,19 @@ Database prefix: %s`, parameters.hostURL, parameters.databaseType, parameters.da
)
}

func uiHandler(
basePath string,
fileServer func(http.ResponseWriter, *http.Request, string)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == uiEndpoint {
fileServer(w, r, strings.ReplaceAll(basePath+"/index.html", "//", "/"))
return
}

fileServer(w, r, strings.ReplaceAll(basePath+"/"+r.URL.Path[len(uiEndpoint):], "//", "/"))
}
}

func getOIDCParams(cmd *cobra.Command) (*oidcParams, error) {
params := &oidcParams{}

Expand Down
35 changes: 35 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 26 additions & 10 deletions pkg/restapi/operation/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import (
"encoding/json"
"errors"
"fmt"

"net/http"
"net/url"

"github.com/coreos/go-oidc"
oidc "github.com/coreos/go-oidc"
"github.com/google/uuid"
"github.com/trustbloc/edge-core/pkg/log"
"github.com/trustbloc/edge-core/pkg/storage"
Expand Down Expand Up @@ -116,6 +118,7 @@ type Operation struct {
oidcClientID string
oidcClientSecret string
oidcCallbackURL string
uiEndpoint string
oauth2ConfigFunc func(...string) oauth2Config
bootstrapStore storage.Store
bootstrapConfig *BootstrapConfig
Expand All @@ -129,6 +132,7 @@ type Config struct {
OIDCClientID string
OIDCClientSecret string
OIDCCallbackURL string
UIEndpoint string
TransientStoreProvider storage.Provider
StoreProvider storage.Provider
BootstrapConfig *BootstrapConfig
Expand All @@ -140,7 +144,7 @@ type BootstrapConfig struct {
KeyServerURL string
}

// New returns rp operation instance.
// New returns hub-auth operation instance.
func New(config *Config) (*Operation, error) {
svc := &Operation{
client: &http.Client{Transport: &http.Transport{TLSClientConfig: config.TLSConfig}},
Expand All @@ -149,6 +153,7 @@ func New(config *Config) (*Operation, error) {
oidcClientSecret: config.OIDCClientSecret,
oidcCallbackURL: config.OIDCCallbackURL,
bootstrapConfig: config.BootstrapConfig,
uiEndpoint: config.UIEndpoint,
}

// TODO implement retries: https://github.com/trustbloc/hub-auth/issues/45
Expand Down Expand Up @@ -329,7 +334,15 @@ func (c *Operation) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
return
}

handleAuthResult(w, r, userProfile)
profileBytes, err := json.Marshal(userProfile)
if err != nil {
c.writeErrorResponse(w, http.StatusInternalServerError,
fmt.Sprintf("failed to marshal user profile data : %s", err))

return
}

c.handleAuthResult(w, r, profileBytes)
}

// TODO onboard user at key server and SDS: https://github.com/trustbloc/hub-auth/issues/38
Expand Down Expand Up @@ -365,9 +378,6 @@ func (c *Operation) handleBootstrapDataRequest(w http.ResponseWriter, r *http.Re
handleAuthError(w, http.StatusInternalServerError,
fmt.Sprintf("failed to query transient store for handle: %s", err))

return
}

response, err := json.Marshal(&bootstrapData{
SDSURL: c.bootstrapConfig.SDSURL,
SDSPrimaryVaultID: profile.SDSPrimaryVaultID,
Expand All @@ -388,10 +398,16 @@ func (c *Operation) handleBootstrapDataRequest(w http.ResponseWriter, r *http.Re
}
}

// TODO redirect to the UI: https://github.com/trustbloc/hub-auth/issues/39
func handleAuthResult(w http.ResponseWriter, r *http.Request, _ *user.Profile) {
http.Redirect(w, r, "", http.StatusFound)
}
func (c *Operation) handleAuthResult(w http.ResponseWriter, r *http.Request, profileBytes []byte) {
handle := url.QueryEscape(uuid.New().String())

err := c.transientStore.Put(handle, profileBytes)
if err != nil {
c.writeErrorResponse(w,
http.StatusInternalServerError, fmt.Sprintf("failed to write handle to transient store : %s", err))

return
}

func handleAuthError(w http.ResponseWriter, status int, msg string) {
// todo #issue-25 handle user data
Expand Down
24 changes: 24 additions & 0 deletions pkg/restapi/operation/operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,30 @@ func TestHandleOIDCCallback(t *testing.T) {
svc.handleOIDCCallback(result, newOIDCCallback(state, "code"))
require.Equal(t, http.StatusInternalServerError, result.Code)
})
t.Run("PUT error while storing user info while handling callback user", func(t *testing.T) {
id := uuid.New().String()
state := uuid.New().String()
config := config(t)

config.TransientStoreProvider = &mockstorage.Provider{
Stores: map[string]storage.Store{
transientStoreName: &mockstore.MockStore{
Store: map[string][]byte{
id: []byte("{}"),
},
ErrGet: storage.ErrValueNotFound,
ErrPut: errors.New("generic"),
},
},
}

svc, err := New(config)
require.NoError(t, err)

result := httptest.NewRecorder()
svc.handleAuthResult(result, newOIDCCallback(state, "code"), nil)
require.Equal(t, http.StatusInternalServerError, result.Code)
})
}

func TestHandleBootstrapDataRequest(t *testing.T) {
Expand Down

0 comments on commit a67a122

Please sign in to comment.