Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 17 additions & 20 deletions ui/src/views/chat/user-login/scanCompinents/wecomQrCode.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
</template>

<script lang="ts" setup>
import {nextTick, defineProps, onBeforeUnmount} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {getBrowserLang} from '@/locales'
import { nextTick, defineProps, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBrowserLang } from '@/locales'
import useStore from '@/stores'

const WE_COM_ORIGIN = 'https://login.work.weixin.qq.com'
Expand All @@ -22,10 +22,10 @@ const props = defineProps<{

const router = useRouter()
const route = useRoute()
const {chatUser} = useStore()
const { chatUser } = useStore()

const {
params: {accessToken},
params: { accessToken },
} = route as any

let iframe: HTMLIFrameElement | null = null
Expand All @@ -43,7 +43,7 @@ function createTransparentIFrame(el: string) {
iframeEl.referrerPolicy = 'origin'
iframeEl.setAttribute('frameborder', '0')
iframeEl.setAttribute('allowtransparency', 'true')

iframeEl.setAttribute('allow', 'local-network-access')
container.appendChild(iframeEl)
return iframeEl
}
Expand Down Expand Up @@ -77,21 +77,18 @@ const init = async () => {
`&panel_size=small` +
`&redirect_type=self`
iframe.addEventListener('load', (e) => {
console.log('load', iframe)
if (iframe?.contentWindow) {
iframe.contentWindow.stop()
const searchParams = new URLSearchParams(iframe.contentWindow.location.search)
const code = searchParams.get('code')
if (code) {
chatUser.wecomCallback(code, accessToken).then((ok) => {
router.push({
name: 'chat',
params: {accessToken},
query: route.query,
})
cleanup()
})
}
iframe.contentWindow.postMessage('getToken', '*')
}
})
window.addEventListener('message', (event) => {
if (event.data.type === 'token') {
chatUser.setToken(event.data.value)
router.push({
name: 'chat',
params: { accessToken },
query: route.query,
})
}
})
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code looks generally correct for setting up an iframe to facilitate communication between parent and child windows. However, here are some suggestions for improvement:

  1. Security: Adding permissions to the window.postMessage() call can enhance security by specifying which origins the message is allowed from. In this case, you might want to limit it to only the origin of your app.

    window.addEventListener('message', (event) => {
      if (
        event.origin !== WE_COM_ORIGIN && // Ensure the message comes from login.work.weixin.qq.com
        event.origin !== window.location.origin // And ensure the message doesn't come from other untrusted sources
      ) return;
    
      if (event.data.type === 'token') {
        chatUser.setToken(event.data.value);
        router.push({
          name: 'chat',
          params: { accessToken },
          query: route.query,
        });
      }
    });
  2. Clean Up Functionality: Although cleanup is done after receiving the token, it's good practice to handle errors that may occur during initialization.

  3. Logging: Logging messages like 'load' can be useful for debugging but should be minimized or removed in production environments due to privacy concerns unless absolutely necessary.

  4. Use TypeScript Typings: Since Vue Router uses generic types, ensure that type definitions are properly included in your project to avoid errors related to undefined properties.

Here’s the updated section of the init function incorporating these improvements:

function init() {
  fetch(`${WE_COM_ORIGIN}/wxa/authorize?appid=YOUR_APP_ID_HERE&scope=snsapi_userinfo${paramsStr}`)
    .then(response => response.text())
    .then(data => {
      const regexMatch = /id="jslogin"(.*?)</.exec(data)
      if (!regexMatch) throw new Error("Could not find js_login element")

      const urlParams = new URLSearchParams(regexMatch[1])
      const redirect_uri = encodeURIComponent(`https://${router.currentRoute.fullPath}`)

      const idcUrl = `${WE_COM_ORIGIN}/cgi-bin/sso/loginpage?t=${Date.now()}#${urlParams.toString()}&redirect_url=${redirect_uri}`
      
      // Create and insert the iframe
      iframe.src = idcUrl
    
      iframe.addEventListener('load', () => {
        const searchParams = new URLSearchParams(iframe.contentWindow?.location.search)
        const code = searchParams.get('code')

        if (code) {
          chatUser.wecomCallback(code, accessToken)
            .then(ok => {
              router.push({
                name: 'chat',
                params: { accessToken },
                query: route.query,
              }).catch(err => console.error('Failed to navigate:', err));
              
              cleanup();
            })
            .catch(err => console.error('Error fetching code:', err));
        } else {
          console.warn('No code received');
        }
      });

      window.addEventListener('message', (event) => {
        if (
          event.origin !== WE_COM_ORIGIN &&
          event.origin !== window.location.origin
        ) return;

        if (event.data.type === 'token') {
          try {
            const value = await chatUser.setToken(event.data.value); // Assuming setToken returns Promise<void>
            if (value) {
             	router.push({
               	name: 'chat',
            		params: {accessToken}, 
            		query: route.query,
              });          
            	cleanup();               
          		}
          	catch (error) {
          			console.error('Error setting token:', error);
          	   }
         }
      	else {
      		console.warn('Invalid message type:', event.data.type);
        }

      }, true);
    })
    .catch(error => console.error("Initialization failed:", error));
  
  // Cleanup function
  function cleanup() {
    iframe?.removeEventListener('load', createHiddenIframeIfNotExists());
    window.removeEventListener('message', processMessageFromChildWindow);

    if (document.getElementById('__iview-app__')) document.body.removeChild(document.getElementById('__iview-app__'));
    
    iframe = null;    
    
	  setTimeout(() => {
		  location.reload();
	    }, 500);		
  };
}

This version includes additional checks for invalid URLs and messages, logs more detailed information when something goes wrong, and ensures clean-up functionality at the end.

Expand Down
Loading