1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-08-02 20:15:24 +02:00

feat: Add OIDC_CLIENT_SECRET and other changes for v2 (#4254)

Co-authored-by: boc-the-git <3479092+boc-the-git@users.noreply.github.com>
This commit is contained in:
Carter 2024-10-05 16:12:11 -05:00 committed by GitHub
parent 4f1abcf4a3
commit 5ed0ec029b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 530 additions and 349 deletions

View file

@ -35,7 +35,7 @@
<v-btn v-else icon @click="activateSearch">
<v-icon> {{ $globals.icons.search }}</v-icon>
</v-btn>
<v-btn v-if="loggedIn" :text="$vuetify.breakpoint.smAndUp" :icon="$vuetify.breakpoint.xs" @click="$auth.logout()">
<v-btn v-if="loggedIn" :text="$vuetify.breakpoint.smAndUp" :icon="$vuetify.breakpoint.xs" @click="logout()">
<v-icon :left="$vuetify.breakpoint.smAndUp">{{ $globals.icons.logout }}</v-icon>
{{ $vuetify.breakpoint.smAndUp ? $t("user.logout") : "" }}
</v-btn>
@ -48,7 +48,7 @@
</template>
<script lang="ts">
import { computed, defineComponent, onBeforeUnmount, onMounted, ref, useContext, useRoute } from "@nuxtjs/composition-api";
import { computed, defineComponent, onBeforeUnmount, onMounted, ref, useContext, useRoute, useRouter } from "@nuxtjs/composition-api";
import { useLoggedInState } from "~/composables/use-logged-in-state";
import RecipeDialogSearch from "~/components/Domain/Recipe/RecipeDialogSearch.vue";
@ -64,6 +64,7 @@ export default defineComponent({
const { $auth } = useContext();
const { loggedIn } = useLoggedInState();
const route = useRoute();
const router = useRouter();
const groupSlug = computed(() => route.value.params.groupSlug || $auth.user?.groupSlug || "");
const routerLink = computed(() => groupSlug.value ? `/g/${groupSlug.value}` : "/");
@ -89,11 +90,16 @@ export default defineComponent({
document.removeEventListener("keydown", handleKeyEvent);
});
async function logout() {
await $auth.logout().then(() => router.push("/login?direct=1"))
}
return {
activateSearch,
domSearchDialog,
routerLink,
loggedIn,
logout,
};
},
});

View file

@ -242,11 +242,6 @@ export interface NotificationImport {
status: boolean;
exception?: string | null;
}
export interface OIDCInfo {
configurationUrl: string | null;
clientId: string | null;
groupsClaim: string | null;
}
export interface RecipeImport {
name: string;
status: boolean;

View file

@ -132,9 +132,6 @@ export interface LongLiveTokenOut {
id: number;
createdAt?: string | null;
}
export interface OIDCRequest {
id_token: string;
}
export interface PasswordResetToken {
token: string;
}

View file

@ -123,7 +123,7 @@ export default {
auth: {
redirect: {
login: "/login",
logout: "/login?direct=1",
logout: "/login",
callback: "/login",
home: "/",
},
@ -161,12 +161,24 @@ export default {
},
},
oidc: {
scheme: "~/schemes/DynamicOpenIDConnectScheme",
scheme: "local",
resetOnError: true,
clientId: "",
token: {
property: "access_token",
global: true,
},
user: {
property: "",
autoFetch: true,
},
endpoints: {
configuration: "",
}
login: {
url: "api/auth/oauth/callback",
method: "get",
},
logout: { url: "api/auth/logout", method: "post" },
user: { url: "api/users/self", method: "get" },
},
},
},
},

View file

