-
Notifications
You must be signed in to change notification settings - Fork 2.6k
feat: streamline WeCom QR code login success handling with direct callback integration #4526
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…lback integration
|
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. DetailsInstructions 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. |
|
[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. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
| }) | ||
| } | ||
| }) | ||
| } |
There was a problem hiding this comment.
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:
-
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, }); } });
-
Clean Up Functionality: Although cleanup is done after receiving the token, it's good practice to handle errors that may occur during initialization.
-
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. -
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.
feat: streamline WeCom QR code login success handling with direct callback integration