Skip to content

Commit

Permalink
Hooking up user login and restricting API
Browse files Browse the repository at this point in the history
  • Loading branch information
snowyfox committed Aug 5, 2017
1 parent 12eddc7 commit 2e94a38
Show file tree
Hide file tree
Showing 32 changed files with 1,141 additions and 416 deletions.
767 changes: 418 additions & 349 deletions .idea/workspace.xml

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const auth = require("./auth.js");
console.log("ENV: " + process.env.NODE_ENV);

const app = express();
Expand All @@ -22,8 +22,13 @@ app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(auth.initialize());

app.use('/api/v1', apiV1);
app.use('/api/v1', auth.authenticateJwt(), apiV1);
app.post('/login', auth.authenticateUser(), auth.createToken, function(req, res){
"use strict";
res.send({ user: req.user, token: req.token});
});
app.use('/', express.static(path.join(__dirname, 'www')));

// catch 404 and forward to error handler
Expand Down
104 changes: 104 additions & 0 deletions auth.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,106 @@


const config = require("./config");

const passport = require('passport');
const ExtractJwt = require('passport-jwt').ExtractJwt;
const JwtStrategy = require('passport-jwt').Strategy;
const LocalStrategy = require('passport-local').Strategy;
const jwt = require('jsonwebtoken');
const jwtOptions = {};
const models = require('./models/index');
const crypto = require('crypto');
const userDatabase = config.databases.forum;

jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();
jwtOptions.secretOrKey = config.jwtKey;
jwtOptions.issuer = 'naranawm.org';

passport.use(new JwtStrategy(jwtOptions, function(jwt_payload, done){
"use strict";
console.log(jwt_payload);
// Just returning a basic user for now TODO: build this out
return done(null, { id: 1 });
}));

// Todo: Move this into an extensions section so others can override
passport.use("learnNaviForum", new LocalStrategy(function(username, password, done){
"use strict";
if(username === undefined || password === undefined || username === "" || password === ""){
return done(null, false, { message: "Incorrect Username / Password" });
}

models.sequelize.query(`SELECT ${userDatabase.database}.${userDatabase.table}.id_member, member_name, passwd, real_name, filename FROM ${userDatabase.database}.${userDatabase.table} LEFT JOIN ${userDatabase.database}.${userDatabase.attachmentTable} ON ${userDatabase.database}.${userDatabase.table}.id_member = ${userDatabase.database}.${userDatabase.attachmentTable}.id_member WHERE member_name = :username`, {
type: models.sequelize.QueryTypes.SELECT,
replacements: {
username: username
}
}).then(results => {
"use strict";
if(results !== null && results.length === 1){
const hash = crypto.createHash("sha1");
hash.update(results[0].member_name + password);
const passwordHash = hash.digest("hex");
if(passwordHash === results[0].passwd){
// Successful Login!!!
return done(null, {
id: results[0].id_member,
name: results[0].real_name,
username: results[0].member_name,
avatar: "https://forum.learnnavi.org/avs/" + results[0].filename,
provider: "https://forum.learnnavi.org"
});
}
}
return done(null, false, { message: "Incorrect Username / Password" });
});
}));

// Used for local testing. TODO: Remove this once other authentication strategies are fully functional
passport.use("localTest", new LocalStrategy(function(username, password, done){
"use strict";
if(username === undefined || password === undefined || username === "" || password === ""){
return done(null, false, { message: "Incorrect Username / Password" });
}

if(username === "test" && password === "test"){
return done(null, {
id: 0,
name: "Test User",
username: username,
provider: "https://naranawm.org"
});
}

return done(null, false, { message: "Incorrect Username / Password" });

}));

module.exports = {
initialize: function(){
return passport.initialize();
},
authenticateJwt: function () {
return passport.authenticate("jwt", { session: false});
},
authenticateUser: function() {
"use strict";
return passport.authenticate(["localTest", "learnNaviForum"], { session: false});
},
createToken: function(req, res, next){
"use strict";
const payload = {
id: req.user.id,
name: req.user.name,
username: req.user.username,
avatar: req.user.avatar,
provider: req.user.provider
};
console.log(payload);
req.token = jwt.sign(payload, config.jwtKey, {
expiresIn: "1d",
issuer: "naranawm.org"
});
next();
}
};
2 changes: 1 addition & 1 deletion bin/rebuild
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const config = require("../config");
const debug = require('debug')('Naranawm:rebuild');

const Dictionary = require('../eanaEltuMigration/dictionary');
const dictionary = new Dictionary(config);
const dictionary = new Dictionary(debug);

debug("Starting Database Rebuild");
dictionary.buildDictionary(function(){
Expand Down
Binary file modified config/kenten.vault.js
Binary file not shown.
7 changes: 5 additions & 2 deletions config/local.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,17 @@ module.exports = {
},
forum: {
database: "learnnavi_forum",
table: "smf_members"
table: "smf_members",
attachmentTable: "smf_attachments"
},
sqlite: {
host: "127.0.0.1",
dialect: "sqlite",
benchmark: false,
logging: false
}
}
},

jwtKey: "arocxg9e8xgh;rchukuthhaetubmapx9i9xcgeu09k"

};
4 changes: 2 additions & 2 deletions eanaEltuMigration/dictionary.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ const Lemma = require('./lemma');
const EanaEltu = require('./eanaEltu');
const models = require('../models');
const Promise = require('bluebird');
const debug = require('debug')('Naranawm:server');
const debug = require('debug')('Naranawm:rebuild');

/*
* This Module / Section is to export data from Eana Eltu
* and convert it into a format that we can insert into
* the new database schema */

function Dictionary (config) {
function Dictionary () {
this.eanaEltu = new EanaEltu();
this.languages = {
en: {
Expand Down
104 changes: 98 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"express": "~4.15.2",
"jsonwebtoken": "^7.4.2",
"morgan": "^1.8.2",
"mysql": "^2.14.0",
"mysql2": "^1.3.6",
"passport": "^0.3.2",
"passport-jwt": "^2.2.1",
"passport-local": "^1.0.0",
"passport-localapikey": "0.0.3",
"pug": "~2.0.0-beta11",
"sequelize": "^4.4.2",
Expand Down
1 change: 1 addition & 0 deletions routes/apiV1.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const router = express.Router();
router.use('/auth', require('./v1/auth'));
router.use('/definitions', require('./v1/definitions'));
router.use('/models', require('./v1/models'));
router.use('/rebuild', require('./v1/rebuild'));
router.use('/export', require('./v1/export'));

module.exports = router;
Loading

0 comments on commit 2e94a38

Please sign in to comment.