Code Monkey home page Code Monkey logo

authentication-secrets's Introduction

Authentication-Secrets

To inspect the code for the module, you can clone this repository and use git checkout to see the completed code for each lesson. If you don't remember how to do this, be sure to revisit the Git and GitHub module in the course.

authentication-secrets's People

Contributors

angelabauer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

authentication-secrets's Issues

Unauthorized access with "โ†" button

Some of our fellow students have found that even after logging out from the app - the cookies continue to remain saved inside the browser, making the secrets page accessible with the โ† / Back / Previous Page button of the browser.

What we need is to control the Cache and prevent them from getting stored inside the user's browser. I have a suggestion to modify the handler function of GET requests made on the /secrets route to fix this issue:

app.get('/secrets', (req, res) => {
  res.set('Cache-Control', 'no-store');
  if(req.isAuthenticated()) {
    res.render('secrets');
  } else {
    res.redirect('/login');
  }
})

Know more about cache control.

MongooseError: Model.prototype.save() no longer accepts a callback in lesson 378 resolved

if anyone face the above situation use promise instead of a callback function
for example :
// User.findOne({ email: username }, function (err, foundUser) {
// if (err) {
// console.log(err);
// } else {
// if (foundUser.password === password) {
// res.render("secrets");
// }
// }
// });
the above code can be rewritten using promises below
User.findOne({ email: username })
.then((foundUser) => {
if (foundUser.password === password) {
res.render("secrets");
}
})

does not get secret file after registering with google instead of secret file i get js object (my id and google id).

app.get("/auth/google",
passport.authenticate("google", { scope: ["profile"] }),
function(req, res) {
// Successfull authentication, redirect to secrets.
res.redirect("/auth/google/secrets");
}
);

app.get("/auth/google/secrets",
passport.authenticate('google', { failureRedirect: "/login" }),
function(req, res) {
// Successful authentication, redirect to secrets.
res.redirect("/secrets");
});

app.post("/register", (req, res) => {
User.register({ username: req.body.username}, req.body.password, (err, user) => {
if(err){
// console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, (err) => {
if(!err) res.redirect("/secrets");
else console.log(err);
});
}
});
});

app.get("/secrets", (req, res) => {
if(req.isAuthenticated()){
res.render("secrets");
} else {
res.redirect("/login");
}
});

any problem here ?

APPLICATION ERROR WHILE DEPLOYING ON HEROKU

It give this when i run this command heroku logs --tail

heroku link: https://murmuring-harbor-89689.herokuapp.com/

$ heroku logs --tail
2022-08-21T19:06:06.906140+00:00 heroku[router]: at=info method=GET path="/" host=murmuring-harbor-89689.herokuapp.com request_id=68785752-e055-43c9-a27c-c79141036ad9 fwd="106.215.91.46" dyno=web.1 connect=0ms
service=10014ms status=500 bytes=404 protocol=https
2022-08-21T19:09:54.000000+00:00 app[api]: Build started by user [email protected]
2022-08-21T19:10:12.836716+00:00 app[api]: Deploy f54b5a3a by user [email protected]
2022-08-21T19:10:12.836716+00:00 app[api]: Release v8 created by user
[email protected]
2022-08-21T19:10:13.000000+00:00 app[api]: Build succeeded
2022-08-21T19:10:13.541563+00:00 heroku[web.1]: Restarting
2022-08-21T19:10:13.557563+00:00 heroku[web.1]: State changed from up
to starting
2022-08-21T19:10:14.247280+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2022-08-21T19:10:14.471883+00:00 heroku[web.1]: Process exited with status 143
2022-08-21T19:10:15.642067+00:00 heroku[web.1]: Starting process with
command npm start
2022-08-21T19:10:17.430610+00:00 app[web.1]:
2022-08-21T19:10:17.430624+00:00 app[web.1]: > [email protected] start
2022-08-21T19:10:17.430624+00:00 app[web.1]: > node app.js
2022-08-21T19:10:17.430625+00:00 app[web.1]:
2022-08-21T19:10:17.850003+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2022-08-21T19:10:17.850018+00:00 app[web.1]: designed for a production environment, as it will leak
2022-08-21T19:10:17.850019+00:00 app[web.1]: memory, and will not scale past a single process.
2022-08-21T19:10:17.869597+00:00 app[web.1]: Server has started on port: 40787
2022-08-21T19:10:17.956857+00:00 heroku[web.1]: State changed from starting to up
2022-08-21T19:10:19.618539+00:00 app[web.1]: /app/node_modules/mongodb/lib/db.js:331
2022-08-21T19:10:19.618553+00:00 app[web.1]: throw new error_1.MongoAPIError(database names cannot contain the character '${invalidChars[i]}');
2022-08-21T19:10:19.618554+00:00 app[web.1]: ^
2022-08-21T19:10:19.618554+00:00 app[web.1]:
2022-08-21T19:10:19.618555+00:00 app[web.1]: MongoAPIError: database names cannot contain the character '/'
2022-08-21T19:10:19.618556+00:00 app[web.1]: at validateDatabaseName (/app/node_modules/mongodb/lib/db.js:331:19)
2022-08-21T19:10:19.618556+00:00 app[web.1]: at new Db (/app/node_modules/mongodb/lib/db.js:87:9)
2022-08-21T19:10:19.618557+00:00 app[web.1]: at MongoClient.db (/app/node_modules/mongodb/lib/mongo_client.js:210:20)
2022-08-21T19:10:19.618557+00:00 app[web.1]: at _setClient (/app/node_modules/mongoose/lib/connection.js:859:58)
2022-08-21T19:10:19.618557+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:814:7
2022-08-21T19:10:19.618557+00:00 app[web.1]: at /app/node_modules/mongodb/lib/utils.js:425:9
2022-08-21T19:10:19.618558+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:137:17
2022-08-21T19:10:19.618558+00:00 app[web.1]: at connectCallback (/app/node_modules/mongodb/lib/operations/connect.js:29:9)
2022-08-21T19:10:19.618558+00:00 app[web.1]: at /app/node_modules/mongodb/lib/operations/connect.js:81:9
2022-08-21T19:10:19.618559+00:00 app[web.1]: at /app/node_modules/mongodb/lib/sdam/topology.js:203:73 {
2022-08-21T19:10:19.618559+00:00 app[web.1]: [Symbol(errorLabels)]: Set(0) {}
2022-08-21T19:10:19.618559+00:00 app[web.1]: }
2022-08-21T19:10:19.745148+00:00 heroku[web.1]: Process exited with status 1
2022-08-21T19:10:19.986802+00:00 heroku[web.1]: State changed from up
to crashed
2022-08-21T19:10:19.989996+00:00 heroku[web.1]: State changed from crashed to starting
2022-08-21T19:10:22.170074+00:00 heroku[web.1]: Starting process with
command npm start
2022-08-21T19:10:24.018460+00:00 app[web.1]:
2022-08-21T19:10:24.018470+00:00 app[web.1]: > [email protected] start
2022-08-21T19:10:24.018470+00:00 app[web.1]: > node app.js
2022-08-21T19:10:24.018471+00:00 app[web.1]:
2022-08-21T19:10:24.517338+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2022-08-21T19:10:24.517357+00:00 app[web.1]: designed for a production environment, as it will leak
2022-08-21T19:10:24.517358+00:00 app[web.1]: memory, and will not scale past a single process.
2022-08-21T19:10:24.541406+00:00 app[web.1]: Server has started on port: 51174
2022-08-21T19:10:24.597181+00:00 heroku[web.1]: State changed from starting to up
2022-08-21T19:10:26.279172+00:00 app[web.1]: /app/node_modules/mongodb/lib/db.js:331
2022-08-21T19:10:26.279179+00:00 app[web.1]: throw new error_1.MongoAPIError(database names cannot contain the character '${invalidChars[i]}');
2022-08-21T19:10:26.279180+00:00 app[web.1]: ^
2022-08-21T19:10:26.279180+00:00 app[web.1]:
2022-08-21T19:10:26.279181+00:00 app[web.1]: MongoAPIError: database names cannot contain the character '/'
2022-08-21T19:10:26.279182+00:00 app[web.1]: at validateDatabaseName (/app/node_modules/mongodb/lib/db.js:331:19)
2022-08-21T19:10:26.279182+00:00 app[web.1]: at new Db (/app/node_modules/mongodb/lib/db.js:87:9)
2022-08-21T19:10:26.279182+00:00 app[web.1]: at MongoClient.db (/app/node_modules/mongodb/lib/mongo_client.js:210:20)
2022-08-21T19:10:26.279183+00:00 app[web.1]: at _setClient (/app/node_modules/mongoose/lib/connection.js:859:58)
2022-08-21T19:10:26.279183+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:814:7
2022-08-21T19:10:26.279183+00:00 app[web.1]: at /app/node_modules/mongodb/lib/utils.js:425:9
2022-08-21T19:10:26.279184+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:137:17
2022-08-21T19:10:26.279184+00:00 app[web.1]: at connectCallback (/app/node_modules/mongodb/lib/operations/connect.js:29:9)
2022-08-21T19:10:26.279185+00:00 app[web.1]: at /app/node_modules/mongodb/lib/operations/connect.js:81:9
2022-08-21T19:10:26.279185+00:00 app[web.1]: at /app/node_modules/mongodb/lib/sdam/topology.js:203:73 {
2022-08-21T19:10:26.279185+00:00 app[web.1]: [Symbol(errorLabels)]: Set(0) {}
2022-08-21T19:10:26.279186+00:00 app[web.1]: }
2022-08-21T19:10:26.402581+00:00 heroku[web.1]: Process exited with status 1
2022-08-21T19:10:26.467952+00:00 heroku[web.1]: State changed from up
to crashed
2022-08-21T19:10:31.665423+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-harbor-89689.herokuapp.com request_id=b062a4bf-63b1-45aa-996c-245cf20ff23c fwd="106.215.91.46" dyno= connect= service= status=503 bytes= protocol=https
2022-08-21T19:11:54.606959+00:00 heroku[web.1]: State changed from crashed to starting
2022-08-21T19:11:56.794254+00:00 heroku[web.1]: Starting process with
command npm start
2022-08-21T19:11:58.568969+00:00 app[web.1]:
2022-08-21T19:11:58.568982+00:00 app[web.1]: > [email protected] start
2022-08-21T19:11:58.568983+00:00 app[web.1]: > node app.js
2022-08-21T19:11:58.568983+00:00 app[web.1]:
2022-08-21T19:11:59.064076+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2022-08-21T19:11:59.064082+00:00 app[web.1]: designed for a production environment, as it will leak
2022-08-21T19:11:59.064083+00:00 app[web.1]: memory, and will not scale past a single process.
2022-08-21T19:11:59.091496+00:00 app[web.1]: Server has started on port: 4334
2022-08-21T19:11:59.135507+00:00 heroku[web.1]: State changed from starting to up
2022-08-21T19:12:00.853108+00:00 app[web.1]: /app/node_modules/mongodb/lib/db.js:331
2022-08-21T19:12:00.853119+00:00 app[web.1]: throw new error_1.MongoAPIError(database names cannot contain the character '${invalidChars[i]}');
2022-08-21T19:12:00.853120+00:00 app[web.1]: ^
2022-08-21T19:12:00.853120+00:00 app[web.1]:
2022-08-21T19:12:00.853121+00:00 app[web.1]: MongoAPIError: database names cannot contain the character '/'
2022-08-21T19:12:00.853121+00:00 app[web.1]: at validateDatabaseName (/app/node_modules/mongodb/lib/db.js:331:19)
2022-08-21T19:12:00.853121+00:00 app[web.1]: at new Db (/app/node_modules/mongodb/lib/db.js:87:9)
2022-08-21T19:12:00.853122+00:00 app[web.1]: at MongoClient.db (/app/node_modules/mongodb/lib/mongo_client.js:210:20)
2022-08-21T19:12:00.853122+00:00 app[web.1]: at _setClient (/app/node_modules/mongoose/lib/connection.js:859:58)
2022-08-21T19:12:00.853123+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:814:7
2022-08-21T19:12:00.853123+00:00 app[web.1]: at /app/node_modules/mongodb/lib/utils.js:425:9
2022-08-21T19:12:00.853123+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:137:17
2022-08-21T19:12:00.853124+00:00 app[web.1]: at connectCallback (/app/node_modules/mongodb/lib/operations/connect.js:29:9)
2022-08-21T19:12:00.853124+00:00 app[web.1]: at /app/node_modules/mongodb/lib/operations/connect.js:81:9
2022-08-21T19:12:00.853125+00:00 app[web.1]: at /app/node_modules/mongodb/lib/sdam/topology.js:203:73 {
2022-08-21T19:12:00.853125+00:00 app[web.1]: [Symbol(errorLabels)]: Set(0) {}
2022-08-21T19:12:00.853126+00:00 app[web.1]: }
2022-08-21T19:12:01.000005+00:00 heroku[web.1]: Process exited with status 1
2022-08-21T19:12:01.091455+00:00 heroku[web.1]: State changed from up to crashed
2022-08-21T19:12:04.276976+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-harbor-89689.herokuapp.com request_id=c9e8baf3-610f-4252-b8f8-ef768b92ee18 fwd="106.215.91.46" dyno= connect= service= status=503 bytes= protocol=https
2022-08-21T19:11:36.000000+00:00 app[api]: Build started by user fk******@gmail.com
I did everything

updated URI(s) // Authorized JavaScript origins & Authorized redirect URIs

updated links in app.js

added Procfile

mongoDB atlas connected

package.json looks like this

{
  "name": "secrets",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "engines": {
    "node": "16.15.1"
  },
  "dependencies": {
    "bcrypt": "^5.0.1",
    "dotenv": "^16.0.1",
    "ejs": "^3.1.8",
    "express": "^4.18.1",
    "express-session": "^1.17.3",
    "md5": "^2.3.0",
    "mongoose": "^6.5.2",
    "mongoose-encryption": "^2.1.2",
    "mongoose-findorcreate": "^3.0.0",
    "passport": "^0.6.0",
    "passport-google-oauth20": "^2.0.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^7.1.2"
  }
}

tried deleting everything and restarting everything. But NOTHING WORKED.

It still gives "application error"

What am I missing here?

throw new MongooseError('Model.prototype.save() no longer accepts a callback'); ....... Fixing use then and catch instead of use if and else method

use new code of register post

app.post("/register", function(req, res) {
const newUser = new User({
email: req.body.username,
password: req.body.password
});

newUser.save().then(function(){
res.render("secrets");
}).catch(function (err){
console.log(err);
});
});


instead of old code of register post

app.post("/register", function(req, res){
const newUser = new User({
email: req.body.username,
password: req.body.password
});
newUser.save(function(err){
if (err) {
console.log(err);
} else {
res.render("secrets");
}
});
});

Two res in authentication

Throughout the module, She said to use a different name for a response so that the name does not clash, However, while logging user in, the response is 'res' and inside that when the passport is used for authentication, she again used 'res'. But it does what we want. I didn't understand this part. chapter 386 17:35.

MongoError: E11000 duplicate key error collection: userDB.users index: username_1 dup key: { username: null }

I added a facebook login button and it works perfectly fine. Problem is that, in the mongoDB facebook/google accounts generates DB without username. So if you register with google account and next you try to register with a different google/facebook account they both have a username:NULL which generates an error.
"MongoError: E11000 duplicate key error collection: userDB.users index: username_1 dup key: { username: null }"
how can i fix this???!

How to set login from single device at a time

How can I set session so that I can login from one device at a time. Suppose I login from laptop and then if I login from another device say my mobile then it automatically gets logged out of my laptop.

Secret undefined error.

I followed the code, I am able to implement sign up with FB but my secret variable does not store any secrets, it shows undefined in the console.

TypeError: User.createStrategy is not a function

Was just following and encountered this error. Tried searching google for solutions and can't find anything.

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));

app.use(session({
    secret: "mysecret.",
    resave: false,
    saveUninitialized: false, 
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/userDB");

const userSchema = new mongoose.Schema({
    email: String,
    password: String
});

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

userSchema.plugin(passportLocalMongoose); ```



this is my code and can't find anything wrong with it

It doesnt appear the secrets!

I have all the code like the posted one, and it doesnt appear the secrets!

app.get("/secrets", function(req, res){
User.find({"secret": {$ne: null}}, function(err, foundUsers){
if (err){
console.log(err);
} else {
if (foundUsers) {
res.render("secrets", {usersWithSecrets: foundUsers});
}
}
});
});

in the db i have the secret, but i cant show them!

[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

When i run nodemon app.js it crashes and is giving the following error:
[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

req.isAuthenticated() always gives false and redirects to login() route.

require("dotenv").config();

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
//const bcrypt = require("bcrypt");

//const md5 = require("md5");
//const encrypt = require("mongoose-encryption");

const app = express();

app.use(express.static("public"));

app.set("view engine","ejs");

app.use(bodyParser.urlencoded({extended: true}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/userDB",{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, });

//mongoose.set("useCrateIndex", true);

const userSchema =new mongoose. Schema({
email: String ,
password: String
});

userSchema.plugin(passportLocalMongoose);

// for encryption
//userSchema.plugin(encrypt,{secret: process.env.SECRET , encryptedFields: ["password"]});
//const saltRounds =10;

const User = new mongoose.model("User",userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get("/",function(req,res){
res.render("home");

});

app.get("/login",function(req,res){
res.render("login");
});

app.get("/register",function(req,res){
res.render("register");
});

app.get("/secrets", function(req, res) {
if(req.isAuthenticated()){
res.render("secrets");
}
else
{res.redirect("/login");}
});

app.post("/register",function(req,res){

User.register({username: req.body.username},req.body.password,function(err,user){
if(err){
console.log(err);
res.redirect("/register");

}
else
{
	passport.authenticate("local")(req,res,function(err){
		if(!err)
			console.log("hey");
		res.redirect("/secrets");
	});
}

});

});

app.post("/login", function(req, res) {

});

app.listen(3000,function(){
console.log("Server started at port 3000");
});

OAuth2Strategy requires a clientID option

C:\Users\lenovo\Downloads\Authentication-Secrets-master\node_modules\passport-oauth2\lib\strategy.js:82 if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
^
TypeError: OAuth2Strategy requires a clientID option
at Strategy.OAuth2Strategy (C:\Users\lenovo\Downloads\Authentication-Secrets-master\node_modules\passport-oauth2\lib\strategy.js:82:34)
at new Strategy (C:\Users\lenovo\Downloads\Authentication-Secrets-master\node_modules\passport-google-oauth20\lib\strategy.js:52:18)
at Object. (C:\Users\lenovo\Downloads\Authentication-Secrets-master\app.js:57:14)

Unauthorized Login with wrong password

As reported by some of our fellow students. The issue is something like this:

  1. Go to localhost:3000/secrets
    --this should reroute you to the login page because you are not authenticated yet.

  2. Login with the CORRECT email BUT USE AN INCORRECT PASSWORD.
    --You won't be redirected to the /secrets route.

  3. Now manually go into localhost:3000/secrets
    --you should have access to the secrets page now despite having entered the wrong password.

I have the following suggestion to fix this issue by modifying the handler function of POST requests made on the /login route::

 // Handle 'POST' requests made on the '/login' route:
app.post('/login', passport.authenticate('local', {
  successRedirect: '/secrets',
  failureRedirect: '/login',
}));

As the official documentation page of passportJS says - "calling passport.authenticate() middleware invokes req.login() automatically", hence no need to call it separately before authenticating, leaving a glitch for unauthorized access.

Google Auth popup not working (Solution)

  1. Change app.get('/auth/google") :

app.get("/auth/google",
passport.authenticate('google',{ scope: ["profile"] }),
function(req, res) {
// Successful authentication, redirect to secrets.
res.redirect("/auth/google/secrets");
});

  1. Use :
    passport.serializeUser((user, done) => done(null, user));
    passport.deserializeUser((user, done) => done(null, user));

Instead of:
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

  1. Also, remove:
    userProfileURL :"https://www.googleapis.com/oauth2/v3/userinfo" from GoogleStrategy. It is no longer needed.
    Google Auth popup must work now.

TypeError: OAuth2Strategy requires a clientID option

Hey there,

I tried to lift this project up on heroku, but it did not work.
The app will crash, claiming the error 'TypeError: OAuth2Strategy requires a clientID option'.
I have no idea what to do, since I followed every step, adjusted the ports and URLs.
Do you have an idea?

Of course, I adjusted the .env file to my Google Credentials and I added the respective heroku URIs to the https://console.developers.google.com/apis/credentials/oauthclient/...

URI: https://HEROKU-NAME-XXXXX.herokuapp.com
Redirect URI: https://HEROKU-NAME-XXXXX.herokuapp.com/auth/google/secrets

Here is the code so far:

//jshint esversion:6
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require('mongoose-findorcreate');

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));

app.use(session({
secret: "Our little secret.",
resave: false,
saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb+srv://CHANGEDTHIS:[email protected]/secretsDB", {useNewUrlParser: true}); //mongoDB Datenbank
mongoose.set("useCreateIndex", true);

const userSchema = new mongoose.Schema ({
email: String,
password: String,
googleId: String,
secret: String
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});

passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "https://HEROKU-NAME-XXXXX.herokuapp.com/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);

User.findOrCreate({ googleId: profile.id }, function (err, user) {
  return cb(err, user);
});

}
));

app.get("/", function(req, res){
res.render("home");
});

app.get("/auth/google",
passport.authenticate('google', { scope: ["profile"] })
);

app.get("/auth/google/secrets",
passport.authenticate('google', { failureRedirect: "/login" }),
function(req, res) {
// Successful authentication, redirect to secrets.
res.redirect("/secrets");
});

app.get("/login", function(req, res){
res.render("login");
});

app.get("/register", function(req, res){
res.render("register");
});

app.get("/secrets", function(req, res){
User.find({"secret": {$ne: null}}, function(err, foundUsers){
if (err){
console.log(err);
} else {
if (foundUsers) {
res.render("secrets", {usersWithSecrets: foundUsers});
}
}
});
});

app.get("/submit", function(req, res){
if (req.isAuthenticated()){
res.render("submit");
} else {
res.redirect("/login");
}
});

app.post("/submit", function(req, res){
const submittedSecret = req.body.secret;

//Once the user is authenticated and their session gets saved, their user details are saved to req.user.
// console.log(req.user.id);

User.findById(req.user.id, function(err, foundUser){
if (err) {
console.log(err);
} else {
if (foundUser) {
foundUser.secret = submittedSecret;
foundUser.save(function(){
res.redirect("/secrets");
});
}
}
});
});

app.get("/logout", function(req, res){
req.logout();
res.redirect("/");
});

app.post("/register", function(req, res){

User.register({username: req.body.username}, req.body.password, function(err, user){
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
});
}
});

});

app.post("/login", function(req, res){

const user = new User({
username: req.body.username,
password: req.body.password
});

req.login(user, function(err){
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
});
}
});

});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function() {
console.log("Server has started successfully.");
});

MongooseError: Model.findOne() no longer accepts a callback ... fixed using then and catch instead of use if and else method

use new code of login post

 app.post("/login",function(req, res){
 const username = req.body.username;
 const password = req.body.password;

 User.findOne({email:username})
 .then(function(foundUser) {
     if(foundUser){
         if(foundUser.password === password){
             res.render("secrets");
         }
     }
})
.catch(function(err) {
 console.log(err);
});

});


instead of old code of login post

app.post("/login", function(req, res){
const username = req.body.username;
const password = req.body.password;
User.findOne({email: username}, function(err, foundUser){
if (err) {
console.log(err);
} else {
if (foundUser){
if (foundUser.password === password){
res.render("secrets");
}
}
}
});
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.