app/models/user.js   A
last analyzed

Complexity

Total Complexity 12
Complexity/F 1.71

Size

Lines of Code 68
Function Count 7

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 0
c 2
b 0
f 0
nc 1
dl 0
loc 68
rs 10
wmc 12
mnd 2
bc 13
fnc 7
bpm 1.8571
cpm 1.7142
noi 2

5 Functions

Rating   Name   Duplication   Size   Complexity  
A user.js ➔ findOne 0 3 1
A user.js ➔ findById 0 3 1
A user.js ➔ create 0 4 1
B user.js ➔ findOrCreate 0 25 1
A user.js ➔ isAuthenticated 0 7 2
1
'use strict';
2
3
var userModel = require('../database').models.user;
4
5
var create = function (data, callback){
6
	var newUser = new userModel(data);
0 ignored issues
show
Coding Style Best Practice introduced by
By convention, constructors like userModel should be capitalized.
Loading history...
7
	newUser.save(callback);
8
};
9
10
var findOne = function (data, callback){
11
	userModel.findOne(data, callback);
12
}
13
14
var findById = function (id, callback){
15
	userModel.findById(id, callback);
16
}
17
18
19
/**
20
 * Find a user, and create one if doesn't exist already.
21
 * This method is used ONLY to find user accounts registered via Social Authentication.
22
 *
23
 */
24
var findOrCreate = function(data, callback){
25
	findOne({'socialId': data.id}, function(err, user){
26
		if(err) { return callback(err); }
27
		if(user){
28
			return callback(err, user);
29
		} else {
30
			var userData = {
31
				username: data.displayName,
32
				socialId: data.id,
33
				picture: data.photos[0].value || null
34
			};
35
36
			// To avoid expired Facebook CDN URLs
37
			// Request user's profile picture using user id 
38
			// @see http://stackoverflow.com/a/34593933/6649553
39
			if(data.provider == "facebook" && userData.picture){
40
				userData.picture = "http://graph.facebook.com/" + data.id + "/picture?type=large";
41
			}
42
43
			create(userData, function(err, newUser){
44
				callback(err, newUser);
45
			});
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...
46
		}
47
	});
48
}
49
50
/**
51
 * A middleware allows user to get access to pages ONLY if the user is already logged in.
52
 *
53
 */
54
var isAuthenticated = function (req, res, next) {
55
	if(req.isAuthenticated()){
56
		next();
57
	}else{
58
		res.redirect('/');
59
	}
60
}
61
62
module.exports = { 
63
	create, 
64
	findOne, 
65
	findById, 
66
	findOrCreate, 
67
	isAuthenticated 
68
};
69