Introduce device flow

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel
2023-02-21 14:50:09 +01:00
parent 2ee329ff7b
commit b6875f6a4b
19 changed files with 833 additions and 47 deletions

View File

@@ -0,0 +1,91 @@
<template>
<h1 class="text-3xl">
{{ t("Autorize this application to access your account?") }}
</h1>
<div
class="rounded-lg bg-mbz-warning dark:text-black shadow-xl my-6 p-4 flex items-center gap-2"
>
<AlertCircle :size="42" />
<p>
{{
t(
"This application will be able to access all of your informations and post content on your behalf. Make sure you only approve applications you trust."
)
}}
</p>
</div>
<div class="rounded-lg bg-white dark:bg-zinc-900 shadow-xl my-6">
<div class="p-4 pb-0">
<p class="text-3xl font-bold">{{ authApplication.name }}</p>
<p>{{ authApplication.website }}</p>
</div>
<div class="flex gap-3 p-4">
<o-button @click="() => authorize()">{{ t("Authorize") }}</o-button>
<o-button outlined tag="router-link" :to="{ name: RouteName.HOME }">{{
t("Decline")
}}</o-button>
</div>
</div>
</template>
<script lang="ts" setup>
import { useHead } from "@vueuse/head";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useMutation } from "@vue/apollo-composable";
import { AUTORIZE_APPLICATION } from "@/graphql/application";
import AlertCircle from "vue-material-design-icons/AlertCircle.vue";
import RouteName from "@/router/name";
import { IApplication } from "@/types/application.model";
const { t } = useI18n({ useScope: "global" });
const props = defineProps<{
authApplication: IApplication;
redirectURI?: string | null;
state?: string | null;
scope?: string | null;
}>();
const { mutate: authorizeMutation, onDone: onAuthorizeMutationDone } =
useMutation<
{ authorizeApplication: { code: string; state: string } },
{
applicationClientId: string;
redirectURI: string;
state?: string | null;
scope?: string | null;
}
>(AUTORIZE_APPLICATION);
const authorize = () => {
authorizeMutation({
applicationClientId: props.authApplication.clientId,
redirectURI: props.redirectURI as string,
state: props.state,
scope: props.scope,
});
};
onAuthorizeMutationDone(({ data }) => {
const code = data?.authorizeApplication?.code;
const returnedState = data?.authorizeApplication?.state ?? "";
if (!code) return;
if (props.redirectURI) {
const params = new URLSearchParams(
Object.entries({ code, state: returnedState })
);
window.location.assign(
new URL(`${props.redirectURI}?${params.toString()}`)
);
}
});
useHead({
title: computed(() => t("Authorize application")),
});
</script>

View File

