warrior-code-api
Version:
API for Warrior-Code.
51 lines (41 loc) • 1.26 kB
JavaScript
;
const config = require('config');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const User = mongoose.models.User;
module.exports = (request, reply) => {
// Ensure that the user is authenticated.
if (!request.auth.isAuthenticated) {
return reply(`Authentication failed due to: ${request.auth.error.message}`);
}
let payload = request.auth.credentials.profile;
let userFilter = {
'github.id': payload.id
};
User.findOne(userFilter).then((err, user) => {
// Check if there is no user created yet.
if (!user) {
// Create a new user.
user = new User({
github: {
id: payload.id,
displayName: payload.displayName,
email: payload.email,
username: payload.username,
}
});
}
// Update the last access time.
user.lastAccess = new Date();
// Return the promise of after saving the user.
return user.save();
}).then((user) => {
// Create the jwt based on the user `_id`.
let payload = { _id: user._id };
let token = jwt.sign(payload, config.get('Secrets.JWT.privateKey'));
// Respond with the JWT.
reply({token: token});
}).catch((err) => {
console.log(err);
});
}