瀏覽代碼

Initial commit with rethink & passport example setup.

KrisVos130 8 年之前
當前提交
4e5490461c
共有 11 個文件被更改,包括 338 次插入0 次删除
  1. 87 0
      .gitignore
  2. 22 0
      client/html/index.html
  3. 22 0
      package.json
  4. 18 0
      server/auth/auth-controller.js
  5. 23 0
      server/auth/auth-router.js
  6. 78 0
      server/auth/index.js
  7. 24 0
      server/db/index.js
  8. 3 0
      server/global.js
  9. 0 0
      server/routes.js
  10. 60 0
      server/server.js
  11. 1 0
      static/test.txt

+ 87 - 0
.gitignore

@@ -0,0 +1,87 @@
+### Node template
+# Logs
+logs
+*.log
+npm-debug.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+
+# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (http://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules
+jspm_packages
+
+# Optional npm cache directory
+.npm
+
+# Optional REPL history
+.node_repl_history
+
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
+# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
+
+.idea/
+
+# User-specific stuff:
+.idea/workspace.xml
+.idea/tasks.xml
+.idea/dictionaries
+.idea/vcs.xml
+.idea/jsLibraryMappings.xml
+
+# Sensitive or high-churn files:
+.idea/dataSources.ids
+.idea/dataSources.xml
+.idea/dataSources.local.xml
+.idea/sqlDataSources.xml
+.idea/dynamic.xml
+.idea/uiDesigner.xml
+
+# Gradle:
+.idea/gradle.xml
+.idea/libraries
+
+# Mongo Explorer plugin:
+.idea/mongoSettings.xml
+
+## File-based project format:
+*.iws
+
+## Plugin-specific files:
+
+# IntelliJ
+/out/
+
+# mpeltonen/sbt-idea plugin
+.idea_modules/
+
+# JIRA plugin
+atlassian-ide-plugin.xml
+
+# Crashlytics plugin (for Android Studio and IntelliJ)
+com_crashlytics_export_strings.xml
+crashlytics.properties
+crashlytics-build.properties
+fabric.properties
+
+*.iml
+
+# Created by .ignore support plugin (hsz.mobi)
+

+ 22 - 0
client/html/index.html

@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Title</title>
+</head>
+<body>
+<h1>Musare!</h1>
+<h1>Passport/RethinkDB Example</h1>
+{{#user}}
+<img style='width: 100px; height: 100px;' src='{{ avatarUrl }}'>
+<p>You are logged in as <span style="font-weight: bold;">{{ login }}</span>. Account created through <span style="font-weight: bold;">{{ type }}</span>.</p>
+<a href='/auth/user'>See user data</a>
+</br>
+<a href='/auth/logout'>Logout</a>
+{{/user}}
+{{^user}}
+<p>You are not logged in.</p>
+<a href='/auth/login/github'>Login with GitHub</a>
+{{/user}}
+</body>
+</html>

+ 22 - 0
package.json

@@ -0,0 +1,22 @@
+{
+  "name": "musare",
+  "version": "1.0.0",
+  "description": "Musare.",
+  "main": "server.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "author": "Musare",
+  "license": "ISC",
+  "dependencies": {
+    "consolidate": "^0.14.1",
+    "express": "^4.14.0",
+    "express-session": "^1.14.0",
+    "mustache": "^2.2.1",
+    "node-sass": "^3.8.0",
+    "passport": "^0.3.2",
+    "passport-github": "^1.1.0",
+    "rethinkdb": "^2.3.2",
+    "rethinkdb-init": "^0.2.2"
+  }
+}

+ 18 - 0
server/auth/auth-controller.js

@@ -0,0 +1,18 @@
+var authController = {};
+authController.getUser = function (req, res) {
+    if (req.user && req.user.id) {
+        res.json(req.user);
+        return;
+    }
+    res.status(400).json(null);
+};
+authController.logout = function (req, res) {
+    req.logout();
+    res.redirect('/');
+};
+
+authController.login = function (req, res) {
+    res.redirect('/');
+};
+
+module.exports = authController;

+ 23 - 0
server/auth/auth-router.js

@@ -0,0 +1,23 @@
+var express = require('express');
+var authControllers = require('./auth-controller');
+
+var auth = require('./index');
+var authRouter = express.Router();
+
+// GitHub
+authRouter.use('/login/callback/github', auth.authenticate('github'), function (req, res) {
+    res.redirect('/');
+});
+authRouter.get('/login/github', auth.authenticate('github'));
+
+// Twitter
+authRouter.use('/login/callback/twitter', auth.authenticate('twitter'), function (req, res) {
+    res.redirect('/');
+});
+authRouter.get('/login/twitter', auth.authenticate('twitter'));
+
+// All
+authRouter.use('/user', authControllers.getUser);
+authRouter.use('/logout', authControllers.logout);
+
+module.exports = authRouter;

+ 78 - 0
server/auth/index.js

@@ -0,0 +1,78 @@
+var passport = require('passport');
+var GitHubStrategy = require('passport-github').Strategy;
+var r = require('../db');
+
+passport.serializeUser(function (user, done) {
+    return done(null, user.id);
+});
+
+passport.deserializeUser(function (id, done) {
+    r
+        .table('users')
+        .get(id)
+        .run(r.conn)
+        .then(function (user) {
+            done(null, user);
+        });
+});
+
+var loginCallbackHandler = function (objectMapper, type) {
+    return function (accessToken, refreshToken, profile, done) {
+        if (accessToken !== null) {
+            r
+                .table('users')
+                .getAll(profile.username, { index: 'login' })
+                .filter({ type: type })
+                .run(r.conn)
+                .then(function (cursor) {
+                    return cursor.toArray()
+                        .then(function (users) {
+                            if (users.length > 0) {
+                                return done(null, users[0]);
+                            }
+                            return r.table('users')
+                                .insert(objectMapper(profile))
+                                .run(r.conn)
+                                .then(function (response) {
+                                    return r.table('users')
+                                        .get(response.generated_keys[0])
+                                        .run(r.conn);
+                                })
+                                .then(function (newUser) {
+                                    done(null, newUser);
+                                });
+                        });
+                })
+                .catch(function (err) {
+                    console.log('Error Getting User', err);
+                });
+        }
+    };
+};
+var callbackURL = 'http://127.0.0.1:3000/auth/login/callback';
+
+// Github
+passport.use(new GitHubStrategy({
+        clientID: "c5516f218aa8682ac67d",
+        clientSecret: "5a3ee482ab2eb4ade56ab6ea01fd7544dd9a9be9",
+        callbackURL: callbackURL + '/github'
+    },
+    loginCallbackHandler(function (profile) {
+        return {
+            'login': profile.username,
+            'name': profile.displayName || null,
+            'url': profile.profileUrl,
+            'avatarUrl': profile._json.avatar_url,
+            'type': 'github'
+        };
+    }, 'github')
+));
+
+passport.checkIfLoggedIn = function (req, res, next) {
+    if (req.user) {
+        return next();
+    }
+    return res.status(401).send('You\'re not logged in');
+};
+
+module.exports = passport;

+ 24 - 0
server/db/index.js

@@ -0,0 +1,24 @@
+var r = require('rethinkdb');
+require('rethinkdb-init')(r);
+
+r.connections = [];
+r.getNewConnection = function () {
+    return r.connect({host: 'localhost', port: 28015, db: 'musare'}).then(function (conn) {
+        conn.use("musare");
+        r.connections.push(conn);
+        return conn;
+    });
+};
+
+r.init({host: 'localhost', port: 28015, db: 'musare'}, [
+    {
+        name: 'users',
+        indexes: ['login']
+    }
+]).then(function (conn) {
+    r.conn = conn;
+    r.connections.push(conn);
+    r.conn.use("musare");
+});
+
+module.exports = r;

+ 3 - 0
server/global.js

@@ -0,0 +1,3 @@
+/**
+ * Created by KrisVos130 on 28/07/2016.
+ */

+ 0 - 0
server/routes.js


+ 60 - 0
server/server.js

@@ -0,0 +1,60 @@
+/*var express = require('express');
+var app = express();
+
+app.get('/', function (req, res) {
+    res.sendFile('client/html/index.html', {root: "./"})
+});
+
+app.use(express.static('static'));
+
+app.listen(3000, function () {
+    console.log('Example app listening on port 3000!');
+});*/
+
+
+
+/* Database stuff
+    var r = require('rethinkdb');
+    var connection = null;
+    r.connect( {host: 'localhost', port: 28015, db: "musare"}, function(err, conn) {
+        if (err) throw err;
+        connection = conn;
+    });
+*/
+
+var express = require('express');
+var session = require('express-session');
+var engines = require('consolidate');
+
+var app = express();
+var auth = require('./auth');
+var authRouter = require('./auth/auth-router');
+
+// Middleware
+app
+    .use(session({
+        secret: 'thisisoursecretcode',
+        resave: false,
+        saveUninitialized: true
+    }))
+    .use(auth.initialize())
+    .use(auth.session());
+
+// Views
+app
+    .set('views', './client/html')
+    .engine('html', engines.mustache)
+    .set('view engine', 'html');
+
+// Routes
+app
+    .use('/auth', authRouter)
+    .get('/', function (req, res) {
+        res.render('index.html', { user: req.user });
+    })
+    .use(express.static(__dirname + '../static'))
+    .use('*', function (req, res) {
+        res.status(404).send('404 Not Found').end();
+    });
+
+app.listen(3000);

+ 1 - 0
static/test.txt

@@ -0,0 +1 @@
+Hey!