@@ -3,6 +3,7 @@ import gql from "graphql-tag";
export const AUTH_APPLICATION = gql`
query AuthApplication($clientId: String!) {
authApplication(clientId: $clientId) {
id
clientId
name
website
@@ -13,7 +14,7 @@ export const AUTH_APPLICATION = gql`
export const AUTORIZE_APPLICATION = gql`
mutation AuthorizeApplication(
$applicationClientId: String!
$redirectURI: String!
$redirectURI: String
$state: String
$scope: String
) {
@@ -53,3 +54,18 @@ export const REVOKED_AUTHORIZED_APPLICATION = gql`
}
}
`;
export const DEVICE_ACTIVATION = gql`
mutation DeviceActivation($userCode: String!) {
deviceActivation(userCode: $userCode) {
id
application {
id
clientId
name
website
}
scope
}
}
`;

View File

@@ -14,6 +14,7 @@ export enum UserRouteName {
VALIDATE = "Validate",
LOGIN = "Login",
OAUTH_AUTORIZE = "OAUTH_AUTORIZE",
OAUTH_LOGIN_DEVICE = "OAUTH_LOGIN_DEVICE",
}
export const userRoutes: RouteRecordRaw[] = [
@@ -120,4 +121,16 @@ export const userRoutes: RouteRecordRaw[] = [
},
},
},
{
path: "/login/device",
name: UserRouteName.OAUTH_LOGIN_DEVICE,
component: (): Promise<any> =>
import("@/views/OAuth/DeviceActivationView.vue"),
meta: {
requiredAuth: true,
announcer: {
message: (): string => t("Device activation") as string,
},
},
},
];

View File

@@ -26,39 +26,14 @@
</div>
</div>
</div>
<div
<AuthorizeApplication
v-if="authApplication"
v-show="!authApplicationLoading && !authApplicationError && !resultCode"
>
<h1 class="text-3xl">
{{ t("Autorize this application to access your account?") }}
</h1>
<div
class="rounded-lg bg-mbz-warning shadow-xl my-6 p-4 flex items-center gap-2"
>
<AlertCircle :size="42" />
<p>
{{
t(
"This application will be able to access all of your informations and post content on your behalf. Make sure you only approve applications you trust."
)
}}
</p>
</div>
<div class="rounded-lg bg-white shadow-xl my-6">
<div class="p-4 pb-0">
<p class="text-3xl font-bold">{{ authApplication?.name }}</p>
<p>{{ authApplication?.website }}</p>
</div>
<div class="flex gap-3 p-4">
<o-button @click="() => authorize()">{{ t("Authorize") }}</o-button>
<o-button outlined tag="router-link" :to="{ name: RouteName.HOME }">{{
t("Decline")
}}</o-button>
</div>
</div>
</div>
:auth-application="authApplication"
:redirectURI="redirectURI"
:state="state"
:scope="scope"
/>
<div v-show="authApplicationError">
<div
class="rounded-lg bg-mbz-danger shadow-xl my-6 p-4 flex items-center gap-2"
@@ -114,6 +89,7 @@ import { IApplication } from "@/types/application.model";
import AlertCircle from "vue-material-design-icons/AlertCircle.vue";
import type { AbsintheGraphQLError } from "@/types/errors.model";
import RouteName from "@/router/name";
import AuthorizeApplication from "@/components/OAuth/AuthorizeApplication.vue";
const { t } = useI18n({ useScope: "global" });

View File

@@ -0,0 +1,149 @@
<template>
<div class="container mx-auto w-96">
<form
@submit.prevent="() => validateCode({ userCode: code })"
@paste="pasteCode"
class="rounded-lg bg-white dark:bg-zinc-900 shadow-xl my-6 p-4"
v-if="!application"
>
<h1 class="text-3xl text-center">
{{ t("Device activation") }}
</h1>
<p class="mb-4 text-center">
{{ t("Enter the code displayed on your device") }}
</p>
<div class="flex items-center justify-between mb-4 gap-2">
<div
v-for="i in Array(9).keys()"
:key="i"
:class="i === 4 ? 'w-6' : 'w-8'"
>
<span
:id="`user-code-${i}`"
v-if="i === 4"
class="block text-3xl text-center"
>-</span
>
<o-input
autocapitalize="characters"
@update:modelValue="(val: string) => inputs[i] = val.toUpperCase()"
:useHtml5Validation="true"
:id="`user-code-${i}`"
:ref="(el: Element) => userCodeInputs[i] = el"
:modelValue="inputs[i]"
v-else
size="large"
style="font-size: 22px; padding: 0.5rem 0.15rem 0.5rem 0.25rem"
required
maxlength="1"
pattern="[A-Z]{1}"
:autofocus="i === 0 ? true : undefined"
/>
</div>
</div>
<div
class="rounded-lg bg-mbz-danger shadow-xl my-6 p-4 flex items-center gap-2"
v-if="error"
>
<AlertCircle :size="42" />
<div>
<p>{{ error }}</p>
</div>
</div>
<div class="text-center">
<o-button native-type="submit">{{ t("Continue") }}</o-button>
</div>
</form>
<AuthorizeApplication v-if="application" :auth-application="application" />
</div>
</template>
<script lang="ts" setup>
import { DEVICE_ACTIVATION } from "@/graphql/application";
import { useMutation } from "@vue/apollo-composable";
import { useHead } from "@vueuse/head";
import { computed, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import AuthorizeApplication from "@/components/OAuth/AuthorizeApplication.vue";
import { IApplication } from "@/types/application.model";
import { AbsintheGraphQLErrors } from "@/types/errors.model";
import AlertCircle from "vue-material-design-icons/AlertCircle.vue";
const { t } = useI18n({ useScope: "global" });
const {
mutate: validateCode,
onDone: onDeviceActivationDone,
onError: onDeviceActivationError,
} = useMutation<{
deviceActivation: { application: IApplication; id: string; scope: string };
}>(DEVICE_ACTIVATION);
const inputs = reactive<string[]>([]);
const application = ref<IApplication | null>(null);
onDeviceActivationDone(({ data }) => {
const foundApplication = data?.deviceActivation?.application;
if (foundApplication) {
application.value = foundApplication;
}
});
const code = computed(() => {
return inputs.join("");
});
const userCodeInputs = reactive<Record<number, Element>>([]);
watch(inputs, (localInputs) => {
localInputs.forEach((input, index) => {
if (input && index < 8) {
if (index === 3) {
index = 4;
}
(userCodeInputs[index + 1] as HTMLInputElement).focus();
}
});
});
const error = ref<string | null>(null);
onDeviceActivationError(
({ graphQLErrors }: { graphQLErrors: AbsintheGraphQLErrors }) => {
if (graphQLErrors[0].status_code === 404) {
error.value = t("The device code is incorrect or no longer valid.");
}
resetInputs();
(userCodeInputs[0] as HTMLInputElement).focus();
setTimeout(() => {
error.value = null;
}, 10000);
}
);
const resetInputs = () => {
inputs.splice(0);
};
const pasteCode = (e: ClipboardEvent) => {
let pastedCode = e.clipboardData?.getData("text").trim();
if (!pastedCode) return;
if (pastedCode.match(/^[A-Z]{4}-[A-Z]{4}$/)) {
pastedCode = pastedCode.slice(0, 4) + pastedCode.slice(5);
}
if (pastedCode.match(/^[A-Z]{8}$/)) {
pastedCode.split("").forEach((val, index) => {
const realIndex = index > 3 ? index + 1 : index;
inputs[realIndex] = val;
});
}
};
useHead({
title: computed(() => t("Device activation")),
});
</script>

View File

@@ -76,11 +76,12 @@ import {
} from "@/graphql/application";
import { useMutation, useQuery } from "@vue/apollo-composable";
import { useHead } from "@vueuse/head";
import { computed } from "vue";
import { computed, inject } from "vue";
import { useI18n } from "vue-i18n";
import RouteName from "../../router/name";
import { IUser } from "@/types/current-user.model";
import { formatDateString } from "@/filters/datetime";
import { Notifier } from "@/plugins/notifier";
const { t } = useI18n({ useScope: "global" });
@@ -132,6 +133,14 @@ const { mutate: revoke, onDone: onRevokedApplication } = useMutation<
},
});
const notifier = inject<Notifier>("notifier");
onRevokedApplication(() => {
notifier?.success(
t("Application was revoked")
);
})
useHead({
title: computed(() => t("Apps")),
});