Login redirect

Can somebody help me modify the code such that the user is redirected to a profile creation page on 1st login and from 2nd login onwards is redirected to members area?

Well!
First at all → do NOT show code as a pic!
Always show your code in a CODE-BLOCK (well formated).

A person like me would even not take a look onto your problem → knowing that i have to retype all your code from image first → i am a very lazy person :roll_eyes::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin::grin:
So provide your code in a CODE-BLOCK.

Second : I do not really understand what your code is doing?
Why all these DATA-QUERIES and INSERTS? For what?

Third: You should perhaps show your SETUP of the issued project-part.

  • Which elements are used?
  • How is the project-flow?
  • Perhaps even a little example & schreenshots?
  • Are dynamic pages involved? (then also show related DATABASE).

You need to insert your redirection code after line 25.

Something like: wixLocation . to (“/redirection_page”);

What happens is the check for new user has completed, The collection has been inserted with the new user and their email. And then you want to redirect to the new page.

To redirect members that have logged in more then once, you will need to add after line 36, another redirect code.

Thanks

@russian-dima

Firstly: Thanks for your response I just used the img. as given to me by wix support. But here you go;

import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;
import wixData from ‘wix data’

$w.onReady(function () {
wixUsers.onLogin((user)=>{
user.getEmail ()
.then ((email)=>{
let userEmail=email
wixData.query (“hasLoggedIn”)
.eq (“userEmail”, userEmail)
.find ()
.then ((results)=>{

if (reults.items.lengt=0){
let toInsert = {
“userEmail” : userEmail,
“hasLoggedIn” : true
}
wixData.insert (“hasLoggedIn” , toInsert)
.then ((result)=>{
wixLocation.to(“/custompage”)
})
} else if (results.iems.length > 0) {
user.getRoles ()
.then((roles) =>{
let role = roles [0]
let roleName = role.name
if (roleName ==“role 1 “) {
wixLocation.to(“/page 1”)
} else if (roleName == “role 2”) {
wixLocation.to (”/page 2”)
}
})
}
})
})
})
});

Secondly: I don’t know what DATA-QUERIES and INSERTS this means, I am non coder so no clue about these but I know the functioning of the code snip I sent.

Thirdly:
I am trying to create a custom members area, for which I am using the following;

  1. A custom registration: The member registration is something I control at my end i.e. I allow them and assign them roles. Members can view restricted pages as per their roles.

  2. A custom member profile creation: I have created a dynamic page for profile creation with respect to different roles. The dynamic pages work perfectly as I have checked them already.

  3. Custom login: Its just the usual login

  4. Custom Members area: Member role based different pages

Now what I am looking for;

I want the newly registered members who are assigned roles to be redirected to the custom member profile creation page on their first login and to their member role specific member pages from the second onwards

@sunilsangam94
I will take alook on this, and will give you tomorrow an answer, perhaps even an example. See you soon…

@russian-dima Thanks for your prompt response

Hey SS.94, I just noticed that the redirect was already in the code you provided. No need to add new ones. Line 24, points to the page you want to go for new registrations. Lines 32 & 34 redirect if the user has previously logged in, and the line is chosen based on their role.

What was it that you wanted to change? The page location or something else? Is the code not working as provided? Quickly scanning it, it looks good.

@sunilsangam94
Can you show the two related pages?

  1. custom member profile
  2. member role specific member page

Just to have better imaginations what you need.

By the way! In the meanwhile you can take a look at this Login-System →

https://russian-dima.wixsite.com/login-system

Which will provide soon all FEATURES & FUNCTIONS given in the SETUP of the shown Login-System.

As i understand, your wished function will be included, when the FINAL-VERSION is ready to go!

SORRY → it’s still in → DEVELOPEMENT :sweat_smile::sweat_smile::sweat_smile: (you can follow every single developed step → regarding the current published version in the right-upper corner…

SS.95, here some further info.

To help, here is what is what the codes does, that you were given.

  1. when the web page loads, it calls the onReady function (javascript code), after loading
  2. the onReady() function calls the WixUsers.onLogin function, the onLogin function returns a user object.
  3. the user object, contains several properties (variables), and methods (functions)
  4. the user.getEmail() method is called and it returns an email variable containing the email.
  5. the .then() waits for the email variable, and continues processing once it gets it
  6. the first WixData query, takes the email and looks in the ‘HasLoggedIn’ collection(table), to see if the user’s email exists in the table.
    If the user exists, then there will be a record containing his/her email, and the results.items.length will be >0.
    If the results.items.length is 0 ( ==0), then the record does not exist, therefore this is a new user who never logged in.
  7. the first if (==0) section deals with the new user, whose never logged in before:
    i) a new record is inserted into the ‘HasLoggedIn’ collection, containing the new email
    ii) the page is then directed to a page for the new user, you need to change this to yours
  8. the elseif, checks if there is at least one record in the ‘HasLoggedIn’ collection (table).
    i) if there is at least 1 ( >0), then this user has logged in before because a record exists with his email.
    ii) the user’s roleName is fetched from the ‘user.getRoles()’ function(method).
    iii) the next if, checks the roleName to confirm if the user belongs to ‘role1’, and if he/she does then they are forward to to the ‘/page1’ link.
    iv) the next elseif, checks if the user belongs to ‘role2’. If they belong to role2, then they get forwarded to the ‘role2’ page

