View reselect.js
var createStructuredSelector = require('reselect').createStructuredSelector;
var createSelector = require('reselect').createSelector;
// Example of structured selector
const mySelectorA = (state) => state.first_user;
const mySelectorB = (state) => state.second_user;
const mySelectorC = (state) => state.second_user + state.first_user;
const structuredSelector = createStructuredSelector({
View passport_strategy_and_route.js
// Login strategy. Enable passing through of the req object by setting passReqToCallback to true.
passport.use(new Strategy({ passReqToCallback: true },
function (req,username, password, done) {
let user = your_user_auth(username,password); // returns the user object if valid, otherwise null
if(user)
// Extract the redirect hash from the request body and store it in the request session object
req.session.redirect_url = req.body.url;
return done(null, user);
}
return done(null, false);
View login_template.jade
div.login-page
form(class='form-login', action='/web-login', method='POST')
input(type='text', name='username', placeholder='Username',required, autofocus)
input(type='password', name='password', placeholder='Password', required)
input(type='hidden', id='url', name='url')
button(class='btn', type='submit') Sign in
script(type='text/javascript').
document.getElementById("url").value = window.location.hash;
View express_is_authenticated.js
// User requests the /app/ route -> Check if he is authenticated
router.get('/app/', isAuthenticated, (req, res) => res.render('app') );
// The isAuthenticated function is using passport.js here to see if the user is logged in (req.isAuthenticated)
// It that's not the case, we redirect them to the login route.
const isAuthenticated = (req, res, next) => {
if(req.isAuthenticated()) return next();
res.redirect('/login');
}
View promises_with_co.js
co(function *() {
// yield any promise
var a = yield getURLPromise('http://www.google.com')
var b = yield getURLPromise('http://www.apple.com')
var c = yield getURLPromise('http://www.microsoft.com')
debug([a, b, c]);
}).catch((error) =>{
debug("Something went wrong: ", error)
});
View co_example.js
co(function* () {
var result = yield Promise.resolve(true);
return result;
}).then(function (value) {
console.log(value);
}, function (err) {
console.error(err.stack);
});
View promises_and_generators.js
// This function will return a promise that will fetch data from a certain URL
function getURLPromise(url) {
return new Promise((resolve, reject) => {
http.get(url, (rs) => {
var data = ''
rs.on('data', (chunk) => data += chunk);
rs.on('end', ()=> resolve(data.length));
});
});