Example #1
0
CouchDBTools.requirejs(["CouchDBUser", "Transport"], function (CouchDBUser, Transport) {

	var transport = new Transport(olives.handlers);

	var io = socketIO.listen(http.createServer(connect()
			.use(connect.responseTime())
			.use(function (req, res, next) {
				res.setHeader("Server", "node.js/" + process.versions.node);
				res.setHeader("X-Powered-By", "OlivesJS + Connect + Socket.io")
				next();
			})
			.use(connect.cookieParser())
			.use(connect.session({
				secret: "not so secret when it's on github",
				key: "suggestions.sid",
				store: sessionStore,
				cookie: {
					maxAge: null,
					httpOnly: true,
					path: "/"
				}
			}))
			.use(connect.static(__dirname + "/public"))
		).listen(8000), {log:true});

		http.globalAgent.maxSockets = Infinity;

		olives.registerSocketIO(io);

		olives.handlers.set("CreateAccount", function (json, onEnd) {
			var user = new CouchDBUser;

			user.setTransport(transport);

			user.set("password", json.password);
			user.set("name", json.name);

			user.create().then(function (si) {
				onEnd({
					status: "okay",
					message: "The account was successfully created."
				})
				user.unsync();
			}, function (json) {
				if (json.error == "conflict") {
					onEnd({
						status: "failed",
						message: "An account with this user name already exists."
					});
				}
				user.unsync();
			});
		});

		olives.handlers.set("Login", function (json, onEnd) {
			var user = new CouchDBUser;

			user.setTransport(transport);

			user.set("password", json.password);
			user.set("name", json.name);

			user.login().then(function (result) {

				var result = JSON.parse(result);

				if (!result.error) {

					var cookieJSON = cookie.parse(json.handshake.headers.cookie),
						sessionID = cookieJSON["suggestions.sid"].split("s:")[1].split(".")[0];

					sessionStore.get(sessionID, function (err, session) {
						if (err) {
							throw new Error(err);
						} else {

							session.auth = json.name + ":" + json.password;
							sessionStore.set(sessionID, session);
							onEnd({
								status: "okay",
								message: json.name + " is logged-in"
							});
						}
					});

				} else {
					onEnd({
						status: "failed",
						message: "name or password incorrect"
					});
				}

				user.unsync();
			}, function (result) {
				var error = JSON.stringify(result);
				onEnd({
						status: "failed",
						message: "Unexpected error" + error
					});
				log("error", error);
				user.unsync();
			});
		});

});
Example #2
0
CouchDBTools.requirejs(["CouchDBUser", "Transport", "CouchDBDocument", "CouchDBView", "CouchDBBulkDocuments", "Store", "Promise"], function(CouchDBUser, Transport, CouchDBDocument, CouchDBView, CouchDBBulkDocuments, Store, Promise) {
        var transport = new Transport(olives.handlers),
            app = http.createServer(connect()
                .use(connect.logger())
		.use(connect.responseTime())
                .use(redirect())
                .use(connect.bodyParser({ uploadDir:contentPath+'/public/upload', keepExtensions: true }))
                .use('/upload', srvUtils.uploadFunc)
		.use('/downloads', srvUtils.downloadFunc)      
                .use(function(req, res, next) {
                        res.setHeader("Ideady Server", "node.js/" + process.versions.node);
                        res.setHeader("X-Powered-By", "OlivesJS + Connect + Socket.io");
                        next();
                })
                .use(connect.cookieParser())
                .use(connect.session({
                        secret : "olives&vin2012AD",
                        key : "ideafy.sid",
                        store : sessionStore,
                        cookie : {
                                maxAge : 864000000,
                                httpOnly : true,
                                path : "/"
                        }
                }))
                .use(connect.static(__dirname + "/public"))).listen(3113),
                io = socketIO.listen(app, {
                        log : true
                });
                
        // Socket.io configuration
        io.enable('browser client minification');  // send minified client
        io.enable('browser client etag');          // apply etag caching logic based on version number
        io.enable('browser client gzip');          // gzip the file
        io.set('log level', 0);                    // reduce logging
        io.set("close timeout", 60);
        io.set("heartbeat interval", 25);
        
        // we need lots of sockets
        http.globalAgent.maxSockets = Infinity;
        
        setInterval(function(){
                console.log("number of sockets used : ", Object.keys(io.connected).length, "socket names : ", JSON.stringify(Object.keys(io.connected)));
        }, 60000);
        
        // register transport
        olives.registerSocketIO(io);
        
        // couchdb config update (session authentication)
        //olives.config.update("CouchDB", "sessionStore", sessionStore);
        CouchDBTools.configuration.sessionStore = sessionStore;
        olives.handlers.set("CouchDB", CouchDBTools.handler);
        
        /*
         *  Application utility functions
         */
        
        // cdbadmin utilities
       CDBAdmin.setVar(_db, _dbIP, _dbPort, cdbAdminCredentials, transport);
       CDBAdmin.setConstructors(Promise, CouchDBDocument);
        
        var updateUserIP = CDBAdmin.updateUserIP,
              updateDocAsAdmin = CDBAdmin.updateDoc,
              getDocAsAdmin = CDBAdmin.getDoc,
              createDocAsAdmin = CDBAdmin.createDoc,
              getViewAsAdmin = CDBAdmin.getView,
              removeDocAsAdmin = CDBAdmin.removeDoc,
              sendSignupEmail = comUtils.sendSignupEmail,
              checkInvited = appUtils.checkInvited,
              addInvited = appUtils.addInvited; 
                       
        // utility handlers (no couchdb)
        srvUtils.setVar(contentPath, currentVersion);
        olives.handlers.set("CheckVersion", srvUtils.checkVersion);
        olives.handlers.set("GetFile", srvUtils.getFile);
        olives.handlers.set("Lang", srvUtils.getLabels);
        olives.handlers.set("GetLanguages", srvUtils.getLanguages);
        olives.handlers.set("cleanUpSession", srvUtils.cleanUpSession);
        olives.handlers.set("DeleteAttachment", srvUtils.deleteAttachment);
        
        // login utilities
        loginUtils.setConstructors(CouchDBDocument, CouchDBUser, Promise);
        loginUtils.setFunctions(sendSignupEmail, checkInvited, CDBAdmin, comUtils.sendMail);
        loginUtils.setVar(cookie, sessionStore, transport, _db, cdbAdminCredentials, supportEmail);
        
        olives.handlers.set("Signup", loginUtils.signup);
        olives.handlers.set("CheckLogin", loginUtils.checkLogin);
        olives.handlers.set("Login", loginUtils.login);
        olives.handlers.set("ChangePWD", loginUtils.changePassword);
        olives.handlers.set("ResetPWD", loginUtils.resetPassword);
        
        // communication utilities (mail and application notifications)
        comUtils.setVar(smtpTransport, supportEmail, mailSender);
        comUtils.setConstructors(CouchDBDocument, Store);
        comUtils.setFunctions(CDBAdmin, checkInvited, addInvited);
        olives.handlers.set("SendMail", comUtils.sendMail);
        olives.handlers.set("Support", comUtils.support);
        olives.handlers.set("Notify", comUtils.notify);
        olives.handlers.set("Invite", comUtils.invite);
        
        // application utilities and handlers
        appUtils.setConstructors(CouchDBDocument, CouchDBView, Promise);
        appUtils.setVar(transport, _db, _dbIP, _dbPort, cdbAdminCredentials, badges, contentPath);
        appUtils.setCDBAdmin(CDBAdmin);
        olives.handlers.set("DeleteDeck", appUtils.deleteDeck);
        olives.handlers.set("DeleteCards", appUtils.removeCardsFromDatabase);
        olives.handlers.set("ShareDeck", appUtils.shareDeck);
        olives.handlers.set("GetFavList", appUtils.getFavList);
        olives.handlers.set("GetAvatar", appUtils.getAvatar);
        olives.handlers.set("GetUserDetails", appUtils.getUserDetails);
        olives.handlers.set("GetGrade", appUtils.getGrade);
        olives.handlers.set("GetAchievements", appUtils.getAchievements);
        olives.handlers.set("GetUserNames", appUtils.getUserNames);
        olives.handlers.set("Welcome", appUtils.welcome);
        olives.handlers.set("CheckRecipientList", appUtils.checkRecipientList);
        olives.handlers.set("Vote", appUtils.vote);
        olives.handlers.set("RemoveFromLibrary", appUtils.removeFromLibrary);
        olives.handlers.set("WriteTwocent", appUtils.writeTwocent);
        olives.handlers.set("SendTwocent", appUtils.sendTwocent);
        olives.handlers.set("UpdateUIP", appUtils.updateUIP);
        olives.handlers.set("UpdateSessionScore", appUtils.updateSessionScore);
        
        // disconnection events
        io.sockets.on("connection", function(socket){
                socket.on("disconnect", function(){
                        appUtils.setOffline(socket);       
                });  
        });       
});