Log in to website using fields from database (without email)

Hi all,

I am essentially trying to create a password protected site for a database of contacts that do not have email addresses. I would like the list of contacts to be able to “sign in” to my site using fields from the database (“employeeNumber” and “password”).

I have found similar posts related to this topic, but none that seem to be close enough to work.

Here is my current code ( copied from this thread ):

import wixUsers from 'wix-users';
import wixData from 'wix-data';
import wixLocation from 'wix-location';

export function button1_click(event) {
    wixData.query("contacts")
    .eq("employeeNumber", $w("#employeeNumber").value)
    .find()
    .then( (results) => {
        if(results.items.length > 0) {
            let items = results.items;
            let password = items[0].password;
            let loggedID = items[0].id;
            if (password === $w('#password').value) {
                console.log("Logged In");
                wixLocation.to("/main-content"+ loggedID);
            }else {
                console.log("Password Incorrect");
            }
        }
        else {
            console.log("No Employee Found");
        }
    })
} 

If there is another way to handle this or the code is incorrect, any help on a solution would be greatly appreciated!

I don’t think that’s the best approach (since these members won’t be system members and you won’t be able to use all members functionality such as page permissions/ members api / members area etc…).

I suggest to do the following instead:

  1. Create a custom sign-up/login form

  2. In this form have 2 fields: >> Username/Email; >> Password

  3. When the user fills-in the first field, run regex to detect whether it’s an email address or a name

  4. If it is a name → generate a fake email address (behind the scenes. The member will never know about it). For example let’s say your own domain is mysite.com and let’s say the name input is: John Doe , - change it to lowercase and replace all spaces by underscore
    john_doe@mysite.com

Now, register the user using these email and password:
https://www.wix.com/velo/reference/wix-members/authentication/register

and every time the member fills the log-in field use this email & password to log in.

And if you won’t to allow registration by name to a predefined contact list, just run a query against the predfinedContacts list, and register the user (like described in my previous comment) only if they appear in the list.

Hi J.D.

Thanks for the info. I think this is on the right track. I have a couple more requirements that may determine if this is doable.

The “Username” needs to be a number. It will be 6 digits, numerical only.
What is the process to generate a fake email address? I haven’t come across function in Wix documentation.

If this works correctly, the person logging in will be able to input their user number and password - for the first time - and log into the site? Without signing up as a member? Ideally this is how I’d like it to function, I have a CSV with all users login number and password, but these users do not have email addresses.

I’d like them to not have to “sign up” using the wix system, and be able to login upon first time visiting the page.

Thanks.

As I said, I think the best way will be to create a Wix member behind the scenes.
And yes, you can use 65485112@mysite.com

If for some reason you don’t want them to be site members at all, you can just query collection where you stored username and pw (but make sure the type is correct. “5468” as string is not equal to 5468 as number) but for security reason, you should not retrieve the password to the fornt-end, just test the match on the backend.

Hi J.D.

I’m still having trouble with exactly how to create a member behind the scenes.
What is the process to create this function?
Will the user need to “sign up” to the site before being able to log in with the potential user number? (ideally I can import all contacts via a CSV and they will be able to sign in with user number).

Using register via wix-members sounds like it will work, but I’m not sure what will happen upon first time signing into the site…

Thanks again for the help.

Please attach a csv for example, because I don’t know what field you have there.
Basically after you import the csv (I’ll assume it contains phone number and password), then you run a query and retrieve all these members. Add to the database a new field registered (Boolean)
and you do something like:

//backend file:
import wixData from 'wix-data';
import { authentication } from 'wix-members-backend';
export function registerMembers(){
let hasNext = false;
let items;
return wixData.query('ImportedMembersCollection')
.ne('registered', true)
.limit(20)
.find()
.then(r => {
hasNext = r.hasNext();
items = r.items.map(e => {e.registered = true; return e;});
return items.map(e => authentication.register(e.phone + '@mysite.com', e.password))
})
.then(() => wixData.bulkUpdate('ImportedMembersCollection', items))
.then(() => {
if(hasNext){return registerMembers();}
console.log('done');
return 'done'
})
}

And run this function (you can click the triangle that located before the export to run it from the editor)

P.S, I haven’t tried it, and there may be some typos etc… try and see if it works for you

