1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-11-10 23:53:31 -05:00
shimapan/app/routes/auth.js

81 lines
2.6 KiB
JavaScript
Raw Normal View History

2017-10-11 10:15:19 -04:00
var fs = require('fs');
var path = require('path');
var express = require('express');
var router = express.Router();
2017-10-11 12:55:46 -04:00
var User = require('../models/User.js');
var Invite = require('../models/Invite.js');
2017-10-11 10:15:19 -04:00
var passport = require('passport');
2017-10-12 12:50:02 -04:00
function checkInvite(code, callback) {
2017-10-14 17:49:11 -04:00
Invite.findOne({code: code}, function (err, invite) {
2017-10-11 12:55:46 -04:00
if (err) return callback(err);
2017-10-12 12:50:02 -04:00
if (!invite || invite.used || invite.exp < new Date())
callback(null, false);
else
2017-10-11 12:55:46 -04:00
callback(null, true, invite);
2017-10-12 12:50:02 -04:00
});
}
function useInvite(code, username) {
2017-10-18 13:31:08 -04:00
Invite.updateOne({code: code}, {recipient: username, used: new Date()}, function (err) {
2017-10-12 12:50:02 -04:00
if (err) throw err;
});
2017-10-11 12:55:46 -04:00
}
2017-10-18 13:31:08 -04:00
router.post('/register', function (req, res, next) {
// Validate the invite code, then hand off to passport
checkInvite(req.body.invite, function (err, valid, invite) {
if (valid) {
User.register(
new User({username: req.body.username, scope: invite.scope, date: Date.now()}),
req.body.password,
function (err) {
if (err) return res.status(403).json({'message': err.message});
passport.authenticate('local')(req, res, function () {
req.session.save(function(err) {
if (err) return next(err);
useInvite(req.body.invite, req.body.username);
res.status(200).json({'message': 'Registered.'});
});
});
2017-10-14 17:49:11 -04:00
}
2017-10-18 13:31:08 -04:00
);
} else {
res.status(401).json({'message': 'Invalid invite code.'});
2017-10-12 12:50:02 -04:00
}
2017-10-11 12:55:46 -04:00
});
2017-10-11 10:15:19 -04:00
});
2017-10-18 13:31:08 -04:00
router.post('/login', function (req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) return res.status(401).json({'message': info});
req.logIn(user, function(err) {
if (err) return next(err);
res.status(200).json({'message': 'Logged in.'});
});
})(req, res, next);
2017-10-11 10:15:19 -04:00
});
2017-10-18 13:31:08 -04:00
router.get('/logout', function (req, res) {
req.logout();
res.status(200).json({'message': 'Logged out.'});
2017-10-14 17:49:11 -04:00
});
2017-10-18 13:31:08 -04:00
router.get('/session', function(req, res) {
if (req.session.passport.user) {
User.findOne({username: req.session.passport.user}, function(err, user) {
res.status(200).json({
user: user.username,
scope: user.scope
});
});
} else {
res.status(401).json({'message': 'Unauthorized.'});
}
});
2017-10-11 10:15:19 -04:00
module.exports = router;