Skip to content

Pr@main/xpack login#2441

Merged
wangdan-fit2cloud merged 2 commits intomainfrom
pr@main/xpack-login
Feb 28, 2025
Merged

Pr@main/xpack login#2441
wangdan-fit2cloud merged 2 commits intomainfrom
pr@main/xpack-login

Conversation

@wangdan-fit2cloud
Copy link
Copy Markdown
Contributor

What this PR does / why we need it?

Summary of your change

Please indicate you've done the following:

  • Made sure tests are passing and test coverage is added if needed.
  • Made sure commit message follow the rule of Conventional Commits specification.
  • Considered the docs impact and opened a new docs issue or PR with docs changes if needed.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Feb 28, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Feb 28, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

loading.value = false
}
})
})
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code snippet has several improvements and corrections:

Improvements:

  1. Remove Unnecessary Conditions: The variable showQrCodeTab and its condition inside the template have been removed as they seem to be unnecessary based on the rest of the logic.

  2. Consistent Loading State Update: Moved the setting of loading to onBeforeMount instead of onMounted. This ensures that the component starts with a non-loading state unless there's an error fetching the profile.

  3. Optimize Login Process:

    • Removed the redundant call to user.asyncGetProfile() inside the onMounted hook.
    • Simplified the conditional logic within the .catch() method.
  4. Variable Naming: Consistently used camelCase for Vue prop names (subTitle) to improve readability and compatibility.

Here is the revised code:

<template>
  <login-layout v-if="!loading" v-loading="loading">
    <LoginContainer :subTitle="user.themeInfo?.slogan || $t('views.system.theme.defaultSlogan')">
      <h2 class="mb-24">{{ !showQrCodeTab ? loginMode || $t('views.login.title') : '' }}</h2>
      <!-- QR Code Tab should be conditionally rendered here -->
      
    </LoginContainer>
  </login-layout>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect } from 'vue';
// Import necessary components

const loading = ref(true);
const showQrCodeTab = ref(false); // Optional: Define this flag if needed

// Functionality defined earlier...

onBeforeMount(async () => {
  try {
    await user.asyncGetProfile(); // Remove duplicate call in mounted

    if (user.isEnterprise()) {
      await user.getAuthType();
      // Handle enterprise-specific logic here
    }
  } catch (error) {
    console.error('Error fetching user profile:', error);
  } finally {
    loading.value = false;
  }
});

// Other methods...
</script>

This version ensures that the component only mounts when it needs to perform data fetching and handles errors appropriately without unnecessarily repeating calls.

@wangdan-fit2cloud wangdan-fit2cloud merged commit ee7cc80 into main Feb 28, 2025
4 checks passed
@wangdan-fit2cloud wangdan-fit2cloud deleted the pr@main/xpack-login branch February 28, 2025 07:21
})

export const getChildRouteListByPathAndName = (path: any, name?: RouteRecordName | any) => {
return getChildRouteList(routes, path, name)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No significant irregularities, potential issues, or immediate optimizations were identified in the provided code snippet. The code is well-structured and follows Vue Router conventions. Here are a few minor improvements that can be made:

  1. Consistent Spacing: Adjusting spacing for consistency can improve readability.

  2. Comments: Adding comments above complex blocks of code can help explain what specific functionalities they serve.

Here's an optimized version with these considerations:

// Import necessary modules
import { hasPermission } from '@/utils/permission/index';
import NProgress from 'nprogress';

NProgress.configure({ showSpinner: false, speed: 500, minimum: 0.3 });

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes
});

// Define route guards
router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  try {
    // Start loading progress bar
    NProgress.start();

    if (to.name === '404') {
      next();
      return;
    }
    
    const userState = await useStore().getters['user/getUserState'];
    if (!hasPermission(userState.permission)) {
      if (from.path !== '/login' && from.path.indexOf('/admin/') !== 0){
        // Redirect to login page when unauthorized non-admin users access restricted areas
        next(`/home?r=403&redirect=${to.fullPath}`);
      } else {
        // For admin redirect them directly to their dashboard upon redirection failure
        next('dashboard');
      }
      return;
    }

    next(); // Proceed to destination if allowed permissions match the required role
  } catch (error) {
    console.error("Failed to authenticate user:", error);
    next('/'); // Redirect to home on authentication failure
  }
});

router.afterEach(() => {
  // Complete/loading process after navigation completes
  NProgress.done();
});

export function getChildRouteListByPathAndName(path: string, name?: RouteRecordName): RouteRecordRaw[] | null {
  return getChildRouteList(routes, path, name);
}

These changes include adding consistent whitespace around operators and expressions, and organizing related functions under one try-catch block within the beforeEach hook to handle exceptions gracefully.

if (user.themeInfo) {
if (typeof user.themeInfo?.loginLogo === 'string') {
return user.themeInfo?.loginLogo
} else {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code you provided has some issues that need to be addressed:

Issues Identified:

  1. Inconsistent Template Syntax: The use of v-if in both <template> and directly within an SVG element might be confusing and redundant because Vue components should not have both template sections (<template>...</template> and standalone elements).

  2. Redundant Condition Check: The condition checks for loginLogo and its type are redundant since they will always evaluate whether it exists.

  3. Simplified Logic: You can simplify the logic for determining the image source and size using computed properties instead of multiple conditional statements.

  4. Potential Bug with Computed Properties: Ensure that user.themeInfo.loginLogo does exist before checking its type; otherwise, undefined may lead to runtime errors.

Optimal Suggestions:

Here's a revised version of your code with suggestions for addressing these points:

<svg id="logo-icon" width="36px" height="auto">
  <!-- Icon rendering goes here -->
</svg>

<img v-if="fileURL.value" :src="fileURL.value" class="max-kb-logo" />

<script setup lang="ts">
import { ref } from 'vue';

const logoOptions = {
  // Define your options here like lightModeImageUrl...
};

const isDarkMode = ref(true); // Example boolean based on user preference

function updateLogo(srcUrl?: string): void {
  logoIcon.src = srcUrl || ''; // Set the logo icon source dynamically
}

// Function to set up theme based on selected mode
function setupTheme(mode: string) {
  switch (mode.toLocaleLowerCase()) {
    case 'light':
      isDarkMode.value = false;
      break;
    default:
      isDarkMode.value = true;
      break;
  }
  const darkModeClassName = isDarkMode.value ? '--dark' : '';
  
  document.documentElement.className = `theme ${darkModeClassName}`;

  try {
    if (!logoOptions.lightModeImageUrl && !logoOptions.darkModeImageUrl) return;

    let imageUrl;
    if (isDarkMode.value && logoOptions.darkModeImageUrl) imageUrl = logoOptions.darkModeImageUrl;
    else if (!logoOptions.lightModeImageUrl ||
             typeof logoOptions.lightModeImageUrl === "object") imageUrl = '/assets/logo/icons/light_logo.svg'; // Default light-mode image fallback
  
    updateLogo(imageUrl);
  } catch (e) {
    console.error('Error setting up theme:', e);
  }

}
</script>

<style>
/* Style for .max-kb-logo */
.max-kb-logo img {
  /* Add styles here as needed */
}
</style>

Explanation:

  • Template Simplification: Removed the unnecessary conditions around the <img> tag.
  • Computed Property Use: Used a computed property setupTheme() to handle dynamic updates to the theme and logos. This simplifies management of different themes.
  • Dynamic Image URL Handling: Uses updateLogo() to manage the actual source of the logos, ensuring correct functionality even when no images are found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants