Skip to content

fixed usage of Meteor.userId for server enviroment + using grunt #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
npm-debug.log
node_modules
44 changes: 44 additions & 0 deletions Gruntfile.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
module.exports = (grunt) ->

# Project configuration.
grunt.initConfig
pkgFile: 'package.json'

'npm-contributors':
options:
commitMessage: 'chore: update contributors'

bump:
options:
commitMessage: 'chore: release v%VERSION%'
pushTo: 'origin'

jshint:
options:
globals:
console: true,
module: true
all:
src: ['*.js']

coffeelint:
options:
no_tabs: {level: 'ignore'}
indentation: {level: 'ignore'}
all: ['*.coffee']

grunt.loadNpmTasks 'grunt-contrib-jshint'
grunt.loadNpmTasks 'grunt-coffeelint'
grunt.loadNpmTasks 'grunt-npm'
grunt.loadNpmTasks 'grunt-bump'

grunt.registerTask 'release', 'Bump the version and publish to NPM.',
(type) -> grunt.task.run [
'npm-contributors',
"bump:#{type||'patch'}",
'npm-publish'
]

grunt.registerTask 'lint', ['jshint', 'coffeelint']
grunt.registerTask 'test', ['lint']
grunt.registerTask 'default', ['test']
143 changes: 56 additions & 87 deletions common.js
Original file line number Diff line number Diff line change
@@ -1,110 +1,79 @@
// This collection is where the UserSession variables are ultimately stored
UserSessionCollection = new Meteor.Collection('userSessionCollection');

// Anonymous user error
noUserError = function () {
console.log('You cannot use UserSession methods when there is no user logged in.');
// Resolves userId depending on current execution environment
function resolveUserId(userId) {
if (Meteor.isServer) {
if (typeof userId === 'undefined') {
console.log('You cannot use UserSession methods on the server without a userId.');
return undefined;
}
}
// ignore input userId using userId of current user
// since on client environment users cannot read settings of other users
userId = Meteor.userId();
if (!userId) {
console.log('You cannot use UserSession methods when there is no user logged in.');
}
return userId;
}

// Missing userId error
noUserIdError = function () {
console.log('You cannot use UserSession methods on the server without a userId.');
// Calls given function with existing variable or returns defval if var does not exist
function invoke(key, userId, defval, fn) {
userId = resolveUserId(userId);
if (!userId) return defval;
var selector = {userId: userId};
if (key) selector.key = key;
var existing = UserSessionCollection.findOne(selector);
return existing ? fn(existing) : defval;
}


//=======================
// = UserSession METHODS
//=======================

UserSession = {
// Sets a new variable in the user session
set: function (key, value, userId) {
// Set a new variable in the user session
if (Meteor.userId() || Meteor.isServer) {
// If the user is logged in, update the variable in the collection
if (typeof userId === 'undefined') {
if (Meteor.isClient) userId = Meteor.userId();
else if (Meteor.isServer) {
noUserIdError();
return undefined;
}
}
var existing = UserSessionCollection.findOne({ key: key, userId: userId});
var sv = { key: key, value: value, userId: userId };
if (existing) UserSessionCollection.update({ _id: existing._id }, { $set: sv });
else UserSessionCollection.insert(sv);
} else {
//XXX Maybe we should degrade to normal Session and sync on login
noUserError();
}
userId = resolveUserId(userId);
if (!userId) return undefined;
var existing = UserSessionCollection.findOne({ key: key, userId: userId});
var sv = { key: key, value: value, userId: userId };
if (existing) UserSessionCollection.update({ _id: existing._id }, { $set: sv });
else UserSessionCollection.insert(sv);
},
// Gets the value of a user session variable
get: function (key, userId) {
// Get the value of a user session variable
if (Meteor.userId() || Meteor.isServer) {
if (typeof userId === 'undefined') {
if (Meteor.isClient) userId = Meteor.userId();
else if (Meteor.isServer) {
noUserIdError();
return undefined;
}
}
var existing = UserSessionCollection.findOne({ key: key, userId: userId});
if (existing) return existing.value;
} else {
noUserError();
}
return invoke(key, userId, undefined, function(it){
return it.value;
});
},
// Deletes a user session variable, if it exists
delete: function (key, userId) {
// Delete a user session variable, if it exists
if (Meteor.userId() || Meteor.isServer) {
if (typeof userId === 'undefined') {
if (Meteor.isClient) userId = Meteor.userId();
else if (Meteor.isServer) {
noUserIdError();
return undefined;
}
}
var existing = UserSessionCollection.findOne({ key: key, userId: userId});
if (existing) UserSessionCollection.remove(existing._id);
} else {
noUserError();
}
return invoke(key, userId, undefined, function(it){
return UserSessionCollection.remove(it._id);
});
},
// Tests if a user session variable is equal to a value
equals: function (key, value, userId) {
// Test if a user session variable is equal to a value
if (Meteor.userId() || Meteor.isServer) {
if (typeof userId === 'undefined') {
if (Meteor.isClient) userId = Meteor.userId();
else if (Meteor.isServer) {
noUserIdError();
return undefined;
}
}
var existing = UserSessionCollection.findOne({ key: key, userId: userId});
if (existing) return existing.value == value; //XXX Should this be ===
} else {
noUserError();
}
return invoke(key, userId, false, function(it){
return it.value == value; //XXX Should this be ===
});
},
// Gets all the user session variables as an object
list: function (userId) {
// Get all the user session variables as an object
if (Meteor.userId() || Meteor.isServer) {
if (typeof userId === 'undefined') {
if (Meteor.isClient) userId = Meteor.userId();
else if (Meteor.isServer) {
noUserIdError();
return undefined;
}
}
var existing = UserSessionCollection.findOne({ userId: userId});
if (existing) {
var list = {};
UserSessionCollection.find({ userId: userId }).forEach(function (sv) {
list[sv.key] = sv.value;
});
return list;
}
} else {
noUserError();
}
return invoke(null, userId, {}, function(){
var list = {};
UserSessionCollection.find({userId: userId}).forEach(function(it) {
list[it.key] = it.value;
});
return list;
});
},
// Determines whether given variable exists in user session
has: function (key, userId) {
return invoke(key, userId, false, function(){
return true;
});
}
};
2 changes: 1 addition & 1 deletion package.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Package.describe({
summary: "Provides a UserSession object that works just like Session does, except it's persistent so you can preserve state across devices *and* sessions."
});

var both = ['client', 'server']
var both = ['client', 'server'];

Package.on_use(function (api) {
api.use('underscore', both);
Expand Down
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "meteor-user-session",
"version": "0.2.0",
"description": "Provides a UserSession object that works just like Session does, except it's persistent so you can preserve state across devices *and* sessions.",
"author": "Benjamin Harris <http://benjaminrharris.com>",
"repository": {
"type": "git",
"url": "https://github.com/BenjaminRH/meteor-user-session.git"
},
"keywords": [
"meteor",
"user",
"session"
],
"contributors": [
"Benjamin Harris <http://benjaminrharris.com>",
"Sergey Todyshev <[email protected]>"
],
"dependencies": {},
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-jshint": "~0.7.1",
"grunt-coffeelint": "0.0.8"
"grunt-cli": "~0.1.11",
"grunt-npm": "0.0.2",
"grunt-bump": "0.0.13"
},
"scripts": {
"lint": "grunt lint",
"test": "grunt test"
}
}
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Meteor.publish('userSessionCollection', function () {
// Check that the userId specified owns the documents
ownsDocument = function (userId, doc) {
return doc && doc.userId === userId;
}
};

// Allow methods for UserSessionCollection (security)
UserSessionCollection.allow({
Expand Down