There seems to be some pieces of missing info you got, that needs to be resolved.

  1. It looks like you will need to create a ‘HasLoggedIn’ collection(table) using the Content Manager. It needs to contain a field called ‘userEmail’. the naming of the field is important (case sensitive). The program won’t work if the name is not correct. The permissions of the collection should most probably be set to ‘Form Submission’

  2. If you don’t care about the roles, just if they have logged in, then you get rid of lines 29-36, and replace those lines with a single line: wixLocation.to(“/page1”); [remember you need to change /page1, to your actual page].

Hope this helps you move forward.

Thank you so much @pekrzyz for this detailed explanation. I completely misunderstood the code earlier. I’ll try to change wixlocation where necessary and check. Will update.

SS.94. One addtional update on the ‘HasLoggedIn’ table that you will need to create. It actually has a second field called ‘hasLoggedIn’.

So to summerize you will need to create a HasLoggedIn collection with 2 fields

  1. userEmail: type = text
  2. hasLoggedIn: type = boolean

Good luck!!!

Do I have to create a sperate dataset than the one that is precreated when we create custom login? and if so what kind of dataset. Would you please elaborate.

@pekrzyz Do I have to create a sperate dataset than default one which is created when we create custom login? and if so what kind of dataset. Would you please elaborate.

Also can we create a custom logout button? I am not using wix default members area so I am having difficulty getting the members to logout and even switch between member page. I fixed the member page switching by using dropdown menus with redirect option but I can’t figure out how to enable the user to Logout

To answer your question, you will need to create a new ‘HasLoggedIn’ collection. I checked my collections and it is not automatically there. But you can check you collections to see if the ‘HasLoggedIn’ collection exists. Remember it needs those 2 fields.

I was doing a bit of research on the permissions that I suggested and I don’t think this will work in your case.

I think the Form Submission is the wrong permission (it is too restrictive) in this case.

Check this youtube video on Collections and permissions:

He talks about permissions arount 3:30 minutes. I have no affiliation or know this person.

What you have to think about is that this is a new user. He/she probably isn’t a member yet (if you are using that feature) or not approved yet, so won’t have any permissions setup to the website.

In order to check the email for this new user who will have no permissions, we have to be more liberal with the permissions we need in order to successfully complete the test to see if the user is already registered.

We need to have enough permissions, so when this user connects to your website that the code works. The code reads data from the collection and writes data to the collection. Therefore anybody has to be able to read it, and anybody has to be able to write it. Only admins should be allowed to update or delete the data from the collection.

A custom permission will solve this. Check the video on how its done. With all the websites being hacked these days, I personally tend to move some of these checks to the backend so they are hidden and can’t be detected if somebody looks at your code.

Since the example given to you, places the code in the front end, the name of the collection is visible to everyone. Someone looking through your code could get the name of your collection. I often take these types of lookup functions and write functions and put them into the backend code. (.jsw file) This protects things like the name of the database.

For example, a backend function could lookup the ‘HasLoggedIn’ and only return a true or false. Your front end code would only pass in the email, and then get back a true or false and continue from there. The code in the backend is not made visible on the website and is more protected. The same thing would be with the writing of the new email to the ‘HasLoggedIn’ table. By taking the email, and moving the write function to the backend, would hide, where the email is being saved.

In fact, because the code is in the backend, in theory, you could check if the email exists, and if not, write out to the collection right away in the same function call, saving having to write it out in a separate step as it is currently being done. You would still need the true/false being returned so you knew what web page to continue to, based on the outcome if the record exists or not.

One aside, Wix has a feature that allows you to override more restictive permissions when executing code in the backend. This means you can leave the more restrictive permissions on the collection, but in the backend code, override the restiction in order to do a search on the table. The advantage of this is that you can prevent anybody from reading the data in the collection, but still allow them to save information. I have done this in the past. Wix has a tutorial on how to override permissions at: https://www.wix.com/velo/forum/tips-tutorials-examples/tutorial-how-to-bypass-collection-permissions-and-hooks

