Elevate Backend Function

Question:
Can someone help me elevate this function so a Non-Admin member can call it.

Product:
Regular Editor

→ This function is in a backend .jsw file

The main problem I’m facing is that when I call the function in the Testing-Environment it works properly and is returning either the NotOk or Ok, depending on the Member.
But when I call it from a regular Member Demo-Account it gives me a permissions error, since the “Members/FullData” App-Database is Read: Admin (btw. in the Docs it says it’s Read: All, but thats not true).

FYI: Due to logical restrictions I can’t use the “getMember, etc.” from the Members API, since I don’t have access to the Member ID. (This function gets called by a custom Velo login form).

So the logical solution would be to just elevate the query right? Well I can’t seem to get it to work. What am I missing?

import wixData from 'wix-data';
import { elevate } from 'wix-auth';

const amountSessionsPerMember = 1;

export async function CheckMemberSessionCount(memberEmail) {
    console.log("MemberEmailatBackend: " + memberEmail);
    try {

        const elevatedQuery = elevate(wixData.query);
        // Suche nach dem Mitglied anhand der E-Mail-Adresse in der Datenbank
        let memberResult = await elevatedQuery("Members/FullData")
            .eq("loginEmail", memberEmail)
            .find();
        console.log("QueryResult:", memberResult.items);
        if (memberResult.items.length > 0) {
            // Mitglied gefunden, Zugriff auf das 'custom_sessions' Feld
            const memberData = memberResult.items[0];
            const sessionFieldValue = memberData.custom_sessions;

            if (sessionFieldValue !== undefined) {
                const currentSessions = Number(sessionFieldValue); // Umwandlung in eine Zahl, falls erforderlich

                // Vergleiche die aktuelle Anzahl der Sitzungen mit der festgelegten Grenze
                if (currentSessions > amountSessionsPerMember) {
                    return "notOk";
                } else {
                    return "Ok";
                }
            } else {
                console.log("Kein 'Sessions'-Feld für dieses Mitglied gefunden.");
                return "fieldNotFound"; // Gibt an, dass kein 'Sessions'-Feld gefunden wurde
            }
        } else {
            // Kein Mitglied mit dieser E-Mail gefunden
            console.log("Kein Mitglied mit der angegebenen E-Mail gefunden.");
            return "memberNotFound"; // Gibt an, dass kein Mitglied gefunden wurde
        }
    } catch (error) {
        console.error("Fehler beim Abrufen der Mitgliederdaten:", error);
        return "error"; // Gibt an, dass ein Fehler aufgetreten ist
    }
}

@CODE-NINJA any thoughts on this? I would really appreciate your help :wink:

Ok, well first of all, i like your code style/structure, continue like that.

  1. Did you try the old method? (i know → depricated, but still should work)… → using suppressAuth ?

EXAMPLE:

import wixData from 'wix-data';
// ...
let options = {
    "suppressAuth": true
};
wixData.query("myCollection")
  .find(options)
  .then( (results) => {
    if(results.items.length > 0) {
      let items = results.items;
      let firstItem = items[0];
    } else {
      // handle case where no matching items found
    }    
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );

About Members-APP, it’s collection and Members/FullData…

Let first collect some facts…
1) Members/FullData is a collection/database created especially for the Wix-Members-APP.
2) You manage your Members in the [Site Members] section of your dashboard.
3) Like most of those by Wix created collections, you have a limited query → (100).
4) The data is → READ <— ONLY.
5) And the FullData collection permissions can’t be changed.
6) To be able to get the data in authorized-mode → (elevation/suppressAuth), you have two options, out of my knowledge.

The first one → (suppressAuth) i already mentioned above.

The second and new one is the elevate function (which i have never used before if i am honest).

7) Such two methods allows a site visitor to call a function without the required permissions (normaly used by admin only). Meaning as soon as you use the elevate function → you turn an ordinary user somekind into an ADMIN, giving the right to read specific user-data.

8) You also have checked this…

Ok, till here i think everyting should be clear.

By the way, i see there are also 2 different import methods for the elevate function like it seems…

1)

   import * as wixAuth from 'wix-auth'; 
   const elevatedCreateMember = wixAuth.elevate(members.createMember);

2)

   import { elevate } from 'wix-auth';
   const elevatedQuery = elevate(wixData.query);

.
.
.
Back to Members/FullData… and your comment…

the “Members/FullData” App-Database is Read: Admin (btw. in the Docs it says it’s Read: All, but thats not true).

----> could you give me the docs you were reffering to ?

Is this you were reffering to …?

Yes, this is strange. A FullData, which is accessible for all, there must be something wrong, else the ELEVATIONT wouldn’t make any sense, wouldn’t it?

→ READ-ALL --------> is probably for → Members/PublicData
→ READ-ADMIN —> is for ----------------> Members/FullData

Public-Data is a non-sensitive-data, which do not include sensitive user-data.
The Full-Data includes all user-informations.

This would make sense.

1) Public-Data → read-all (anyone)
2) Full-Data ------> read with permissions (admin).

And here we go for more clarification… (this one seems to be ok)…

So there is for sure a mistake in the VELO-API-DOC about FullData-Permissions.

First try to read through all these informations, maybe it will already help you somehow to get your result. If not → then i will have to rebuild your use-case to go more into detail and inspect everything in CONSOLE.

By the way → console-logs are always very interessting for more detailed description.

…to be continued…

Link:

Seems like you are not the only one, who has problems with elevate-function…

Similar issue ?

And last thing where i looked at is…

Your code…

const elevatedQuery = elevate(wixData.query);
const memberResult = await elevatedQuery("Members/FullData")
            .eq("loginEmail", memberEmail)
            .find();
        console.log("QueryResult:", memberResult.items);

What about…?

const elevatedQuery = elevate( wixData.query("Members/FullData") );
const memberResult = await elevatedQuery().eq("loginEmail", memberEmail).find();
        console.log("QueryResult:", memberResult.items);

So i am also not 100% sure, since i did not really used it before → you will have to test it.

For reference… take a look here…

Let me know if you have found your SOLUTION.

Thank you for this extensive (first analysis) of the problem. As you have also seen, the Wix Documentation lacks in the details (again).

.
.
.

So first I now tried the suppressAuth Method, but this doesn’t override the standard “Admin” settings of the collection, unfortunately :frowning: :

.
.
.
Regarding the following: This then throws the error:

Argument of type 'WixDataQuery' is not assignable to parameter of type '(...arg: any) => any'. Type 'WixDataQuery' provides no match for the signature '(...arg: any): any'.

.
.
.
→ In conclusion I think it’s currently not possible to “give” access to the Members/FullData Collection to a regular Website Member. (At least through the ways we tried).

The main Goal im trying to achieve is to restrict the amount of Sessions one Member can have at the same time and I think I’ve found a workaround on doing that, I’ll post it in the “Made by the Community”-Feed shortly.

Thanks again for looking into it @CODE-NINJA :slight_smile:

1 Like

Would like to hear/read more opinions and informations about this issue from users who already worked with elevate function. Maybe there is more we do not know.

The elevate-function is a very new one, maybe it will be optimized in future.

Waiting for your analysis and results. :wink: