Question:
How can I ensure that our site members have exclusive access to certain collections based on their email address or a specific badge assignment?
Product:
Wix Editor
What are you trying to achieve:
MEMBER1 should show content that’s relevant only to them when they click on My Documents.
What have you already tried:
- MEMBER#1 has a badge assigned to them called “7499” (each member will have their own badge exclusive to them)
- CRM Collection created: “MyDocuments” with text fields to collect badgeName and userEmail. This is where documents will be uploaded for members with their unique badgename
- CRM Collection created: “userProfiles” with text fields to record badgeName and userEmail (this is so Wix can match the email to the badge)
- Dynamic page create for “My Documents” linking it back to the MyDocuments collection. No filter set due to over-ride by below code
- Code entered into Developer Mode
Additional information:
If there is a way to do this without inserting code, I would like to go that route. But, here is the code entered into Developer Mode:
import wixData from ‘wix-data’;
import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;
import {session} from ‘wix-storage’;
$w.onReady(function () {
// Check if a user is logged in
if (wixUsers.currentUser.loggedIn) {
// Retrieve the logged-in user’s email
wixUsers.currentUser.getEmail().then((email) => {
// Query the ‘UserProfiles’ collection to find the user’s profile by their email
wixData.query(‘UserProfiles’)
.eq(‘userEmail’, email)
.find()
.then((results) => {
if (results.items.length > 0) {
// Assuming the user’s profile was found, extract the badgeName
let userBadgeName = results.items[0].badgeName;
// Ensure the 'MyDocuments' dataset is ready before applying the filter
$w("#MyDocuments").onReady(() => {
// Apply a filter to the 'MyDocuments' dataset to only show documents with the user's badgeName
$w("#MyDocuments").setFilter(wixData.filter()
.eq('badgeName', userBadgeName)
);
});
} else {
console.log("No user profile found.");
}
})
.catch((err) => {
console.error("Error querying UserProfiles:", err);
});
});
} else {
// User is not logged in, prompt them to log in
let currentPage = wixLocation.url; // Store the current page URL
session.setItem(“returnToPage”, currentPage); // Save the current page to return to after login
// Redirect to the login page or open a login lightbox
wixUsers.promptLogin({ mode: "login" })
.then(() => {
// User is now logged in, redirect them back to the page they were trying to access
let returnToPage = session.getItem("returnToPage");
if (returnToPage) {
wixLocation.to(returnToPage); // Redirect user back to the original page
} else {
// If the page to return to isn't specified, redirect to a default page or refresh
wixLocation.to("/"); // Adjust this to your preferred default page
}
})
.catch((err) => {
console.error("Error during login:", err);
});
}
});