I’m trying not to overwhelm you, just making you aware of the issues you will have to deal with/face.

@pekrzyz Thanks again understood what you said. And the hasloggedIn doesn’t exist but a members data does exit but its read only and at the back end and also records the number of logins and last logins. I tried using that directly but it didn’t work, So I’ll just create a new dataset with hasloggedIn with red write to anyone and update by admin, I am aware of how to do this as I have done it for profile creation.

Last question @pekrzyz Also can we create a custom logout button? I am not using wix default members area so I am having difficulty getting the members to logout and even switch between member page. I fixed the member page switching by using dropdown menus with redirect option but I can’t figure out how to enable the user to Logout

Thanks your answers have helped me tons

I’ve provided the backend code that checks the user email address. Here it is:
----------- begin code ----------------
import wixData from ‘wix-data’;

export async function checkUserEmail(email) {
// convert email to uppercase, remove all spaces
let scrubbedEmail = email.toUpperCase().split(" “).join(”");

let options = { 
    "suppressAuth": true, 
    "suppressHooks": true 
}; 

return wixData.query("HasLoggedIn") 
    .eq("userEmail", scrubbedEmail) 
	.find( options ) 
	.then( (results) => { 
        if (results.items.length == 0) { 
        // didn't find email in table so save it 
            let toInsert = { 
                "userEmail": scrubbedEmail, 
                "hasLoggedIn": true 
            } 
            wixData.insert("HasLoggedIn", toInsert, options) 
            return false; 
        } else { 
	//found email 
            return true; 
        } 
    }) 
    .catch( (error) => { 
        console.log("[checkRegistered:]\n" + error.message); 
    }) 

}
----------- end code ----------------
I saved this in a backend web module called: checkRegistered.jsw

What I did, was convert the email to all capitals and removed any spaces. This reduces chances of user mistyping or typing in their email in uppercase one time and lowercase another time. By always saving the emails in one case, makes it much easier to confirm variations of the same email being typed in. As well, emails shouldn’t have spaces, so I strip any spaces from the email.

I then take this scrubbed email and test to see if it exists in the table. If it does not exist, then I add it to the table, but return false (indicating this is a new user and it was not found).
If I find the email in the table, then I return true. I only need to test if the length of the array (results.items) is zero, because if it contains something it is always greater than zero. Therefore I don’t specifically need to test for it using else if. Since it can only be zero, or a positive number, the else is fine.

So when you call the code, you get returned a true or false. False for new user, True for user that exists or has logged in previously.

I also bypassed the security using the options feature. Therefore you can leave your table security set to ‘Form Submission’. This means that anybody can save to the table, but only admins can read the table or manipulate it.

Here is a picture of your HasLoggedIn collection (table). I set the userEmail field to ‘Make Primary’, and set the sort on it to (Sort from A-Z).

Here is the new front end code for your login page. It no longer directly reads or writes to the collection/table, making it much more safer (secure).

--------------------- begin coded ---------------------------------
import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;
import {checkUserEmail} from ‘backend/checkRegistered’;

$w.onReady(async function () {
wixUsers.onLogin((user)=>{
user.getEmail()
.then ( (email) => {
let found = await checkUserEmail( email );

        if ( !found ) {  
            // user is new, never logged in before 
            wixLocation.to("/custompage");  
        } else { 
            // user was found, previously logged in 
            user.getRoles () 
            .then((roles) =>{ 
                let role = roles [0] 
                let roleName = role.name  
                if (roleName ==="role 1 ") { 
                    wixLocation.to("/page 1");  
                } else if (roleName === "role 2") { 
                    wixLocation.to("/page 2"); 
                } 
            }) 
        } 
    }) 
}) 

});

--------------------- end code ------------------------------

I googled the button logout code and found this:

It suggests that you add this to your mouse event, although you can just as well add it to to your button_click event.

export somebutton_click(event) {
if (wixUsers.currentUser.loggedIn) {
// log the user out
wixUsers.logout();
wixLocation.to (‘/’);
}
}

Hi, @pekrzyz I am getting this error on line 26 for the await -

‘await’ expressions are only allowed within async functions and at the top levels of modules.
Parsing error: Cannot use keyword ‘await’ outside an async function

And the logout button code has errors to. I read the article for the logout you posted but thats not working for me as it keeps showing errors.

The await error is usually caused by a missing async word that has to be put infront of the function line.

EG: $w.onReady(async function () {

I did try the button code and it works fine for me.
Did you remember to add these 2 lines at the top of the module which contains the button code.

import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;

@pekrzyz yea I did put the import part in the code.

The login is still not working, there are no errors in the code i.e. no red lines for either the login code or the backend file but its still not working.