exports.loginRequired = function(req, res, next) { if (req.loggedIn) { return next(); } res.redirect(everyauth.password.getLoginPath() + "?next=" + encodeURIComponent(req.url)); };
schema.static('createWithGoogleOAuth', function (googleUser, accessToken, accessTokenExtra, callback) { var expiresDate = new Date; expiresDate.setSeconds(expiresDate.getSeconds() + accessTokenExtra.expires_in); var params = { google: { email: googleUser.email , name: googleUser.name , given_name: googleUser.given_name , family_name: googleUser.family_name , picture: googleUser.picture , gender: googleUser.gender , locale: googleUser.locale , expires: expiresDate , accessToken: accessToken , refreshToken: accessTokenExtra.refresh_token } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "google:" + googleUser.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
everyauth.password.authenticate( function (login, password) { var errors = []; if (!login) errors.push('Votre email est requis'); if (!password) errors.push('Un mot de passe est requis'); if (errors.length) return errors; var promise = this.Promise(); userProvider.findByField(everyauth.password.loginFormFieldName(), login, function(err, user){ console.log('authenticate: err: '+util.inspect(err)+' - user:'******'mot de passe erroné'); promise.fulfill(['Mot De Passe Erroné']); } else { console.log('utilisateur authentifié'); user['id']=user['_id']; promise.fulfill(user); } } else { promise.fulfill(['Cet identifiant n\'est pas référencé']); } } }); return promise; });
schema.static('createWithFoursquare', function (foursquareUserMeta, accessToken, accessTokenExtra, callback) { var params = { foursquare: { accessToken: accessToken , id: foursquareUserMeta.id , firstName: foursquareUserMeta.firstName , lastName: foursquareUserMeta.lastName , homeCity: foursquareUserMeta.homeCity , photo: foursquareUserMeta.photo , gender: foursquareUserMeta.gender , relationship: foursquareUserMeta.relationship , type: foursquareUserMeta.type , contact: foursquareUserMeta.contact , pings: foursquareUserMeta.pings , badges: foursquareUserMeta.badges , checkins: foursquareUserMeta.checkins , mayorships: foursquareUserMeta.mayorships , tips: foursquareUserMeta.tips , todos: foursquareUserMeta.todos , photos: foursquareUserMeta.photos , friends: foursquareUserMeta.friends , followers: foursquareUserMeta.followers , requests: foursquareUserMeta.requests , pageInfo: foursquareUserMeta.pageInfo } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "foursquare:" + foursquareUserMeta.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
schema.static('createWithWeiboOAuth', function (weiboUser, accessToken, accessTokenExtra, callback) { var expiresDate = new Date; expiresDate.setSeconds(expiresDate.getSeconds() + accessTokenExtra.expires_in); var params = { weibo: { accessToken: accessToken , expires: expiresDate , refreshToken: "" , id: weiboUser.id , screen_name: weiboUser.screen_name , avatar_large: weiboUser.avatar_large , profile_image_url: weiboUser.profile_image_url , gender: weiboUser.gender , location: weiboUser.location , province: weiboUser.province , city: weiboUser.city , lang: weiboUser.lang , verified: weiboUser.verified , verified_reason: weiboUser.verified_reason , verified_type: weiboUser.verified_type , url: weiboUser.url , weihao: weiboUser.weihao } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "weibo:" + weiboUser.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
schema.static('createWithFB', function (fbUserMeta, accessToken, expires, callback) { var expiresDate = new Date(); expiresDate.setSeconds(expiresDate.getSeconds() + expires); var params = { fb: { id: fbUserMeta.id , accessToken: accessToken , expires: expiresDate , name: { full: fbUserMeta.name , first: fbUserMeta.first_name , last: fbUserMeta.last_name } , alias: fbUserMeta.link.match(/^https?:\/\/www.facebook\.com\/(.+)/)[1] , gender: fbUserMeta.gender , email: fbUserMeta.email , timezone: fbUserMeta.timezone , locale: fbUserMeta.locale , verified: fbUserMeta.verified , updatedTime: fbUserMeta.updated_time } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "fb:" + fbUserMeta.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
userProvider.findByField(everyauth.password.loginFormFieldName(), login, function(err, user){ console.log('authenticate: err: '+util.inspect(err)+' - user:'******'mot de passe erroné'); promise.fulfill(['Mot De Passe Erroné']); } else { console.log('utilisateur authentifié'); user['id']=user['_id']; promise.fulfill(user); } } else { promise.fulfill(['Cet identifiant n\'est pas référencé']); } } });
return function (req, res, next) { var sess = req.session , auth = sess.auth , ea = { loggedIn: !!(auth && auth.loggedIn) }; // Copy the session.auth properties over for (var k in auth) { ea[k] = auth[k]; } if (everyauth.enabled.password) { // Add in access to loginFormFieldName() + passwordFormFieldName() ea.password || (ea.password = {}); ea.password.loginFormFieldName = everyauth.password.loginFormFieldName(); ea.password.passwordFormFieldName = everyauth.password.passwordFormFieldName(); } res.locals.everyauth = ea; next(); }
exports.authenticate = function (login, password, callback) { // TODO This will break if we change everyauth's // configurable loginName var query = {}; query[everyauth.password.loginKey()] = login; this.findOne(query, function (err, user) { if (err) return callback(err); if (!user) return callback('User with login ' + login + ' does not exist'); user.authenticate(password, function (err, didSucceed) { if (err) return callback(err); if (didSucceed) return callback(null, user); return callback(null, null); }); }); };
schema.static('createWithWeiboOAuth', function (weiboUser, appId, appSecret, callback) { var expiresDate = new Date; expiresDate.setSeconds(expiresDate.getSeconds() + accessTokenExtra.expires_in); var params = { weibo: { email: weiboUser.id , appId: appId , appSecret: appSecret } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "weibo:" + weiboUser.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
schema.static('createWithTwitter', function (twitUserMeta, accessToken, accessTokenSecret, callback) { var params = { twit: { accessToken: accessToken , accessTokenSecret: accessTokenSecret , id: twitUserMeta.id , name: twitUserMeta.name , screenName: twitUserMeta.screen_name , location: twitUserMeta.location , description: twitUserMeta.description , profileImageUrl: twitUserMeta.profile_image_url , url: twitUserMeta.url , protected: twitUserMeta.protected , followersCount: twitUserMeta.followers_count , profileBackgroundColor: twitUserMeta.profile_background_color , profileTextColor: twitUserMeta.profile_text_color , profileLinkColor: twitUserMeta.profile_link_color , profileSidebarFillColor: twitUserMeta.profile_sidebar_fill_color , profileSiderbarBorderColor: twitUserMeta.profile_sidebar_border_color , friendsCount: twitUserMeta.friends_count , createdAt: twitUserMeta.created_at , favouritesCount: twitUserMeta.favourites_count , utcOffset: twitUserMeta.utc_offset , timeZone: twitUserMeta.time_zone , profileBackgroundImageUrl: twitUserMeta.profile_background_image_url , profileBackgroundTile: twitUserMeta.profile_background_tile , profileUseBackgroundImage: twitUserMeta.profile_use_background_image , geoEnabled: twitUserMeta.geo_enabled , verified: twitUserMeta.verified , statusesCount: twitUserMeta.statuses_count , lang: twitUserMeta.lang , contributorsEnabled: twitUserMeta.contributors_enabled } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "twit:" + twitUserMeta.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
schema.static('createWithGithub', function (ghUser, accessToken, callback) { var params = { github: { id: ghUser.id , accessToken: accessToken , type: ghUser.type , login: ghUser.login , gravatarId: ghUser.gravatar_id , name: ghUser.name , email: ghUser.email , publicRepoCount: ghUser.public_repo_count , publicGistCount: ghUser.public_gist_count , followingCount: ghUser.following_count , followersCount: ghUser.followers_count , company: ghUser.company , blog: ghUser.blog , location: ghUser.location , permission: ghUser.permission , createdAt: ghUser.created_at // Private data , totalPrivateRepoCount: ghUser.total_private_repo_count , collaborators: ghUser.collaborators , diskUsage: ghUser.disk_usage , ownedPrivateRepoCount: ghUser.owned_private_repo_count , privateGistCount: ghUser.private_gist_count , plan: { name: ghUser.plan.name , collaborators: ghUser.plan.collaborators , space: ghUser.plan.space , privateRepos: ghUser.plan.private_repos } } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "github:" + ghUser.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
everyauth.password.validateRegistration( function (newUserAttrs) { var errors = []; var promise = this.Promise(); console.log('new user attr:'+util.inspect(newUserAttrs)); var fieldName = everyauth.password.loginFormFieldName(); var fieldValue = newUserAttrs[fieldName]; userProvider.findByField(fieldName, fieldValue, function(err, user){ console.log('err: '+util.inspect(err)+' - user:'******'Cet Identifiant a déjà été utilisé']); } else { promise.fulfill([]); } } }); return promise; });
schema.static('createWithVK', function (vkUserMeta, accessToken, expires, callback) { var expiresDate = new Date; expiresDate.setSeconds(expiresDate.getSeconds() + expires); var params = { vk: { id: vkUserMeta.uid , accessToken: accessToken , expires: expiresDate , name: { first: vkUserMeta.first_name , last: vkUserMeta.last_name , nickname: vkUserMeta.nick_name , screen_name: vkUserMeta.screen_name } , sex: vkUserMeta.sex , bdate: parseDate(vkUserMeta.bdate) , city: vkUserMeta.city , country: vkUserMeta.country , timezone: vkUserMeta.timezone , photo: vkUserMeta.photo , photo_medium: vkUserMeta.photo_medium , photo_big: vkUserMeta.photo_big , has_mobile: vkUserMeta.has_mobile , rate: vkUserMeta.rate , university: vkUserMeta.university , university_name: vkUserMeta.university_name , faculty: vkUserMeta.faculty , faculty_name: vkUserMeta.faculty_name , graduation: vkUserMeta.graduation } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "vk:" + vkUserMeta.uid; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
schema.static('createWithInstagram', function (hipster, accessToken, callback) { var params = { instagram: { id: hipster.id , name: { first: hipster.first_name , last: hipster.last_name } , profilePicture: hipster.profile_picture , counts: { media: hipster.counts.media , follows: hipster.counts.follows , followedBy: hipster.counts.followed_by } } }; // TODO Only do this if password module is enabled // Currently, this is not a valid way to check for enabled if (everyauth.password) params[everyauth.password.loginKey()] = "instagram:" + hipster.id; // Hack because of way mongodb treate unique indexes this.create(params, callback); });
var everyauth = require("everyauth"); var User = require("./../models/User"); var log = require("./../lib/log")("log.txt"); everyauth.password .getLoginPath("/client/src/index.html#login") .postLoginPath("/login") .authenticate(function(login,password){ console.log("logging in " + login+ " " + password); var promise = this.Promise(); var query = User.where('username').equals(login);//.where('password').equals(password); query.exec(function(err, user){ if (err) return promise.fulfill([err]); if (user && user.length > 0 && user[0].comparePasswords(password)){ log("logged in "+ user[0].username); promise.fulfill(user[0]); } else promise.fulfill([{error:"login failed"}]); }); return promise; }) .respondToLoginSucceed( function (res, user, data) { var loggedIn =everyauth._req._getters.loggedIn(); if (user) { everyauth.user = user; //response.login = true; return res.json({ success: true,user:{ username:user.username, _id:user._id }}, 200); }
everyauth.google .appId(conf.google[process.env.NODE_ENV].appId) .appSecret(conf.google[process.env.NODE_ENV].appSecret) .scope('https://www.googleapis.com/auth/userinfo.profile') .handleAuthCallbackError(function (req, res) { res.redirect('/'); }) .findOrCreateUser(function (session, accessToken, accessTokenExtra, googleUserMetadata) { var promise = this.Promise(); findOrCreateRemoteUser('google', googleUserMetadata, promise); return promise; }) .redirectPath('/landing'); everyauth.password .getLoginPath('/#login') .postLoginPath('/login') .loginView('index.jade') .authenticate(function(login, password) { var promise = this.Promise(); crypto.hash(password, function(err, key) { if(err){console.log(err); return promise.fulfill([err]);} key = new Buffer(key, 'binary').toString('base64'); userController.get({username: login, password: key}, function(err, user) { if(err){console.log(err); return promise.fulfill([err]);} if(!user){return promise.fulfill(['Incorrect credentials for ' + login]);} return promise.fulfill(user); }); });
var everyauth = require('everyauth'); everyauth .password .loginWith('email') .getLoginPath('/login') .postLoginPath('/login') .loginView('login.jade') // .loginLocals({ // title: 'Login' // }) // .loginLocals(function (req, res) { // return { // title: 'Login' // } // }) .loginLocals( function (req, res, done) { setTimeout( function () { done(null, { title: 'Async login' }); }, 200); }) .authenticate( function (login, password) { var errors = []; if (!login) errors.push('Missing login'); if (!password) errors.push('Missing password'); if (errors.length) return errors; var user = usersByLogin[login]; if (!user) return ['Login failed']; if (user.password !== password) return ['Login failed']; return user;
var everyauth = require('everyauth'); var getData = require('./getData'); var bcrypt = require('bcrypt'); //everyauth.debug = true; everyauth.password .getLoginPath('/login') // Uri path to the login page .postLoginPath('/login') // Uri path that your login form POSTs to .loginView('login.jade') .loginFormFieldName('email') .loginHumanName('email') .loginKey('email') .authenticate( function (login, password) { var promise , errors = []; if (!login) errors.push('Missing login.'); if (!password) errors.push('Missing password.'); if (errors.length) return errors; promise = this.Promise(); //findUser passes an error or user to a callback after finding the //user by login getData.findUserByEmail( login, function (err, user) { if (err) { errors.push(err.message || err); return promise.fulfill(errors); } if (!user) { errors.push('User with login ' + login + ' does not exist.'); return promise.fulfill(errors);
everyauth.everymodule .findUserById( function (id, callback) { // callback(null, usersById[id]); db.User.find(id).success(function(user){ if(user!==null){ callback(null, user); } }); }); everyauth.everymodule.logoutPath('/logout'); everyauth.everymodule.logoutRedirectPath('/'); //Logowanie za pomoca maila everyauth.password .loginFormFieldName('login') .passwordFormFieldName('password') .getLoginPath('/login') .postLoginPath('/login') .loginView('user/login') .authenticate(function(login, password){ var prom = this.Promise(); db.User.find({where: {login: login, password: password}}).success(function(user){ if(user!==null){ prom.fulfill(user); }else{ prom.fulfill(['Logowanie nie udane']); } }); return prom; })
// , express.session({ secret: "deepp blue", svc_id: "nodejs_chat_svc", cookie:{maxAge:sessionMaxAge} }) // , everyauth.middleware() ); //Get the config params var httpPort = cfg.get("http:port"); var useSSL = cfg.get("http:useSSL"); var sessionMaxAge = cfg.get("session:maxAge"); var viewsPath = __dirname + '/views'; //Setup the modules everyauth.debug = true; everyauth .password // .loginWith('email') .loginWith('login') .getLoginPath('/login') .postLoginPath('/login') .loginView('login.jade') .loginLocals( function (req, res, done) { setTimeout( function () { done(null, { title: 'Async login' }); }, 200); }) .authenticate( function (login, password) { var errors = []; if (!login) errors.push('Missing login'); if (!password) errors.push('Missing password');
module.exports.configure = function(app){ everyauth.debug = false; everyauth.everymodule.moduleTimeout(-1); everyauth.google .appId('888576786409.apps.googleusercontent.com') .appSecret('IFCE9K7ho3ICCMIFK6rb05pJ') .redirectPath('/') .scope('https://www.google.com/m8/feeds') .findOrCreateUser(function(session,accessToken,accessTokenExtra,googleUserMetadata){ return googleID[googleUserMetadata.id] || (googleID[googleUserMetadata.id] = addUser('google',googleUserMetadata)); }) .handleAuthCallbackError(function(request,response){ console.log('auth.error:',request,response); }); everyauth.twitter .consumerKey('kiKNZ1y5Jw5dCYxHFoDVA') .consumerSecret('jJQEQguVqEj8YLnO6Ch5QiV74I6vYVCFva6rQUcUcs') .redirectPath('/') .findOrCreateUser(function(sess,accessToken,accessSecret,twitUser){ return twitterID[twitUser.id] || (twitterID[twitUser.id] = addUser('twitter',twitUser)); }) .handleAuthCallbackError(function(request,response){ console.log('auth.error:',request,response); }); everyauth.github .appId('c09cf8b4d7d112266e51') .appSecret('f86dbd4c5b6dfdaf9a4bdaa3e307a5e4968888b6') .redirectPath('/') .findOrCreateUser(function(sess,accessToken, accessTokenExtra,ghUser){ return githubID[ghUser.id] || (githubID[ghUser.id] = addUser('github',ghUser)); }) .handleAuthCallbackError(function(request,response){ console.log('auth.error:',request,response); }); everyauth.facebook .appId('294934693859231') .appSecret('2b77a53643850578682ca236a9edd63e') .redirectPath('/') .findOrCreateUser(function(session,accessToken,accessTokExtra,fbUserMetadata){ return facebookID[fbUserMetadata.id] || (facebookID[fbUserMetadata.id] = addUser('facebook',fbUserMetadata)); }) .handleAuthCallbackError(function(request,response){ console.log('auth.error:',request,response); }); everyauth .password .loginWith('email') .getLoginPath('/login') .postLoginPath('/login') .loginView('login.jade') // .loginLocals({ // title: 'Login' // }) /*.loginLocals(function (req, res) { return { title: 'Login' } })*/ .loginLocals(function(req,res,done){ setTimeout(function(){ done(null,{ title: 'Async login' }); },200); }) .authenticate(function(login,password){ var errors = []; if (!login) errors.push('Missing login'); if (!password) errors.push('Missing password'); if (errors.length) return errors; var user = localUsers[login]; if (!user) return ['Login failed']; if (user.password !== password) return ['Login failed']; return user; }) .getRegisterPath('/register') .postRegisterPath('/register') .registerView('register.jade') // .registerLocals({ // title: 'Register' // }) .registerLocals(function (req, res) { return { title: 'Sync Register' } }) /*.registerLocals( function (req, res, done) { setTimeout( function () { done(null, { title: 'Async Register' }); }, 200); })*/ .validateRegistration( function (newUserAttrs, errors) { var login = newUserAttrs.login; if (localUsers[login]) errors.push('Login already taken'); return errors; }) .registerUser( function (newUserAttrs) { var login = newUserAttrs[this.loginKey()]; localUsers[login] = addUser('local',newUserAttrs); return localUsers[login]; }) .loginSuccessRedirect('/') .registerSuccessRedirect('/'); everyauth.everymodule.findUserById(function(id,callback){ var protocol = users[id].protocol, username = protocol + '|' + users[id][protocol].id; // If I decide to do so, here would be a good place to handle passing // protocol-specific usernames. Maybe pass ghUser to addUser(), etc. callback(null,username); }); everyauth.helpExpress(app); return everyauth.middleware(); };
/** * Init function called in server.js to initialize this module * * @param {Object} theModules variable to access the other modules. */ WebServer.init = function(theModules) { Modules = theModules; var server = require('http').createServer(app); WebServer.server = server; server.listen(global.config.port); // start server (port set in config file) }; everyauth.password .loginFormFieldName('username') .passwordFormFieldName('password') .getLoginPath('/login') // Uri path to the login page .postLoginPath('/login') // Uri path that your login form POSTs to .loginView('login.html') .authenticate(function(login, password) { var errors = []; if (!login) { errors.push('Missing username'); } if (!password) { errors.push('Missing password'); }
var nextUserId = 0 /* code start */ everyauth.everymodule.findUserById(function (id, fn) { fn(false, usersById[id]) }) everyauth.everymodule.logoutPath('/logout/') everyauth.everymodule.logoutRedirectPath('/') /** * password auth */ everyauth.password // login partion .loginWith('email') .getLoginPath('/login/') .postLoginPath('/login/') .loginView(__dirname + '/../../views/login.jade') .authenticate(function(login, password, app) { var promise = this.Promise() var user = { email: login, password: password } authUtils.uncode(user, function(err, user) { if (err) return promise.fulfill([err]) usersById[user.id = ++nextUserId] = user promise.fulfill(user) })
init: function(app){ everyauth.password .loginWith('email') .getLoginPath('/login') // Uri path to the login page .postLoginPath('/login') // Uri path that your login form POSTs to .loginView('login') .authenticate( function (email, password) { // Either, we return a user or an array of errors if doing sync auth. // Or, we return a Promise that can fulfill to promise.fulfill(user) or promise.fulfill(errors) // `errors` is an array of error message strings // // e.g., // Example 1 - Sync Example // if (usersByLogin[login] && usersByLogin[login].password === password) { // return usersByLogin[login]; // } else { // return ['Login failed']; // } // // Example 2 - Async Example // var promise = this.Promise() // YourUserModel.find({ login: login}, function (err, user) { // if (err) return promise.fulfill([err]); // promise.fulfill(user); // } // return promise; var promise = this.Promise(); db.Users.by_email(email, function(err, user){ if (err) return promise.fulfill([err]); if (user && verify(user, password)){ promise.fulfill(user); } promise.fulfill(['Wrong username or password.']); }); return promise; }) .respondToLoginSucceed(function(res, user, data){ //careful! this function is called in both cases if(user) { res.json({'status':'ok', 'user':user}); } }) .respondToLoginFail(function(req, res, errors, username){ //careful! this function is called in both cases if (!errors || !errors.length) return; res.json({'status':'error', 'error':errors}); }) .respondToRegistrationSucceed(function(res, user, data){ //careful! this function is called in both cases if(user) { res.json({'status':'ok', 'user':user}); } }) .respondToRegistrationFail(function(req, res, error, username){ //careful! this function is called in both cases if (!errors || !errors.length) return; res.json({'status':'error', 'error':errors}); }) .getRegisterPath('/register') // Uri path to the registration page .postRegisterPath('/register') // The Uri path that your registration form POSTs to .registerView('register') .validateRegistration( function (newUserAttributes, baseErrors) { // Validate the registration input // Return undefined, null, or [] if validation succeeds // Return an array of error messages (or Promise promising this array) // if validation fails // // e.g., assuming you define validate with the following signature // var errors = validate(login, password, extraParams); // return errors; // // The `errors` you return show up as an `errors` local in your jade template // First, validate your errors. Here, validateUser is a made up function var promise = this.Promise(); var e = []; if(newUserAttributes.password.length < 5){ e.push("Password too short."); } if(newUserAttributes.email.length === 0){ e.push("Enter an email."); } if (e.length > 0){ promise.fulfill(e); } else { db.Users.by_email_exists(newUserAttributes.email, function(err, exists){ if (err) return promise.fulfill([err]); if (exists) { e.push("An account with this email already exists."); } promise.fulfill(e); }); } return promise; }) .registerUser( function (newUserAttributes) { // This step is only executed if we pass the validateRegistration step without // any errors. // // Returns a user (or a Promise that promises a user) after adding it to // some user store. // // As an edge case, sometimes your database may make you aware of violation // of the unique login index, so if this error is sent back in an async // callback, then you can just return that error as a single element array // containing just that error message, and everyauth will automatically handle // that as a failed registration. Again, you will have access to this error via // the `errors` local in your register view jade template. // e.g., // var promise = this.Promise(); // User.create(newUserAttributes, function (err, user) { // if (err) return promise.fulfill([err]); // promise.fulfill(user); // }); // return promise; // // Note: Index and db-driven validations are the only validations that occur // here; all other validations occur in the `validateRegistration` step documented above. var promise = this.Promise(); newUserAttributes.password = hash(newUserAttributes.email, newUserAttributes.password); newUserAttributes.account_type = 'password'; var user = new db.User(newUserAttributes); user.save(function(err){ if(err) return promise.fulfill([err]); promise.fulfill(user); }); return promise; }) .everyauth .browser_id .authenticate(function(user, req, res){ if(!user) return ['Login Failed']; var promise = this.Promise(); db.Users.by_email(user.email, function(err, dbuser){ if (err) return promise.fulfill([err]); if(!dbuser) { //create the user attributes = { email: user.email, browser_id_audience: user.audience, browser_id_session_expire: user.audience, browser_id_issuer: user.issuer, account_type: 'browser_id' } dbuser = new db.User(attributes); dbuser.save(function(err){ if(err) return promise.fulfill([err]); promise.fulfill(dbuser); }); } promise.fulfill(dbuser); }); return promise; }); everyauth.helpExpress(app, {userAlias:'user'}); everyauth.everymodule.findUserById(function (userId, callback) { // todo: don't look up the user in the database for every single request (including static requests) db.Users.by_id(userId, callback); }); },
var userProvider = new UserProvider('localhost', 27017); // EveryAuth helpers definition everyauth.everymodule.findUserById( function (userId, callback) { userProvider.findById(userId, function (err, value){ if (err) { callback(err); } else { callback (null, value); } }); }); //EveryAuth login field selection : we do prefer using email as an id for our applciation everyauth.password.loginWith('email'); // EveryAuth Password Registration everyauth.password.getRegisterPath('/register'); everyauth.password.postRegisterPath('/register'); everyauth.password.registerView('register.ejs'); everyauth.password.registerLocals({title : 'Social Demo : Enregistrement'}); everyauth.password.validateRegistration( function (newUserAttrs) { var errors = []; var promise = this.Promise(); console.log('new user attr:'+util.inspect(newUserAttrs)); var fieldName = everyauth.password.loginFormFieldName(); var fieldValue = newUserAttrs[fieldName]; userProvider.findByField(fieldName, fieldValue, function(err, user){ console.log('err: '+util.inspect(err)+' - user:'+util.inspect(user)); if (err) {