Local-userpass not working

Hello. I’ve got Google authentication working, but email/password authentication is not working properly. Here’s my code for register and login. When I run these functions I never enter the .then or .catch expressions, and only very rarely do they actually lead to a registration/login when I look at my list of users in Stitch. I’ve tried these functions without the async prefix as well, that also doesn’t work. Can anyone suggest what I need to do?

async function loginWithEmailFunction() {

    const app = stitch.Stitch.defaultAppClient

    const credential = new UserPasswordCredential(typedEmail.toString(), typedPassword.toString())

    const loginRes = await app.auth.loginWithCredential(credential)

    .then(authedUser => console.log(`successfully logged in with id: ${authedUser.id}`))

    .catch(err => console.error(`login failed with error: ${err}`))

}
async function registerWithEmailFunction() {

    const emailPasswordClient = stitch.Stitch.defaultAppClient.auth

    .getProviderClient(stitch.UserPasswordAuthProviderClient.factory);

    const registerRes = await emailPasswordClient.registerWithEmail(typedEmail.toString(),typedPassword.toString()) 

    .then(() => console.log("Successfully sent account confirmation email!"))

    .catch(err => console.log("Error registering new user:", err));

}

Hi Daniel – In this case you should be either using await or .then() . It seems like the issue here is likely due to a mix of await/promise syntax – Can you try using one or the other and letting us know if that addresses?

Hi Drew,

I tried both options, and neither has fixed the issues. I can’t spot any pattern, these functions very rarely result in the desired action in my list of stitch users.

I have amended the functions to the following using .then: however the process doesn’t enter the .then or .catch, it seems to redirect back to the same login page after running .registerWithEmail

function registerWithEmailFunction() {

    var typedEmail = document.getElementById("emailAddress").value;

    var typedPassword = document.getElementById("password").value;

    const emailPasswordClient = stitch.Stitch.defaultAppClient.auth

    .getProviderClient(stitch.UserPasswordAuthProviderClient.factory);
    
    emailPasswordClient.registerWithEmail(typedEmail.toString(),typedPassword.toString()) 

    .then(() => console.log("Successfully sent account confirmation email!"))

    .catch(err => console.log("Error registering new user:", err));

}
function loginWithEmailFunction() {

    var typedEmail = document.getElementById("emailAddress").value;

    var typedPassword = document.getElementById("password").value;

    const app = stitch.Stitch.defaultAppClient

    const credential = new UserPasswordCredential(typedEmail.toString(), typedPassword.toString())

    app.auth.loginWithCredential(credential)

    .then(authedUser => console.log(`successfully logged in with id: ${authedUser.id}`))

    .catch(err => console.error(`login failed with error: ${err}`))

}

Hi Daniel – Could you also provide some of the surrounding code for how these functions are called? If you like, you can DM me this.

Hi Drew, I’m not sure if you got the information I sent. I’ve included my login html here:

title
    <script>

        // const { Stitch, RemoteMongoClient, UserPasswordCredential, getProviderClient, getAuthProviderRoute, UserPasswordAuthProviderClient } = stitch;

        const client = stitch.Stitch.initializeDefaultAppClient('<App ID>');

        if (client.auth.hasRedirectResult()){

            client.auth.handleRedirectResult().then(user => {

                

                let redirectUrl = localStorage.getItem('redirectUrl');

                if (!redirectUrl) {

                    redirectUrl =   "/index.html";

                }

                window.location.replace(redirectUrl);

            });

        };

        // client.auth.logout().then(function() {

            // if (document.referrer === './pages/login.html')

            // {

                // localStorage.setItem('redirectUrl', "/index.html");                    

            // } else {

            //     localStorage.setItem('redirectUrl', document.referrer);

            // }

            

            // let credential = new stitch.GoogleRedirectCredential();

            // client.auth.loginWithRedirect(credential);

        // });

    </script> 

</head>

<body class="grey lighten-4"> 

    <nav class="z-depth-0">

      <div class="nav-wrapper container">

        <a href="/">title<span>title</span></a>

        <span class="right grey-text text-darken-1">

          <i class="material-icons sidenav-trigger" data-target="side-menu">menu</i>

        </span>

      </div>

    </nav>

    <ul id="side-menu" class="sidenav side-menu">

        <li><a class="subheader">title</a></li>

        <li><a href="/" class="waves-effect">Home</a></li>

        <li><a href="/pages/about.html" class="waves-effect">About</a></li>

        <li><div class="divider"></div></li>

        <li><a href="/pages/contact.html" class="waves-effect">

        <i class="material-icons">mail_outline</i>Contact</a>

        </li>

    </ul>

    <div class="container grey-text center">

        <h5>Welcome</h5>

        <br>   

        <h3 id="headerTag"></h3>

          <button class="loginBtn loginBtn--facebook">

            Login with Facebook

          </button>

           <br>

          <button class="loginBtn loginBtn--google"  id="google-login-btn">

            Login with Google

          </button>

        <br>    

        <p>-- or --</p>

    </div>

    

    <div class="row">

        <form class="sign-in container section" id="form-username-password">

        <div class="divider"></div>

        <div class="input-field">

            <input placeholder="" value="test5@test.com" id="emailAddress" type="text" class="validate"> 

            <label for="emailAddress">Email Address</label>

        </div>

        <div class="input-field">

            <input placeholder="" value="PwdStrong1" id="password" type="text" class="validate">

            <label for="password">Password</label>

        </div>

        <div class="input-field center">

            <button class="btn-small" id="emailPwd-login-btn">Login</button>

            <button class="btn-small" id="emailPwd-register-btn">Register</button>

        </div>

        </form>

    </div>

   

    <p><a id="emailPwd-reset-btn">I've forgotten my password</a></p>

    

</body>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script>

if (client.auth.isLoggedIn) {

        headerTag.innerText = "Logged in as " + client.auth.currentUser.id;

} else {

        headerTag.innerText = "Not logged in.";

}

</script>

<script>

$(document).ready(function(){

        // function logoutFunction() {

        //     document.getElementById("logout-btn").innerHTML = "Logging out!";

        //     client.auth.logout()

        // }

        $('#google-login-btn').click(function() {

            document.getElementById("google-login-btn").innerHTML = "Logging in!";

            let credential = new stitch.GoogleRedirectCredential();

            client.auth.loginWithRedirect(credential);

        })   

        $('#emailPwd-login-btn').click(function() {

            var typedEmail = document.getElementById("emailAddress").value;

            var typedPassword = document.getElementById("password").value;

            const app = stitch.Stitch.defaultAppClient

            const credential = new stitch.UserPasswordCredential(typedEmail.toString(), typedPassword.toString())

            console.log('login:', typedEmail.toString(),typedPassword.toString());

            app.auth.loginWithCredential(credential) // loginWithCredential

            .then(authedUser => console.log(`successfully logged in with id: ${authedUser.id}`))

            .catch(err => 

            console.error(`login failed with error: ${err}`))

        })

        $('#emailPwd-register-btn').click(function() {

            var typedEmail = document.getElementById("emailAddress").value;

            var typedPassword = document.getElementById("password").value;

            const emailPasswordClient = stitch.Stitch.defaultAppClient.auth

            .getProviderClient(stitch.UserPasswordAuthProviderClient.factory);

            

            console.log('register:', typedEmail.toString(),typedPassword.toString());

            emailPasswordClient.registerWithEmail(typedEmail.toString(),typedPassword.toString()) 

            .then(() => console.log("Successfully sent account confirmation email!"))

            .catch(err => 

            console.log("Error registering new user:", err));

        })

        $('#emailPwd-reset-btn').click(function() {

            var typedEmail = document.getElementById("emailAddress").value;

            if (typedEmail === "")

            {

                alert("enter email address");

            } else {

                const emailPassClient = stitch.Stitch.client.auth

                .getProviderClient(stitch.UserPasswordAuthProviderClient.factory);

                emailPassClient.sendResetPasswordEmail(typedEmail).then(() => {

                console.log("Successfully sent password reset email!");

                }).catch(err => {

                console.log("Error sending password reset email:", err);

                });

            }

        })

    })

</script>