Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
refactor: auth
liyasthomas971b35a25266
diff --git a/components/http/Auth.vue b/components/http/Auth.vuenew file mode 100644index 000000000..57079561e--- /dev/null+++ b/components/http/Auth.vue@@ -0,0 +1,171 @@+<template>+ <div>+ <div class="flex flex-1 p-2 items-center justify-between">+ <tippy+ ref="authTypeOptions"+ interactive+ trigger="click"+ theme="popover"+ arrow+ >+ <template #trigger>+ <div class="flex">+ <span class="select-wrapper">+ <ButtonSecondary+ class="pr-8"+ :label="`${$t('authentication')}: ${authType}`"+ outline+ />+ </span>+ </div>+ </template>+ <SmartItem+ label="None"+ @click.native="+ authType = 'none'+ $refs.authTypeOptions.tippy().hide()+ "+ />+ <SmartItem+ label="Basic"+ @click.native="+ authType = 'basic'+ $refs.authTypeOptions.tippy().hide()+ "+ />+ <SmartItem+ label="Bearer"+ @click.native="+ authType = 'bearer'+ $refs.authTypeOptions.tippy().hide()+ "+ />+ </tippy>+ <ButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="$t('clear')"+ icon="clear_all"+ @click.native="clearContent"+ />+ </div>+ <div v-if="authType === 'basic'" class="space-y-2 p-2">+ <div class="flex relative">+ <input+ id="http_basic_user"+ v-model="basicUsername"+ class="input floating-input"+ placeholder=" "+ name="http_basic_user"+ />+ <label for="http_basic_user">+ {{ $t("username") }}+ </label>+ </div>+ <div class="flex relative">+ <input+ id="http_basic_passwd"+ v-model="basicPassword"+ class="input floating-input"+ placeholder=" "+ name="http_basic_passwd"+ :type="passwordFieldType"+ />+ <label for="http_basic_passwd">+ {{ $t("password") }}+ </label>+ <ButtonSecondary+ :icon="passwordFieldType === 'text' ? 'visibility' : 'visibility_off'"+ outline+ class="ml-2"+ @click.native="switchVisibility"+ />+ </div>+ </div>+ <div v-if="authType === 'bearer'" class="space-y-2 p-2">+ <div class="flex relative">+ <input+ id="bearer_token"+ v-model="bearerToken"+ class="input floating-input"+ placeholder=" "+ name="bearer_token"+ />+ <label for="bearer_token"> Token </label>+ </div>+ </div>+ <!-- <button+ v-if="authType === 'OAuth 2.0'"+ v-tooltip.bottom="$t('use_token')"+ class="icon button"+ @click="showTokenListModal = !showTokenListModal"+ >+ <i class="material-icons">open_in_new</i>+ </button> -->+ <!-- <button+ v-if="authType === 'OAuth 2.0'"+ v-tooltip.bottom="$t('get_token')"+ class="icon button"+ @click="showTokenRequest = !showTokenRequest"+ >+ <i class="material-icons">vpn_key</i>+ </button> -->+ <!-- <SmartToggle+ :on="!URL_EXCLUDES.auth"+ @change="setExclude('auth', !$event)"+ >+ {{ $t("include_in_url") }}+ </SmartToggle> -->+ </div>+</template>++<script lang="ts">+import { defineComponent, Ref, ref } from "@nuxtjs/composition-api"+import {+ HoppRESTAuthBasic,+ HoppRESTAuthBearer,+} from "~/helpers/types/HoppRESTAuth"+import { pluckRef, useStream } from "~/helpers/utils/composables"+import { restAuth$, setRESTAuth } from "~/newstore/RESTSession"+import { useSetting } from "~/newstore/settings"++export default defineComponent({+ setup() {+ const auth = useStream(restAuth$, { authType: "none" }, setRESTAuth)++ const authType = pluckRef(auth, "authType")++ const basicUsername = pluckRef(auth as Ref<HoppRESTAuthBasic>, "username")+ const basicPassword = pluckRef(auth as Ref<HoppRESTAuthBasic>, "password")++ const bearerToken = pluckRef(auth as Ref<HoppRESTAuthBearer>, "token")++ const URLExcludes = useSetting("URL_EXCLUDES")++ const passwordFieldType = ref("text")++ const clearContent = () => {+ auth.value = {+ authType: "none",+ }+ }++ const switchVisibility = () => {+ if (passwordFieldType.value === "text")+ passwordFieldType.value = "password"+ else passwordFieldType.value = "text"+ }++ return {+ auth,+ authType,+ basicUsername,+ basicPassword,+ bearerToken,+ URLExcludes,+ passwordFieldType,+ clearContent,+ switchVisibility,+ }+ },+})+</script>diff --git a/components/http/CodegenModal.vue b/components/http/CodegenModal.vueindex bcab8c371..f07f4b4a9 100644--- a/components/http/CodegenModal.vue+++ b/components/http/CodegenModal.vue@@ -10,45 +10,34 @@{{ $t("request.choose_language") }}</label><div class="flex flex-1">- <span class="select-wrapper">- <tippy- ref="options"- interactive- trigger="click"- theme="popover"- arrow- >- <template #trigger>- <span- class="- bg-primaryLight- border border-dividerLight- rounded- cursor-pointer- flex- font-semibold- w-full- py-2- px-4- focus:outline-none- "- >- {{ codegens.find((x) => x.id === codegenType).name }}- </span>- </template>- <SmartItem- v-for="(gen, index) in codegens"- :key="`gen-${index}`"- :label="gen.name"- :info-icon="gen.id === codegenType ? 'done' : ''"- :active-info-icon="gen.id === codegenType"- @click.native="- codegenType = gen.id- $refs.options.tippy().hide()- "- />- </tippy>- </span>+ <tippy+ ref="options"+ interactive+ trigger="click"+ theme="popover"+ arrow+ >+ <template #trigger>+ <span class="select-wrapper">+ <ButtonSecondary+ :label="codegens.find((x) => x.id === codegenType).name"+ outline+ class="w-full"+ />+ </span>+ </template>+ <SmartItem+ v-for="(gen, index) in codegens"+ :key="`gen-${index}`"+ :label="gen.name"+ :info-icon="gen.id === codegenType ? 'done' : ''"+ :active-info-icon="gen.id === codegenType"+ @click.native="+ codegenType = gen.id+ $refs.options.tippy().hide()+ "+ />+ </tippy></div><div class="flex flex-1 justify-between"><label for="generatedCode" class="font-semibold px-4 pt-4 pb-4">@@ -120,6 +109,7 @@ export default defineComponent({const path = urlObj.pathname// TODO: Solidify+ // TODO: Implement updated auth stuffreturn codegens.find((x) => x.id === this.codegenType)!.generator({diff --git a/components/http/ImportCurl.vue b/components/http/ImportCurl.vueindex 5ff988d6d..5b84bc34e 100644--- a/components/http/ImportCurl.vue+++ b/components/http/ImportCurl.vue@@ -111,6 +111,9 @@ export default defineComponent({headers,preRequestScript: "",testScript: "",+ auth: {+ authType: "none",+ },body: {contentType: "application/json",body: "",diff --git a/helpers/types/HoppRESTAuth.ts b/helpers/types/HoppRESTAuth.tsnew file mode 100644index 000000000..8799fc2f0--- /dev/null+++ b/helpers/types/HoppRESTAuth.ts@@ -0,0 +1,21 @@+export type HoppRESTAuthNone = {+ authType: "none"+}++export type HoppRESTAuthBasic = {+ authType: "basic"++ username: string+ password: string+}++export type HoppRESTAuthBearer = {+ authType: "bearer"++ token: string+}++export type HoppRESTAuth =+ | HoppRESTAuthNone+ | HoppRESTAuthBasic+ | HoppRESTAuthBearerdiff --git a/helpers/types/HoppRESTRequest.ts b/helpers/types/HoppRESTRequest.tsindex 53e8161fc..e5d7ce9a3 100644--- a/helpers/types/HoppRESTRequest.ts+++ b/helpers/types/HoppRESTRequest.ts@@ -1,4 +1,5 @@import { ValidContentTypes } from "../utils/contenttypes"+import { HoppRESTAuth } from "./HoppRESTAuth"export const RESTReqSchemaVersion = "1"@@ -31,6 +32,8 @@ export interface HoppRESTRequest {preRequestScript: stringtestScript: string+ auth: HoppRESTAuth+body: HoppRESTReqBody}@@ -89,6 +92,8 @@ export function translateToNewRequest(x: any): HoppRESTRequest {const body = parseRequestBody(x)+ const auth = parseOldAuth(x)+const result: HoppRESTRequest = {name,endpoint,@@ -98,9 +103,32 @@ export function translateToNewRequest(x: any): HoppRESTRequest {preRequestScript,testScript,body,+ auth,v: RESTReqSchemaVersion,}return result}}++export function parseOldAuth(x: any): HoppRESTAuth {+ if (!x.auth || x.auth === "None")+ return {+ authType: "none",+ }++ if (x.auth === "Basic Auth")+ return {+ authType: "basic",+ username: x.httpUser,+ password: x.httpPassword,+ }++ if (x.auth === "Bearer Token")+ return {+ authType: "bearer",+ token: x.bearerToken,+ }++ return { authType: "none" }+}diff --git a/helpers/utils/EffectiveURL.ts b/helpers/utils/EffectiveURL.tsindex 9c9a37b4c..4f99be525 100644--- a/helpers/utils/EffectiveURL.ts+++ b/helpers/utils/EffectiveURL.ts@@ -27,24 +27,44 @@ export function getEffectiveRESTRequest(request: HoppRESTRequest,environment: Environment): EffectiveHoppRESTRequest {+ const effectiveFinalHeaders = request.headers+ .filter(+ (x) =>+ x.key !== "" && // Remove empty keys+ x.active // Only active+ )+ .map((x) => ({+ // Parse out environment template strings+ active: true,+ key: parseTemplateString(x.key, environment.variables),+ value: parseTemplateString(x.value, environment.variables),+ }))++ // Authentication+ // TODO: Support a better b64 implementation than btoa ?+ if (request.auth.authType === "basic") {+ effectiveFinalHeaders.push({+ active: true,+ key: "Authorization",+ value: `Basic ${btoa(+ `${request.auth.username}:${request.auth.password}`+ )}`,+ })+ } else if (request.auth.authType === "bearer") {+ effectiveFinalHeaders.push({+ active: true,+ key: "Authorization",+ value: `Bearer ${request.auth.token}`,+ })+ }+return {...request,effectiveFinalURL: parseTemplateString(request.endpoint,environment.variables),- effectiveFinalHeaders: request.headers- .filter(- (x) =>- x.key !== "" && // Remove empty keys- x.active // Only active- )- .map((x) => ({- // Parse out environment template strings- active: true,- key: parseTemplateString(x.key, environment.variables),- value: parseTemplateString(x.value, environment.variables),- })),+ effectiveFinalHeaders,effectiveFinalParams: request.params.filter((x) =>diff --git a/newstore/RESTSession.ts b/newstore/RESTSession.tsindex 1e90e79be..3798dde3b 100644--- a/newstore/RESTSession.ts+++ b/newstore/RESTSession.ts@@ -11,6 +11,7 @@ import {import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import { useStream } from "~/helpers/utils/composables"import { HoppTestResult } from "~/helpers/types/HoppTestResult"+import { HoppRESTAuth } from "~/helpers/types/HoppRESTAuth"function getParamsInURL(url: string): { key: string; value: string }[] {const result: { key: string; value: string }[] = []@@ -126,6 +127,9 @@ const defaultRESTRequest: HoppRESTRequest = {params: [],headers: [],method: "GET",+ auth: {+ authType: "none",+ },preRequestScript: "// pw.env.set('variable', 'value');",testScript: "// pw.expect('variable').toBe('value');",body: {@@ -327,6 +331,14 @@ const dispatchers = defineDispatchers({},}},+ setAuth(curr: RESTSession, { newAuth }: { newAuth: HoppRESTAuth }) {+ return {+ request: {+ ...curr.request,+ auth: newAuth,+ },+ }+ },setPreRequestScript(curr: RESTSession, { newScript }: { newScript: string }) {return {request: {@@ -508,6 +520,15 @@ export function deleteAllRESTHeaders() {})}+export function setRESTAuth(newAuth: HoppRESTAuth) {+ restSessionStore.dispatch({+ dispatcher: "setAuth",+ payload: {+ newAuth,+ },+ })+}+export function setRESTPreRequestScript(newScript: string) {restSessionStore.dispatch({dispatcher: "setPreRequestScript",@@ -598,6 +619,8 @@ export const restActiveHeadersCount$ = restHeaders$.pipe(map((params) => params.filter((x) => x.active).length))+export const restAuth$ = restRequest$.pipe(pluck("auth"))+export const restPreRequestScript$ = restSessionStore.subject$.pipe(pluck("request", "preRequestScript"),distinctUntilChanged()diff --git a/pages/index.vue b/pages/index.vueindex c56177886..fd06efa02 100644--- a/pages/index.vue+++ b/pages/index.vue@@ -27,7 +27,7 @@</SmartTab><SmartTab :id="'authentication'" :label="$t('authentication')">- <!-- TODO: Implement -->+ <HttpAuth /></SmartTab><SmartTab