app/auth/index.js   A
last analyzed

Complexity

Total Complexity 14
Complexity/F 1.56

Size

Lines of Code 69
Function Count 9

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
c 1
b 0
f 0
nc 1
dl 0
loc 69
rs 10
wmc 14
mnd 1
bc 14
fnc 9
bpm 1.5555
cpm 1.5555
noi 1

1 Function

Rating   Name   Duplication   Size   Complexity  
A index.js ➔ init 0 50 1
1
'use strict';
2
3
var config 		= require('../config');
4
var passport 	= require('passport');
5
var logger 		= require('../logger');
6
7
var LocalStrategy 		= require('passport-local').Strategy;
8
var FacebookStrategy  	= require('passport-facebook').Strategy;
9
var TwitterStrategy  	= require('passport-twitter').Strategy;
10
11
var User = require('../models/user');
12
13
/**
14
 * Encapsulates all code for authentication 
15
 * Either by using username and password, or by using social accounts
16
 *
17
 */
18
var init = function(){
19
20
	// Serialize and Deserialize user instances to and from the session.
21
	passport.serializeUser(function(user, done) {
22
		done(null, user.id);
23
	});
24
25
	passport.deserializeUser(function(id, done) {
26
		User.findById(id, function (err, user) {
27
			done(err, user);
28
		});
29
	});
30
31
	// Plug-in Local Strategy
32
	passport.use(new LocalStrategy(
33
	  function(username, password, done) {
34
	    User.findOne({ username: new RegExp(username, 'i'), socialId: null }, function(err, user) {
35
	      if (err) { return done(err); }
36
37
	      if (!user) {
38
	        return done(null, false, { message: 'Incorrect username or password.' });
39
	      }
40
41
	      user.validatePassword(password, function(err, isMatch) {
42
	        	if (err) { return done(err); }
43
	        	if (!isMatch){
44
	        		return done(null, false, { message: 'Incorrect username or password.' });
45
	        	}
46
	        	return done(null, user);
47
	      });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
48
49
	    });
50
	  }
51
	));
52
53
	// In case of Facebook, tokenA is the access token, while tokenB is the refersh token.
54
	// In case of Twitter, tokenA is the token, whilet tokenB is the tokenSecret.
55
	var verifySocialAccount = function(tokenA, tokenB, data, done) {
56
		User.findOrCreate(data, function (err, user) {
57
	      	if (err) { return done(err); }
58
			return done(err, user); 
59
		});
60
	};
61
62
	// Plug-in Facebook & Twitter Strategies
63
	passport.use(new FacebookStrategy(config.facebook, verifySocialAccount));
64
	passport.use(new TwitterStrategy(config.twitter, verifySocialAccount));
65
66
	return passport;
67
}
68
	
69
module.exports = init();