【发布时间】:2018-03-02 12:18:49
【问题描述】:
我尝试在我的 Node + Express 应用程序中实现 firebase 身份验证。但无法弄清楚如何使用电子邮件和密码对用户进行身份验证。如果有教程或示例项目会很有帮助。
【问题讨论】:
标签: node.js express firebase-authentication
我尝试在我的 Node + Express 应用程序中实现 firebase 身份验证。但无法弄清楚如何使用电子邮件和密码对用户进行身份验证。如果有教程或示例项目会很有帮助。
【问题讨论】:
标签: node.js express firebase-authentication
我知道这可能会帮助像 Shams Nahid 这样需要帮助的人,我会为此推荐 firebase 身份验证教程。 Firebase Authentication Tutorial using
要使用 firebase、Node js 和 express 实现用户登录,请按照以下简单步骤操作
第 1 步。遵循有关 firebase 身份验证的文档How to use email and password to sign in
第 2 步。创建 login.ejs 文件
<!doctype html>
<html>
<head> <title>Login into your account</title>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-auth.js"</script>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-firestore.js"
</script>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-database.js">
</script>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-
awesome/4.0.3/css/font-awesome.min.css">
<style>body{padding-top:80px;}</style>
</head>
<body>
<div class="container " >
<div class="col-sm-6 col-sm-offset-3 ">
<h1><span class="fa fa-sign-in"></span> Login</h1>
<!-- LOGIN FORM -->
<fieldset>
<div class="form-group">
<label>Email</label>
<input type="email" id="txtemail" value="" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="txtpassword" value="" class="form-
control">
</div>
<button type="submit" id="loginButton" onclick="signInUsers()"class="btn
btn-warning"><a href="/login">Login</a>
</button>
<button type="submit" id="logoutButton" onclick="logout()"class="btn btn-
warning">logout</button>
</fieldset>
<hr>
</div>
</div>
<script src="/js/firebase.js"></script>
</body>
</html>
步骤 3. 创建身份验证脚本
firebase.js
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "INSERT HERE YOUR API FROM FIREBASE CONSOLE",
authDomain: "INSERT YOUR DOMAIN",
databaseURL: "INSERT YOUR DATABASE URL",
projectId: "INSERT HERE YOUR PROJECT ID",
storageBucket: "canon-4f6d8.appspot.com",
messagingSenderId: "INSERT HERE YOUR MESSAGING ID FROM FIREBASE",
appId: "1YOUR APP ID FROM FIREBASE"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
function signInUsers(){
var email = document.getElementById('txtemail').value;
var pass = document.getElementById('txtpassword').value;
firebase.auth().signInWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
//check if user is logged in or not
function checkIfLogedIn(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) { // if the user is logged in
console.log(user)
var emailv =user.email;
console.log("User is signed in. with email: "+ emailv);
document.getElementById('loginButton').setAttribute('style','display: none;visibility: hidden;');
document.getElementById('logoutButton').setAttribute('style','display: inline-block;visibility: visible;')
} else { // if the user is not logged in
console.log("No user is signed in.");
document.getElementById('loginButton').setAttribute('style','display: none;visibility: visible;');
document.getElementById('logoutButton').setAttribute('style','display: inline-block;visibility: hidden;')
}
});
}
window.onload=function(){
checkIfLogedIn()
}
function logout(){
firebase.auth().signOut();
checkIfLogedIn()
}
第 3 步。创建您将要运行的 app.js 脚本
app.js 文件
var express=require('express')
var logger=require('morgan')
var passport = require('passport');
var bodyParser=require('body-parser')
var admin=require('firebase-admin')
var path = require('path');
var serviceAccount=require('./canon-serviceKey.json')
var firebaseAdmin=admin.initializeApp({
credential:admin.credential.cert(serviceAccount),
databaseURL: "INSERT YOUR FIREBASE DB URL"
})
///database reference
var database=firebaseAdmin.database()
//create instance of express app
var app=express()
//we want to serve js and html in ejs
//ejs stands for embedded javascript
app.set('view engine','ejs')
//we also want to send css images and other static files in views folder
//app.use(express.static('views'))
app.use(express.static(path.join(__dirname, '/views/')));
app.set('views',__dirname+'/views/')
//Give the server access to user input
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended:false}))
app.use(logger('dev'))
//create authentication middle ware
function checkLoggedIn(request, resposense, next) {// if user is authenticated in the session, carry on
if (request.isAuthenticated())
return next();// if they aren't redirect them to the index page
resposense.redirect('/');
}
app.get('/',function(request,response){
response.render('login.ejs')
})
app.get('/login', function(request,response){
response.render('profile.ejs')
});
app.get('/logout', function(request,response){
response.render('login.ejs')
});
app.listen(port,function(){
console.log('App running on port'+port)
})
注意:确保首先使用 npm install package-name 安装必要的包 比如
完成上述步骤后,您可以使用 node app.js 运行 app.js,一切顺利。 我希望这对使用 node js 和 express 的 firebase 身份验证有同样问题的人有所帮助
【讨论】: