Elffuss BraidHub

kikocis/ecs-apigateway-sample public

b65454d73c29 · 7.9 KiBRawPermalink
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: MIT
3
4import React from 'react'
5import { Amplify, Auth } from 'aws-amplify'
6import { AmplifyAuthenticator, AmplifySignOut, AmplifySignUp } from '@aws-amplify/ui-react'
7import { onAuthUIStateChange } from '@aws-amplify/ui-components'
8import awsconfig from './aws-exports'
9import axios from 'axios'
10
11const searchParams = new URLSearchParams( window.location.search )
12const searchParamsList = {
13 regionID: searchParams.get('stackregion'),
14 HttpApiID: searchParams.get('stackhttpapi'),
15 UserPoolID: searchParams.get('stackuserpool'),
16 UserPoolClientID: searchParams.get('stackuserpoolclient'),
17}
18if( !searchParamsList.regionID.match(/^[a-zA-Z0-9\-]+$/) ){ throw new Error('Invalid Region ID!!'); }
19if( !searchParamsList.HttpApiID.match(/^[a-zA-Z0-9\-]+$/) ){ throw new Error('Invalid API ID!!'); }
20awsconfig.Auth = {
21 region: searchParamsList.regionID,
22 userPoolId: searchParamsList.UserPoolID,
23 userPoolWebClientId: searchParamsList.UserPoolClientID
24}
25Amplify.configure(awsconfig)
26
27var MyPropsMethods = {}
28
29const App = () => {
30
31 const [acceptState, setAcceptState] = React.useState(false)
32
33 return (
34 !acceptState
35 ? <div style={{textAlign: 'center', margin: '1em 0 0 0'}}>
36 <h2>Only proceed if you opened this link from the CloudFormation Outputs of the stack described in the AWS Blog</h2>
37 <button onClick={ e => setAcceptState(true) } style={{fontSize: '1em'}} >Proceed</button>
38 </div>
39 : <MyAuth />
40 )
41
42}
43
44const MyAuth = () => {
45
46 const [authState, setAuthState] = React.useState()
47 const [showLogin, setShowLogin] = React.useState(false)
48 const goToSignIn = () => setShowLogin(true)
49 const exitFromSignIn = () => setShowLogin(false)
50 const showAuthenticator = (showLogin || authState == 'signedin')
51 const showApp = (!showLogin || authState == 'signedin')
52 const showgoToSignIn = !(showLogin || authState == 'signedin') && authState != null
53
54 React.useEffect(() => {
55 return onAuthUIStateChange(newAuthState => {
56 setAuthState(newAuthState)
57 if(newAuthState=='signedin'){
58 setShowLogin(false)
59 }
60 })
61 }, [])
62
63 return (
64 <div>
65
66 <div style={{
67 display: showAuthenticator ? '' : 'none',
68 textAlign: 'center'
69 }}>
70 <div style={{ display: authState != 'signedin' ? '' : 'none', margin: '1em 0' }}>
71 <button onClick={exitFromSignIn} style={{fontSize: '1em'}} >Back to the Application!</button>
72 </div>
73 <AmplifyAuthenticator usernameAlias="email">
74 <AmplifySignUp
75 slot="sign-up"
76 usernameAlias="email"
77 formFields={[
78 { type: "email", required: true, },
79 { type: "password", required: true, },
80 ]}
81 ></AmplifySignUp>
82 <AmplifySignOut />
83 </AmplifyAuthenticator>
84 </div>
85
86 { showApp &&
87 <div style={{ textAlign: 'center', margin: '1em 0 0 0' }}>
88 { showgoToSignIn && <button onClick={goToSignIn} style={{fontSize: '1em'}} >Go to Sign In!</button> }
89 <ApiForm
90 authState={authState}
91 />
92 </div>
93 }
94
95 </div>
96 )
97
98}
99
100MyPropsMethods.APIProperties = {
101 'foodstore/foods/':['foodId'],
102 'petstore/pets/':['petId'],
103}
104
105const ApiForm = (props) => {
106
107 const [selectedMethod, setSelectedMethod] = React.useState()
108 const [selectedAPI, setSelectedAPI] = React.useState()
109 const [selectedVariable, setSelectedVariable] = React.useState()
110 const [selectedPayload, setSelectedPayload] = React.useState()
111
112 const handleMethodChange = (e) => setSelectedMethod(e.target.value)
113 const handleAPIChange = (e) => setSelectedAPI(e.target.value)
114 const handleVariableChange = (e) => setSelectedVariable(e.target.value)
115 const handlePayloadChange = (e) => setSelectedPayload( selectedMethod == 'GET' ? undefined : e.target.value )
116
117 const pathVariable = selectedAPI ? MyPropsMethods.APIProperties[selectedAPI][0] : ''
118
119 const enableFormSubmission = !!( selectedMethod && selectedAPI && selectedVariable && ( selectedMethod == 'GET' || selectedPayload ) )
120
121 return (
122 <div style={{ margin: '1em 0 0 0' }}>
123 <form onSubmit={ (e) => MyPropsMethods.invokeAPI(e,enableFormSubmission, selectedMethod, selectedAPI, selectedVariable, selectedPayload, props.authState) }>
124 <h2>
125 { props.authState == 'signedin'
126 ? <span>Looks like you're <u style={{color:"#00bb00"}}>signed in!</u></span>
127 : <span>Looks like you're <u style={{color:"red"}}>NOT signed in</u></span>
128 }
129 </h2>
130 <h3>
131 { props.authState == 'signedin'
132 ? <span>You should be able to invoke <span style={{color:"#00bb00"}}>GET</span> and also <span style={{color:"#00bb00"}}>PUT</span>. Try it out!</span>
133 : <span>You should be able to invoke <span style={{color:"#00bb00"}}>GET</span> but not <span style={{color:"red"}}>PUT</span>. Try it out!</span>
134 }
135 </h3>
136 <br />
137 <div>
138 <b>Method:</b>
139 <div onChange={handleMethodChange}>
140 <input type="radio" value="PUT" name="method" id="PUT"/>
141 <label htmlFor="PUT"> PUT</label><br />
142 <input type="radio" value="GET" name="method" id="GET"/>
143 <label htmlFor="GET"> GET</label><br />
144 </div>
145 </div>
146 <br />
147 <div>
148 <b>API:</b>
149 <div onChange={handleAPIChange}>
150 <input type="radio" value="foodstore/foods/" name="api" id="foodstore/foods/"/>
151 <label htmlFor="foodstore/foods/"> /foodstore/foods/{'{foodId}'}</label><br />
152 <input type="radio" value="petstore/pets/" name="api" id="petstore/pets/"/>
153 <label htmlFor="petstore/pets/"> /petstore/pets/{'{petId}'}</label><br />
154 </div>
155 </div>
156 <br />
157 <div style={{ display: selectedAPI ? '' : 'none' }}>
158 <b id="path-variable-label">{'{'+pathVariable+'}'}:</b><br />
159 <input type="text" name="variable" style={{fontSize: '1em'}} onChange={handleVariableChange}/>
160 </div>
161 <br />
162 <div style={{ display: selectedMethod=='PUT' ? '' : 'none' }} >
163 <b id="path-variable-label">Body (JSON):</b><br />
164 <textarea name="payload" rows="10" style={{fontSize: '1em', maxWidth: '90%', width: '500px'}} onChange={handlePayloadChange}/>
165 </div>
166 <br />
167
168 <input type="submit" value="Invoke!" style={{ fontSize: '1em' }} />
169
170 </form>
171 </div>
172 )
173
174}
175
176MyPropsMethods.invokeAPI = ( e, enableFormSubmission, selectedMethod, selectedAPI, selectedVariable, selectedPayload, authState ) => {
177
178 e.preventDefault()
179 if( !enableFormSubmission ) return alert("Error: All fields are mandatory.")
180
181 if( authState == 'signedin' ){
182 Auth.currentSession().then( tokens => {
183 MyPropsMethods.AjaxCall( selectedMethod, selectedAPI, selectedVariable, selectedPayload, tokens.accessToken.jwtToken )
184 })
185 } else{
186 MyPropsMethods.AjaxCall( selectedMethod, selectedAPI, selectedVariable, selectedPayload )
187 }
188
189}
190
191MyPropsMethods.AjaxCall = ( selectedMethod, selectedAPI, selectedVariable, selectedPayload, jwtToken ) => {
192
193 const invokeURL = `https://${searchParamsList.HttpApiID}.execute-api.${searchParamsList.regionID}.amazonaws.com/${selectedAPI}${selectedVariable}`
194 const reqHeaders = jwtToken ? { authorization: jwtToken } : undefined
195
196 try {
197 selectedPayload = selectedPayload ? JSON.parse(selectedPayload): selectedPayload
198 if (Object.prototype.toString.call(selectedPayload) === '[object Array]') throw new Error();
199 } catch (e) {
200 return alert("Error: Body is NOT a valid JSON.");
201 }
202
203 axios({
204 method: selectedMethod,
205 url: invokeURL,
206 data: selectedPayload,
207 headers: reqHeaders
208 })
209 .then( response => {
210 alert(JSON.stringify(response.data))
211 }).catch( error => {
212 alert( error )
213 })
214
215}
216
217export default App