go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/web/rpcexplorer/src/components/auth_selector.tsx (about) 1 // Copyright 2022 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 import FormControl from '@mui/material/FormControl'; 16 import FormControlLabel from '@mui/material/FormControlLabel'; 17 import Radio from '@mui/material/Radio'; 18 import RadioGroup from '@mui/material/RadioGroup'; 19 20 // How to authenticate an RPC request. 21 export enum AuthMethod { 22 // Do not send any credentials. 23 Anonymous = 'anonymous', 24 // Send an OAuth access token. 25 OAuth = 'oauth', 26 } 27 28 /* eslint-disable-next-line @typescript-eslint/no-namespace */ 29 export namespace AuthMethod { 30 const storeKey = 'auth_selector.AuthMethod'; 31 32 // Loads an AuthMethod from the local storage. 33 export const load = (): AuthMethod => { 34 const item = localStorage.getItem(storeKey); 35 if (item && Object.values(AuthMethod).includes(item as AuthMethod)) { 36 return item as AuthMethod; 37 } 38 return AuthMethod.OAuth; // default 39 }; 40 41 // Stores AuthMethod into the local storage. 42 export const store = (val: AuthMethod) => { 43 localStorage.setItem(storeKey, val as string); 44 }; 45 } 46 47 48 export interface Props { 49 selected: AuthMethod; 50 onChange: (method: AuthMethod) => void; 51 disabled?: boolean, 52 anonOnly?: boolean, 53 } 54 55 // Allows to select an authentication method to use for sending RPCs. 56 export const AuthSelector = (props: Props) => { 57 const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { 58 props.onChange((event.target as HTMLInputElement).value as AuthMethod); 59 }; 60 61 // If only anonymous method is supported, force the selection to it. 62 let selected = props.selected; 63 if (props.anonOnly) { 64 selected = AuthMethod.Anonymous; 65 } 66 67 return ( 68 <FormControl disabled={props.disabled}> 69 <RadioGroup row value={selected} onChange={handleChange}> 70 <FormControlLabel 71 value={AuthMethod.Anonymous} 72 control={<Radio />} 73 label='Call anonymously' 74 /> 75 <FormControlLabel 76 value={AuthMethod.OAuth} 77 control={<Radio />} 78 label='Use OAuth access tokens' 79 disabled={props.anonOnly} 80 /> 81 </RadioGroup> 82 </FormControl> 83 ); 84 };