用户名是否为html中的每个登录重复?

时间:2019-03-26 05:59:13

标签: javascript html firebase firebase-authentication

我一直在使用Firebase Cloud Firestore。我的问题是,当用户登录时,用户名显示在带有下拉选项帐户,付款和注销的标题上。当用户注销并使用相同或另一个帐户详细信息再次登录时,用户名会继续添加具有先前登录用户名的标题。

注意:这里我正在使用Firebase身份验证和Cloud Firestore数据库。

这是我的屏幕截图:

enter image description here

$(document).ready(function(){
  //initialize the firebase app
  var config = {
     apiKey: "AIzaSyBDwqFKPt4D0eIspjsziweLI0nc49BRDrU",
    authDomain: "cloudthrifty-demo.firebaseapp.com",
    databaseURL: "https://cloudthrifty-demo.firebaseio.com",
    projectId: "cloudthrifty-demo",
    storageBucket: "cloudthrifty-demo.appspot.com",
    messagingSenderId: "638814042535"
  };
  firebase.initializeApp(config);

  //create firebase references
  var Auth = firebase.auth(); 
  var dbRef = firebase.database();
  var contactsRef = dbRef.ref('contacts')
  var usersRef = dbRef.ref('users')
  var auth = null;
  var db = firebase.firestore();

  //Register
  $('#registerForm').on('submit', function (e) {
    e.preventDefault();
    $('#registerModal').modal('hide');
    $('#messageModalLabel').html(spanText('<i class="fa fa-cog fa-spin"></i>', ['center', 'info']));
    $('#messageModal').modal('show');
    var data = {
      email: $('#registerEmail').val(), //get the email from Form
      firstName: $('#registerFirstName').val(), // get firstName
      lastName: $('#registerLastName').val(), // get lastName
    };
    var passwords = {
      password : $('#registerPassword').val(), //get the pass from Form
      cPassword : $('#registerConfirmPassword').val(), //get the confirmPass from Form
    }
    if( data.email != '' && passwords.password != ''  && passwords.cPassword != '' ){
      if( passwords.password == passwords.cPassword ){
        //create the user
          firebase.auth().createUserWithEmailAndPassword(data.email, passwords.password).catch(function(error) {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;

          })
          .then(function(user){
            //now user is needed to be logged in to save data
            auth = user;
            //now saving the profile data
          
          var uid = firebase.auth().currentUser.uid;
          console.log(uid);
          db.collection("users").doc(uid).set({
            name: data.firstName
            
        })
        .then(function() {
            console.log("Document successfully written!");
            $('#messageModal').modal('hide');
            $('.modal-backdrop').remove();
        })
        .catch(function(error) {
            console.error("Error writing document: ", error);
            $('#messageModal').modal('hide');
            $('.modal-backdrop').remove();
        });


            $('#messageModalLabel').html(spanText('Success!', ['center', 'success']))
            
            $('#messageModal').modal('hide');
            $('.modal-backdrop').remove();

          })
          .catch(function(error){
            console.log("Error creating user:", error);
            $('#messageModalLabel').html(spanText('ERROR: '+error.code, ['danger']))
            
          });
      } else {
        //password and confirm password didn't match
        $('#messageModalLabel').html(spanText("ERROR: Passwords didn't match", ['danger']))
      }
    }  
  });

  //Login
  $('#loginForm').on('submit', function (e) {
    e.preventDefault();
    $('#loginModal').modal('hide');
    $('#messageModalLabel').html(spanText('<i class="fa fa-cog fa-spin"></i>', ['center', 'info']));
    $('#messageModal').modal('show');

    if( $('#loginEmail').val() != '' && $('#loginPassword').val() != '' ){
      //login the user
      var data = {
        email: $('#loginEmail').val(),
        password: $('#loginPassword').val()
      };
      firebase.auth().signInWithEmailAndPassword(data.email, data.password)
        .then(function(authData) {
          auth = authData;
          $('#messageModalLabel').html(spanText('Success!', ['center', 'success']))
          $('#loginModal').modal('hide');
          $('#messageModal').modal('hide');
          $('.modal-backdrop').remove();
        })
        .catch(function(error) {
          console.log("Login Failed!", error);
          $('#messageModalLabel').html(spanText('ERROR: '+error.code, ['danger']))
          $('#messageModal').modal('hide');
          $('.modal-backdrop').remove();
        });
    }
  });

  $('#logout').on('click', function(e) {
    e.preventDefault();
    
    firebase.auth().signOut().then(function() {
      // Sign-out successful.
      // window.location='index.html';
    }).catch(function(error) {
      // An error happened.
    });
  });

  //save contact
  $('#contactForm').on('submit', function( event ) {  
    event.preventDefault();
    if( auth != null ){
      if( $('#name').val() != '' || $('#email').val() != '' ){
        contactsRef.child(auth.uid)
          .push({
            name: $('#name').val(),
            email: $('#email').val(),
            location: {
              city: $('#city').val(),
              state: $('#state').val(),
              zip: $('#zip').val()
            }
          })
          document.contactForm.reset();
      } else {
        alert('Please fill at-lease name or email!');
      }
    } else {
      //inform user to login
    }
  });

  // firebase.auth().onAuthStateChanged(function(user) {
  //   if (user) {
  //     auth = user;
  //     $('body').removeClass('auth-false').addClass('auth-true');
  //     usersRef.child(user.uid).once('value').then(function (data) {
  //       var info = data.val();
  //       console.log(info);
  //       // if(user.photoUrl) {
  //       //   $('.user-info img').show();
  //       //   $('.user-info img').attr('src', user.photoUrl);
  //       //   $('.user-info .user-name').hide();
  //       // } else if(user.displayName) {
  //       //   $('.user-info img').hide();
  //       //   $('.user-info').append('<span class="user-name">'+user.displayName+'</span>');
  //       // } else if(info.firstName) {
  //       //   $('.user-info img').hide();
  //       //   $('.user-info').append('<span class="user-name">'+info.firstName+'</span>');
  //       // }
  //     });
  //     contactsRef.child(user.uid).on('child_added', onChildAdd);
  //   } else {
  //     // No user is signed in.
  //     $('body').removeClass('auth-true').addClass('auth-false');
  //     auth && contactsRef.child(auth.uid).off('child_added', onChildAdd);
  //     $('#contacts').html('');
  //     auth = null;
  //   }
  // });

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      // User is signed in.
      auth = user;
      var uid = firebase.auth().currentUser.uid;
      console.log(uid);
      $('body').removeClass('auth-false').addClass('auth-true');
      db.collection("users").doc(uid)
    .onSnapshot(function(doc) {
        console.log("Current data: ", doc.data());

        var name = doc.data().name
        $('.user-info').append('<span class="user-name">'+name+'<span class="caret"></span></span>');
        console.log(name);
    });
    } else {
      // User is signed out.

      $('body').removeClass('auth-true').addClass('auth-false');
      auth && contactsRef.child(auth.uid).off('child_added', onChildAdd);
      
      $('#contacts').html('');
      auth = null;
    }
  });
});

function onChildAdd (snap) {
  $('#contacts').append(contactHtmlFromObject(snap.key, snap.val()));
}
 
//prepare contact object's HTML
function contactHtmlFromObject(key, contact){
  return '<div class="card contact" style="width: 18rem;" id="'+key+'">'
    + '<div class="card-body">'
      + '<h5 class="card-title">'+contact.name+'</h5>'
      + '<h6 class="card-subtitle mb-2 text-muted">'+contact.email+'</h6>'
      + '<p class="card-text" title="' + contact.location.zip+'">'
        + contact.location.city + ', '
        + contact.location.state
      + '</p>'
      // + '<a href="#" class="card-link">Card link</a>'
      // + '<a href="#" class="card-link">Another link</a>'
    + '</div>'
  + '</div>';
}

function spanText(textStr, textClasses) {
  var classNames = textClasses.map(c => 'text-'+c).join(' ');
  return '<span class="'+classNames+'">'+ textStr + '</span>';
}
*, *:before, *:after {
  box-sizing: border-box;
}

html {
  overflow-y: scroll;
}

body {
  background: #fff;
  font-family: 'Titillium Web', sans-serif;
}

a {
  text-decoration: none;
  color: #4F5459;
  transition: .5s ease;
}
a:hover {
  color: #71D72C;
}



/* @media only screen and (min-width: 640px) and (orientation: portrait) {



}


@media only screen and (min-width: 640px) and (orientation: landscape) {

} */


.userAuth {
  display: block;
  margin: 0px 0 0;
}
.modal-header:last-child{
  border-bottom: 0;
}
.card {
  display: inline-block;
  margin: 1em;
  max-width: calc(25% - 2em);
}

.user-info {
  display: inline-block;
  margin: 0 0.5em;
}
.user-info img{
  display: inline-block;
  max-width: 2em;
}

.auth-true .authenticated,
.auth-false .unauthenticated {
  display: block;
}
.auth-true .unauthenticated,
.auth-false .authenticated {
  display: none;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Sign-Up/Login Form</title>
    <!-- Bootstrap -->
   
    <link href='https://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
      <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
  

        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" href="css/captcha.css">
  
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body onLoad="ChangeCaptcha()" class="auth-false">

      <nav class="navbar navbar-default" style="background-color: #6c757d; min-height: 50px"> 
          <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" style="color: aliceblue; font-size: 25px" href="#">demo</a>
            </div>
        
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
              <ul class="nav navbar-nav navbar-right" >
                <!-- <li class="active" ><a href="#" style="color: #4F5459; font-size: 18px; font-weight: 600">What We Do <span class="sr-only">(current)</span></a></li> -->
                <li><a href="#" style="color: #4F5459; font-size: 18px; font-weight: 600">menu1</a></li>

                <li><a href="#" style="color: #4F5459; font-size: 18px; font-weight: 600">menu2 </a></li>
                <li><a href="#" style="color: #4F5459; font-size: 18px; font-weight: 600">menu3</a></li>
                <li><a href="#" style="color: #4F5459; font-size: 18px; font-weight: 600">menu4</a></li>
               
                <!-- <li><button type="button" class="btn navbar-btn  userAuth unauthenticated" style="color: #4F5459; font-size: 18px; font-weight: 600; background-color: #ffffff00; outline: 0; box-shadow: none!important;" data-toggle="modal" data-target="#registerModal">Register</button></li> -->
                <li><button type="button" class="btn navbar-btn  userAuth unauthenticated" style="color: #4F5459; font-size: 18px; font-weight: 600; background-color: #ffffff00; outline: 0; box-shadow: none!important;" data-toggle="modal" data-target="#loginModal">Login</button></li>
               <!-- <li><a href="#" class=" userAuth authenticated user-info" style="color: #71D72C; font-size: 18px; font-weight: 600" alt="User"></a></li> -->
               <!-- <li><span class="userAuth authenticated user-info"><img src="./user.svg" alt="User" class="rounded-circle"></span></li> -->

               <!-- <div class="userAuth authenticated pull-right">
                  <span class="user-info">
                    <img src="./user.svg" alt="User" class="rounded-circle">
                  </span>
                  <button type="button" class="btn btn-success" id="logout">Logout</button>
                </div> -->
                <!-- <li><button type="button" class="btn navbar-btn userAuth authenticated" id="logout"   style="color: #4F5459; font-size: 18px; font-weight: 600; background-color: #ffffff00; outline: 0; box-shadow: none!important;">Logout</button></li> -->

                <button class="btn  navbar-btn userAuth unauthenticated" style="background-color: #71D72C; color: #4F5459; font-size: 18px;">Free Trail</button>


                <li class="dropdown">
                  <a href="#" id="options" class="navbar-btn dropdown-toggle userAuth authenticated user-info" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" style="color: #fff; font-size: 18px; font-weight: 600; background-color: #ffffff00;" alt="User"></a>
                  <ul class="dropdown-menu">
        
                      <li><a href="#" role="button" class="btn  userAuth authenticated" id="Account"  style="color: #4F5459; font-size: 18px; text-align: left;" >Account</a></li>
                      <li><a href="#" role="button" class="btn  userAuth authenticated" id="Scheduler"  style="color: #4F5459; font-size: 18px; text-align: left;" >payment</a></li>
                      <li><a href="#" role="button" class="btn  userAuth authenticated" id="logout"  style="color: #4F5459; font-size: 18px; text-align: left;" >Logout</a></li>

                  </ul>
                </li>
              </ul>

            </div><!-- /.navbar-collapse -->
          </div><!-- /.container-fluid -->
        </nav>
        <main class="authenticated">
          <center>
              <h1>welcome to cloud thrifty</h1>
          </center>
          <div id="contacts"></div>
        </main>
        <div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="Register" aria-hidden="true" >
          <div class="modal-dialog">
            <div class="modal-content">
              <form id="registerForm" method="POST">
                <div class="modal-header">
                  <h4 class="modal-title" id="registerModalLabel">Register</h4>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                  <div class="form-group">
                    <label for="recipient-name" class="control-label">First Name:</label>
                    <input type="text" class="form-control" id="registerFirstName"required>
                    
                  </div>
                  <div class="form-group">
                    <label for="recipient-name" class="control-label">Last Name:</label>
                    <input type="text" class="form-control" id="registerLastName"required>
                  </div>
                  <div class="form-group">
                    <label for="recipient-name" class="control-label">Email:</label>
                    <input type="text" class="form-control" id="registerEmail"required>
                  </div>
                  <div class="form-group">
                    <label for="message-text" class="control-label">Password:</label>
                    <input type="password" class="form-control" id="registerPassword"required>
                  </div>
                  <div class="form-group">
                    <label for="message-text" class="control-label">Confirm Password:</label>
                    <input type="password" class="form-control" id="registerConfirmPassword"required>
                  </div>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn pull-left" data-toggle="modal" data-target="#loginModal" data-dismiss="modal" style="background-color: #71D72C; border: 0px; color:#fff;">Login</button>
                  <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-primary" id="doRegister" style="background-color: #71D72C; border: 0px">Register</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="Login" aria-hidden="true" >
          <div class="modal-dialog">
            <div class="modal-content">
              <form id="loginForm" method="POST">
                <div class="modal-header">
                  <h4 class="modal-title" id="loginModalLabel">Login</h4>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                
                <div class="modal-body">
                  <div class="form-group">
                    <label for="recipient-name" class="control-label">Email:</label>
                    <input type="text" class="form-control" id="loginEmail"required>
                  </div>
                  <div class="form-group">
                    <label for="message-text" class="control-label">Password:</label>
                    <input type="password" class="form-control" id="loginPassword"required>
                  </div>
                  <div class="form-group">
                      <button class="btn pull-right" style="background-color: #ffffff00; color: #4F5459; font-size: 14px; text-align: left">Forgot password?</button><br>
                    </div>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-primary pull-left" data-toggle="modal" data-target="#registerModal" data-dismiss="modal" style="background-color: #71D72C; border: 0px;color:#fff;">Register Now</button>
                  <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-primary" id="doLogin" style="background-color: #71D72C; border: 0px" >Login</button>
                </div>
              </form>
            </div>
          </div>
        </div>

        
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

    <!-- Firebase App is always required and must be first -->
    <!-- <script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-app.js"></script> -->

    <!-- Add additional services that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-messaging.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-functions.js"></script>

    <!-- Comment out (or don't include) services that you don't want to use -->
    <!-- <script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-storage.js"></script> -->

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
  
    <!-- <script  src="js/index.js"></script> -->
    <!-- <script  src="js/login.js"></script> -->
    <!-- <script  src="js/captcha.js"></script> -->
    <script src="js/script.js"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

每次用户的身份验证状态更改(即他们登录或注销)时,您都可以执行以下操作:

$('.user-info').append('<span class="user-name">'+name+'<span class="caret"></span></span>');

因此,您要将它们的新状态附加到.user-info元素的现有内容中。

要替换现有值,请使用.html而不是.append

$('.user-info').html('<span class="user-name">'+name+'<span class="caret"></span></span>');