Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

feat: streamline WeCom QR code login success handling with direct callback integration

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Dec 16, 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-sigs/prow repository.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Dec 16, 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

})
}
})
}
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.

@shaohuzhang1 shaohuzhang1 merged commit 8d360b1 into v2 Dec 16, 2025
3 of 6 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@v2@fix_wecom branch December 16, 2025 12:52
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