@ -65,7 +65,7 @@
<v-checkbox v-model="form.remember" class="ml-2 mt-n2" :label="$t('user.remember-me')"></v-checkbox>
<v-card-actions class="justify-center pt-0">
<div class="max-button">
<v-btn :loading="loggingIn" color="primary" type="submit" large rounded class="rounded-xl" block>
<v-btn :loading="loggingIn" :disabled="oidcLoggingIn" color="primary" type="submit" large rounded class="rounded-xl" block>
{{ $t("user.login") }}
</v-btn>
</div>
@ -85,7 +85,7 @@
</div>
<v-card-actions v-if="allowOidc" class="justify-center">
<div class="max-button">
<v-btn color="primary" large rounded class="rounded-xl" block @click.native="oidcAuthenticate">
<v-btn :loading="oidcLoggingIn" color="primary" large rounded class="rounded-xl" block @click.native="() => oidcAuthenticate()">
{{ $t("user.login-oidc") }} {{ oidcProviderName }}
</v-btn>
</div>
@ -133,7 +133,7 @@
</template>
<script lang="ts">
import { defineComponent, ref, useContext, computed, reactive, useRouter, useAsync } from "@nuxtjs/composition-api";
import { defineComponent, ref, useContext, computed, reactive, useRouter, useAsync, onBeforeMount } from "@nuxtjs/composition-api";
import { useDark, whenever } from "@vueuse/core";
import { useLoggedInState } from "~/composables/use-logged-in-state";
import { useAppInfo } from "~/composables/api";
@ -180,6 +180,7 @@ export default defineComponent({
);
const loggingIn = ref(false);
const oidcLoggingIn = ref(false)
const appInfo = useAppInfo();
@ -196,19 +197,34 @@ export default defineComponent({
{immediate: true}
)
onBeforeMount(async () => {
if (isCallback()) {
await oidcAuthenticate(true)
}
})
function isCallback() {
return router.currentRoute.query.state;
const params = new URLSearchParams(window.location.search)
return params.has("code") || params.has("error")
}
function isDirectLogin() {
return Object.keys(router.currentRoute.query).includes("direct")
const params = new URLSearchParams(window.location.search)
return params.has("direct") && params.get("direct") === "1"
}
async function oidcAuthenticate() {
try {
await $auth.loginWith("oidc")
} catch (error) {
alert.error(i18n.t("events.something-went-wrong") as string);
async function oidcAuthenticate(callback = false) {
if (callback) {
oidcLoggingIn.value = true
try {
await $auth.loginWith("oidc", { params: new URLSearchParams(window.location.search)})
} catch (error) {
await router.replace("/login?direct=1")
alertOnError(error)
}
oidcLoggingIn.value = false
} else {
window.location.replace("/api/auth/oauth") // start the redirect process
}
}
@ -227,6 +243,12 @@ export default defineComponent({
try {
await $auth.loginWith("local", { data: formData });
} catch (error) {
alertOnError(error)
}
loggingIn.value = false;
}
function alertOnError(error: any) {
// TODO Check if error is an AxiosError, but isAxiosError is not working right now
// See https://github.com/nuxt-community/axios-module/issues/550
// Import $axios from useContext()
@ -240,8 +262,6 @@ export default defineComponent({
} else {
alert.error(i18n.t("events.something-went-wrong") as string);
}
}
loggingIn.value = false;
}
return {
@ -253,6 +273,7 @@ export default defineComponent({
authenticate,
oidcAuthenticate,
oidcProviderName,
oidcLoggingIn,
passwordIcon,
inputType,
togglePasswordShow,

View file

@ -1,122 +0,0 @@
import jwtDecode from "jwt-decode"
import { ConfigurationDocument, OpenIDConnectScheme } from "~auth/runtime"
/**
* Custom Scheme that dynamically gets the OpenID Connect configuration from the backend.
* This is needed because the SPA frontend does not have access to runtime environment variables.
*/
export default class DynamicOpenIDConnectScheme extends OpenIDConnectScheme {
async mounted() {
await this.getConfiguration();
this.configurationDocument = new ConfigurationDocument(
this,
this.$auth.$storage
)
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await super.mounted()
}
// Overrides the check method in the OpenIDConnectScheme
// We don't care if the id token is expired as long as we have a valid Mealie token.
// We only use the id token to verify identity on the initial login, then issue a Mealie token
check(checkStatus = false) {
const response = super.check(checkStatus)
// we can do this because id token is the last thing to be checked so if the id token is expired then it was
// the only thing making the request not valid
if (response.idTokenExpired && !response.valid) {
response.valid = true;
response.idTokenExpired = false;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return response;
}
async fetchUser() {
if (!this.check().valid) {
return
}
const { data } = await this.$auth.requestWith(this.name, {
url: "/api/users/self"
})
this.$auth.setUser(data)
}
async _handleCallback() {
// sometimes the mealie token is being sent in the request to the IdP on callback which
// causes an error, so we clear it if we have one
if (!this.token.status().valid()) {
this.token.reset();
}
const redirect = await super._handleCallback()
await this.updateAccessToken()
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return redirect;
}
async updateAccessToken() {
if (this.isValidMealieToken()) {
return
}
if (!this.idToken.status().valid()) {
this.idToken.reset();
return
}
try {
const response = await this.$auth.requestWith(this.name, {
url: "/api/auth/token",
method: "post"
})
// Update tokens with mealie token
this.updateTokens(response)
} catch (e) {
if (e.response?.status === 401 || e.response?.status === 500) {
this.$auth.reset()
}
const currentUrl = new URL(window.location.href)
if (currentUrl.pathname === "/login" && currentUrl.searchParams.has("direct")) {
return
}
window.location.replace("/login?direct=1")
}
}
isValidMealieToken() {
if (this.token.status().valid()) {
let iss = null;
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
iss = jwtDecode(this.token.get()).iss
} catch (e) {
// pass
}
return iss === "mealie"
}
return false
}
async getConfiguration() {
const route = "/api/app/about/oidc";
try {
const response = await fetch(route);
const data = await response.json();
this.options.endpoints.configuration = data.configurationUrl;
this.options.clientId = data.clientId;
this.options.scope = ["openid", "profile", "email"]
if (data.groupsClaim !== null) {
this.options.scope.push(data.groupsClaim)
}
console.log(this.options.scope)
} catch (error) {
// pass
}
}
}