Guest User

Untitled

a guest
Aug 12th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.56 KB | None | 0 0
  1. (function() {
  2. // Initialize Firebase
  3. var config = {
  4. //...
  5. };
  6.  
  7. firebase.initializeApp(config);
  8.  
  9. // no local persistence because of the httpOnly flag
  10. firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
  11.  
  12. const emailField = document.getElementById("email");
  13. const passwordField = document.getElementById("password");
  14. const loginButton = document.getElementById("loginButton");
  15.  
  16. loginButton.addEventListener("click", e => {
  17. const email = emailField.value;
  18. const password = passwordField.value;
  19.  
  20. const signInPromise = firebase.auth().signInWithEmailAndPassword(email, password);
  21. signInPromise.catch(e => {
  22. console.log("Login Error: " + e.message);
  23. })
  24. return signInPromise.then(() => {
  25. console.log("Signed in + " + firebase.auth().currentUser.uid);
  26. return firebase.auth().currentUser.getIdToken().then(idToken => {
  27. // Session login endpoint is queried and the session cookie is set.
  28. // CSRF protection should be taken into account.
  29. // ...
  30. // const csrfToken = getCookie('csrfToken')
  31. console.log("User ID Token: " + idToken);
  32. return sendToken(idToken);
  33. //return postIdTokenToSessionLogin('/sessionLogin', idToken, csrfToken);
  34. });
  35. })
  36. });
  37.  
  38. firebase.auth().onAuthStateChanged(user => {
  39. if (user) {
  40. document.getElementById('loginSuccess').innerHTML = `Signed in as ${user.uid}`;
  41. document.getElementById('loginError').innerHTML = "";
  42. } else {
  43. document.getElementById('loginSuccess').innerHTML = "";
  44. document.getElementById('loginError').innerHTML = `Not signed in`;
  45. }
  46. });
  47. })();
  48.  
  49. function sendToken(idToken) {
  50. console.log("Posting " + idToken);
  51. var xhr = new XMLHttpRequest();
  52. var params = `token=${idToken}`;
  53. xhr.open('POST', "/admin/login", true);
  54. xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  55. return new Promise(function(resolve, reject) {
  56. xhr.onreadystatechange = function() {//Call a function when the state changes.
  57. if (xhr.readyState == 4 && xhr.status == 200) {
  58. resolve();
  59. } else if (xhr.readyState == 4 && xhr.status != 200) {
  60. reject("Invalid http return status");
  61. }
  62. }
  63. return xhr.send(params);
  64. });
  65. }
  66.  
  67. adminApp.post("/login", (request, response) => {
  68. console.log("Got login post request");
  69. if (request.body.token) {
  70. const idToken = request.body.token.toString();
  71. console.log("idToken = " + idToken);
  72. // Set session expiration to 5 days.
  73. const expiresIn = 60 * 60 * 24 * 5 * 1000;
  74. return adminFirebase.auth().createSessionCookie(idToken, {expiresIn}).then((sessionCookie) => {
  75. const options = {maxAge: expiresIn, httpOnly: true, secure: true};
  76. response.cookie('session', sessionCookie, options);
  77. response.end(JSON.stringify({status: 'success'}));
  78. }, error => {
  79. response.status(401).send('UNAUTHORIZED REQUEST!');
  80. });
  81. }
  82. return response.status(400).send("MISSING TOKEN");
  83. });
  84.  
  85. const validateLogin = function (req, res, next) {
  86. const sessionCookie = req.cookies.session || '';
  87. console.log(JSON.stringify(req.headers));
  88. console.log("Verifying " + sessionCookie);
  89. return adminFirebase.auth().verifySessionCookie(sessionCookie, true).then((decodedClaims) => {
  90. console.log("decoded claims: " + decodedClaims);
  91. next();
  92. }).catch(error => {
  93. res.redirect('/admin/login');
  94. });
  95. };
  96.  
  97. adminApp.get("/secret/", validateLogin, (request, response) => {
  98. return response.send("This is secret!");
  99. });
Add Comment
Please, Sign In to add comment