Prechádzať zdrojové kódy

Replaced rethinkDB with mongoDB, added user schema and continued work on authentication

Jonathan 8 rokov pred
rodič
commit
3c6af209fa
8 zmenil súbory, kde vykonal 154 pridanie a 94 odobranie
  1. 0 1
      .gitignore
  2. 1 1
      README.md
  3. 19 27
      bootstrap.sh
  4. 2 2
      package.json
  5. 78 57
      src/app.js
  6. 10 5
      src/logic/coreHandler.js
  7. 1 1
      src/logic/global.js
  8. 43 0
      src/schemas/user.js

+ 0 - 1
.gitignore

@@ -89,5 +89,4 @@ Thumbs.db
 .DS_Store
 
 .vagrant/
-rethinkdb_data/
 config/default.json

+ 1 - 1
README.md

@@ -39,7 +39,7 @@ You can run `vagrant` to view more options.
 You can view logs at the following locations:
 
 * Musare: `/var/log/upstart/musare.log`
-* RethinkDB: `/var/log/upstart/rethinkdb.log`
+* mongoDB: `/var/log/upstart/mongodb.log`
 
 ### Development
 

+ 19 - 27
bootstrap.sh

@@ -2,7 +2,7 @@
 
 function command_exists { type "$1" &> /dev/null; }
 
-# install NodeJS
+# install mosh
 if command_exists "mosh"; then
 	echo "Skipping mosh install"
 else
@@ -19,45 +19,37 @@ else
 	sudo apt-get install -y nodejs
 fi
 
-# install RethinkDB
-if command_exists "rethinkdb"; then
-	echo "Skipping rethinkdb install"
+# install mongodb
+if command_exists "mongo"; then
+	echo "Skipping mongodb install"
 else
-	echo "Installing rethinkdb"
-	source /etc/lsb-release && echo "deb http://download.rethinkdb.com/apt $DISTRIB_CODENAME main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list
-	wget -qO- https://download.rethinkdb.com/apt/pubkey.gpg | sudo apt-key add -
+	echo "Installing mongodb"
+	sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
+	echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
 	sudo apt-get update
-	sudo apt-get install -y rethinkdb
+	sudo apt-get install -y mongodb-org
 fi
 
-# setup a service for RethinkDB
-if [ -f /etc/init/rethinkdb.conf ]; then
-	echo "Skipping up rethinkdb service"
+# setup a service for mongodb
+if [ -f /etc/init/mongodb.conf ]; then
+	echo "Skipping up mongodb service"
 else
-	echo "Setting up rethinkdb service"
-	sudo tee -a /etc/init/rethinkdb.conf > /dev/null <<EOF
-description "Service file for starting / stopping rethinkdb"
+	echo "Setting up mongoDB service"
+	sudo tee -a /etc/init/mongodb.conf > /dev/null <<EOF
+description "Service file for starting / stopping mongodb"
 author "Musare Developers"
-
 start on filesystem
 stop on shutdown
-
-setgid rethinkdb
 console log
-
 script
-	echo \$\$ > /var/run/rethinkdb.pid
-	cd /musare
-	exec rethinkdb --bind all
+	exec mongod
 end script
-
 pre-start script
-	echo "[\`date\`] rethinkdb starting" >> /var/log/rethinkdb.log
+	echo "[\`date\`] mongodb starting" >> /var/log/mongodb.log
 end script
-
 pre-stop script
-	rm /var/run/rethinkdb.pid
-	echo "[\`date\`] rethinkdb stopping" >> /var/log/rethinkdb.log
+	rm /var/run/mongodb.pid
+	echo "[\`date\`] mongodb stopping" >> /var/log/mongodb.log
 end script
 EOF
 fi
@@ -98,4 +90,4 @@ fi
 # automatically install all of our dependencies
 cd /musare
 npm install --no-bin-links
-sudo npm install --global gulp-cli
+sudo npm install -g gulp-cli

+ 2 - 2
package.json

@@ -8,15 +8,15 @@
     "async": "2.0.1",
     "body-parser": "^1.15.2",
     "config": "^1.21.0",
+    "connect-mongo": "^1.3.2",
     "cookie-parser": "^1.4.3",
     "express": "^4.14.0",
     "express-session": "^1.14.0",
+    "mongoose": "^4.6.0",
     "passport": "^0.3.2",
     "passport-local": "^1.0.0",
     "passport.socketio": "^3.6.2",
     "request": "^2.74.0",
-    "rethinkdb": "^2.3.2",
-    "session-rethinkdb": "^2.0.0",
     "socket.io": "^1.4.8"
   },
   "devDependencies": {

+ 78 - 57
src/app.js

@@ -7,15 +7,15 @@ const path = require('path'),
 
 // npm modules
 const express          = require('express'),
-      session          = require('express-session'),
-      rethinkdbStore   = require('session-rethinkdb')(session),
-      bodyParser       = require('body-parser'),
-      config           = require('config'),
-      request          = require('request'),
-      r                = require('rethinkdb'),
-      passport         = require('passport'),
-      localStrategy    = require('passport-local').Strategy,
-      passportSocketIo = require("passport.socketio");
+    session          = require('express-session'),
+    mongoose         = require('mongoose'),
+    mongoStore       = require('connect-mongo')(session),
+    bodyParser       = require('body-parser'),
+    config           = require('config'),
+    request          = require('request'),
+    passport         = require('passport'),
+    localStrategy    = require('passport-local').Strategy,
+    passportSocketIo = require("passport.socketio");
 
 // custom modules
 const global         = require('./logic/global'),
@@ -23,68 +23,89 @@ const global         = require('./logic/global'),
       socketHandler  = require('./logic/socketHandler'),
       expressHandler = require('./logic/expressHandler');
 
+// database
+const MongoDB = mongoose.connect('mongodb://localhost:27017/musare').connection;
+
+MongoDB.on('error', function(err) {
+    console.log('Database error: ' + err.message);
+});
+
+MongoDB.once('open', function() {
+    console.log('Connected to database');
+});
+
+const db = {
+    user: require('./schemas/user')(mongoose)
+};
+
 // setup express and socket.io
-const app = express();
+const app = express(MongoDB);
 const server = app.listen(80);
 const io = require('socket.io')(server);
 
-// connect to our database before doing anything else
-r.connect( { host: 'localhost', port: 28015, db: 'musare' }, function(err, rc) {
-	if (err) {
-		console.log(err);
-	} else {
+global.io = io;
+global.db = db;
 
-		global.rc = rc;
-		global.io = io;
+app.use(passport.initialize());
+app.use(passport.session());
 
-        const store = new rethinkdbStore(r);
+app.use(session({
+    secret: config.get('secret'),
+    store: new mongoStore({ mongooseConnection: MongoDB }),
+    resave: true,
+    saveUninitialized: true
+}));
 
-        app.use(passport.initialize());
-        app.use(passport.session());
+io.use(passportSocketIo.authorize({
+  secret: config.get('secret'),
+  store: new mongoStore({ mongooseConnection: MongoDB })
+}));
 
-        app.use(session({
-          secret: config.get('secret'),
-          store,
-          resave: true,
-          saveUninitialized: true
-        }));
+passport.serializeUser(function(user, done) {
+    done(null, user);
+});
 
-        io.use(passportSocketIo.authorize({
-          secret: config.get('secret'),
-          store: store,
-        }));
+passport.deserializeUser(function(user, done) {
+    done(null, user);
+});
 
-        passport.serializeUser(function(user, done) {
-            done(null, user);
+passport.use('local-signup', new localStrategy (function(username, password, cb) {
+    process.nextTick(function() {
+        db.user.findOne({'username' : username }, function(err, user) {
+            if (err) return cb(err);
+            if (user) return cb(null, false);
+            else {
+                var newUser = new db.user({
+                    username: username
+                });
+                newUser.save(function(err) {
+                    if (err) throw err;
+                    return cb(null, newUser);
+                });
+            }
         });
+    });
+}));
+
+passport.use('local-login', new localStrategy (function(username, password, cb) {
+    process.nextTick(function() {
+        db.user.findOne({'username' : username }, function(err, user) {
+            if (err) return cb(err);
+            if (!user) return cb(null, false);
+            if (!user.services.token.password == password) return done(null, false);
 
-        passport.deserializeUser(function(user, done) {
-            done(null, user);
+            return done(null, user);
         });
+    });
+}));
 
-        passport.use(new localStrategy(function(username, password, done) {
-            process.nextTick(function() {
-                r.table('users').filter({
-                    username: username
-                }).run(rc, function (err, cursor) {
-                    if (err) return done(err);
-                    cursor.toArray(function (err, result) {
-                        if (!result) return done(null, false);
-                        if (result.password != password) return done(null, false);
-                        return done(null, user);
-                    });
-                });
-            });
-        }));
 
-        app.use(bodyParser.json());
-        app.use(bodyParser.urlencoded({
-            extended: true
-        }));
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({
+    extended: true
+}));
 
-		app.use(express.static(__dirname + '/../public'));
+app.use(express.static(__dirname + '/../public'));
 
-		socketHandler(coreHandler, io);
-		expressHandler(coreHandler, app);
-    }
-});
+socketHandler(coreHandler, io);
+expressHandler(coreHandler, app);

+ 10 - 5
src/logic/coreHandler.js

@@ -10,7 +10,7 @@ const path   = require('path'),
 const config    = require('config'),
       request   = require('request'),
       waterfall = require('async/waterfall'),
-	  passport      = require('passport');
+	  passport  = require('passport');
 
 // custom modules
 const global   = require('./global'),
@@ -33,13 +33,18 @@ module.exports = {
 	// core route handlers
 
 	'/users/login': function (user, cb) {
-		passport.authenticate('local', {
-			successRedirect: cb({ status: 'success', message: 'Successfully logged in' }),
-			failureRedirect: cb({ status: 'error', message: 'Error while trying to log in' })
+		passport.authenticate('local-login', {
+			// successRedirect: cb({ status: 'success', message: 'Successfully logged in' }),
+			// failureRedirect: cb({ status: 'error', message: 'Error while trying to log in' })
 		});
 	},
 
-	'/users/register': function (user, cb) {},
+	'/users/register': function (user, cb) {
+		passport.authenticate('local-signup', {
+			// successRedirect: cb({ status: 'success', message: 'Successfully signed up' }),
+			// failureRedirect: cb({ status: 'error', message: 'Error while trying to sign up' })
+		});
+	},
 
 	'/stations': function (cb) {
 		cb(stations.getStations().map(function (result) {

+ 1 - 1
src/logic/global.js

@@ -30,8 +30,8 @@ function Timer(callback, delay, paused) {
 }
 
 module.exports = {
-	rc: null, // RethinkDB Connection, this gets set in app.js
 	io: null, // Socket.io
+	db: null, // Database
 	htmlEntities: function(str) {
 		return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
 	},

+ 43 - 0
src/schemas/user.js

@@ -0,0 +1,43 @@
+module.exports = function(mongoose) {
+
+    var Schema = mongoose.Schema;
+
+    var userSchema = new Schema({
+        username: String,
+        email: {
+            verified: { type: Boolean, default: false },
+            verificationToken: String,
+            address: String
+        },
+        services: {
+            password: {
+                token: String
+            },
+            github: {
+                token: String
+            },
+            discord: {
+                token: String
+            }
+        },
+        ban: {
+            banned: { type: Boolean, default: false },
+            reason: String,
+            bannedAt: Date,
+            bannedUntil: Date
+        },
+        mute: {
+            muted: { type: Boolean, default: false },
+            reason: String,
+            mutedAt: Date,
+            mutedUntil: Date
+        },
+        statistics: {
+            songsRequested: { type: Number, default: 0 },
+            songsAccepted: { type: Number, default: 0 }
+        },
+        createdAt: { type: Date, default: Date.now() }
+    });
+
+    return mongoose.model('user', userSchema);
+}