Below are the fields the CSV will have. User Name/Login will be the employee number associated with each contact. There will be an email field, but for most users this will be blank (some might have email, but could be easy to just delete for everyone, if we are replacing the email field with a login or fake email).

Username | Password | Name | Address | Email | Phone
123456 | crh1234 | Joe | 123 Main | | 555-5555

From your previous comments, it sounds like if I import all these as contacts, when they try to login with username (6-digit number) and their assigned password, the backend will create/add them as a member, and login will be successful. This sounds like what I want, if it works that way.

Let me know if this sounds correct or doable, and if the code you provided above still applies.


After you import them, run the query I posted.

  • create a custom login page where they have to put in phone and password,
    when the click “Connect” run login function to connect them.
    Using the @mysite.com and the password:

https://www.wix.com/velo/reference/wix-members/authentication/login

I am trying to implement and test this now.

I am getting errors on:

import { authentication } from ‘wix-members-backend’ ;

Should this be ‘wix-members’ instead? The system is not recognizing ‘wix-members-backend’

export registerMembers (){

This is also an unrecognized error.

Is it possible to change the phone field to an employee number? ‘Phone’ seems to be a field recognized in the system, I am having trouble connecting the fields to my user collection. I am using the custom Member Login form lightbox. I’m not sure if I should create a custom form/input fields and connect them to the collection, or to my contact list so that the backend code can add the contacts as members.

Apologies for not fully understanding what to do here… I have not worked with Wix contacts/members before and the backend system seems very limited. Appreciate the help

For those who have problems to work with wix-members-backend-API…

BACK-END-CODE … (including some modifications)

import { members } from 'wix-members-backend';
import { currentMember } from 'wix-members-backend';

//------ GET-CURRENT-MEMBER --------------
export function getCurrentMember() {let options = {fieldsets: [ 'FULL' ]};
  return currentMember.getMember(options)
    .then(async(member) => {        
        let originalRoles = await myGetRolesFunction();
        let originalMemberData = await getMemberData(member._id, options);

      let generatedMemberData={
         memberID:originalMemberData._id,
         nickname:originalMemberData.profile.nickname,
         email:originalMemberData.loginEmail,
         firstname:    
         originalMemberData.contactDetails.firstName,
         lastname:
         originalMemberData.contactDetails.lastName,
         roleID: originalRoles[0]._id,
         roleTitle: originalRoles[0].title,
         roleColor: originalRoles[0].color
         phone:     
         originalMemberData.contactDetails.phones[0],
         imgProfile:         
         originalMemberData.profile.profilePhoto.url,    
        }
        return ({"Current-Member": member, "Original-Member-Data": originalMemberData, "generatedMemberData": generatedMemberData, "originalRoles": originalRoles});        
    }).catch((error) => {console.error(error);});
}


//---------- GET-MEMBER-INFO -----------------------
export function getMemberData(id, options) {
    return members.getMember(id, options)
    .then((memberData) => {
        const slug = memberData.profile.slug;
        const name = `${memberData.contactDetails.firstName} ${memberData.contactDetails.lastName}`;
        const contactId = memberData.contactId;

        return memberData;
    }).catch((error) => {console.error(error); return error});
}

All you have to do is to generate FRONT-END-CODE for this backend-example.

You can even expand its functionality to make it perfect.

EDIT: FRONT-END:


import {getCurrentMember} from 'backend/xxx.jsw'
import { authentication } from 'wix-members';

$w.onReady(async(()=> {
    let query = [], repData = [];
    let data, memberData, memberID, generalData;
   
    if(authentication.loggedIn()) {
        console.log(authentication.loggedIn);
        data = await getCurrentMember();                                                                                            
        memberData = await data.generatedMemberData;    
        memberID = memberData.memberID;
        console.log("User-ID: ", memberID);

        //START ANY FUNCTION HERE...
        start_myFunction ();
    
        //Even checking for members current ROLE....
        if(memberData.roleTitle==="Admin") {...} 
        else {...}
    }
    else{console.log("User not logged-in!!!");}
});

You should put it in a backend file, not in front-end page code.
So you can click the arrow and run it on a new tab (see images).
Also I fixed some syntax errors in my code. See above.

First click this little arrow:

Then click the tab (sometimes need to be clicked twice) and RUN: