LoginDemo/server.js

168 lines
5.5 KiB
JavaScript

var express = require('express');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var db = require('./db');
// Google
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
//Digest
var DigestStrategy = require('passport-http').DigestStrategy
passport.use(new DigestStrategy({ qop: 'auth' },
function(username, done) {
db.users.findByUsername(username, function (err, user) {
console.log("User")
console.log(user)
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user, user.password);
});
}
));
// Configure the local strategy for use by Passport.
//
// The local strategy requires a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user. The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.
passport.use(new Strategy(
function(username, password, cb) {
db.users.findByUsername(username, function(err, user) {
if (err) { return cb(err); }
if (!user) { return cb(null, false); }
if (user.password != password) { return cb(null, false); }
return cb(null, user);
});
}));
// Use the GoogleStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a token, tokenSecret, and Google profile), and
// invoke a callback with a user object.
passport.use(new GoogleStrategy({
clientSecret: 'YEMhoekMa89lFFGesgx7o23L',
clientID: '796153694464-k1qqko2fgqtqg3n5teiq2pape1cjkaud.apps.googleusercontent.com',
callbackURL: "http://localhost:4000/auth/google/callback"
},
function(token, tokenSecret, profile, done) {
console.log("pro")
console.log(profile)
db.users.findByUsernameGoogle({ googleId: profile.id }, function (err, user) {
console.log("user")
console.log(user)
if (err) { return done(err); }
if(user == null || user == {}){
var newUser = {username: profile.name.givenName, passwort: '', displayName: profile.displayName, emails: [{value: 'ONLY Google Login'}], googleId: '108136196294121041031'}
db.users.createUser(newUser, function (err, user){
return done(err, user)
})
}else {
return done(err, user);
}
});
}
));
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
passport.deserializeUser(function(id, cb) {
db.users.findById(id, function (err, user) {
if (err) { return cb(err); }
cb(null, user);
});
});
// Create a new Express application.
var app = express();
// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
// Define routes.
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.get('/login',
function(req, res){
res.render('login');
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/logout',
function(req, res){
req.logout();
res.redirect('/');
});
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
app.get('/digest',
passport.authenticate('digest', { session: false }),
function(req, res) {
res.send("<a href=\"/logout\"><button>Logout</button></a> Hallo: " + req.user.displayName);
});
// GET /auth/google
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Google authentication will involve redirecting
// the user to google.com. After authorization, Google will redirect the user
// back to this application at /auth/google/callback
app.get('/auth/google',
passport.authenticate('google', { scope: 'https://www.googleapis.com/auth/plus.login' }));
// GET /auth/google/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
function(req, res) {
res.redirect('/');
});
app.listen(4000);