-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
87 lines (76 loc) · 2.59 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const session = require('express-session');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const redisClient = redis.createClient();
const passport = require('passport');
const GithubStrategy = require('passport-github2').Strategy;
const config = require('./config');
const appController = require('./controllers/app/appController');
app.use(session({
secret: config.sessionSecret || 'Frase muy secreta',
store: new redisStore({
host: config.redis.host,
port: config.redis.port,
client: redisClient,
ttl: 260
}),
saveUninitialized: false,
resave: false,
cookie: {
httpOnly: true,
maxAge: 7*60*24*3600*1000
}
}));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser((function(obj, done) {
done(null, obj);
}));
passport.use(new GithubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL
}, (accessToken, refreshToken, profile, done) => {
appController.logUser(profile, done);
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.use(passport.initialize());
app.use(passport.session());
if (config.morgan.user) {
app.use(config.morgan.log);
}
const allowCrossDomain = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Accept, Content-Type, X-Access-Token, Cache-Control, Pragma');
next();
};
app.use(allowCrossDomain);
app.get('/', (req, res) => {
res.status(200).send(req.user);
});
app.get('/auth/github', passport.authenticate('github'), (req, res) => {
res.status(200).json(req.user);
});
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/' }), (req, res) => {
console.log(req.user);
res.status(200).json(req.user);
});
app.listen(config.port, (err) => {
if (err) throw new Error(err.message);
console.log(`Server is up and running on port: ${config.port}`);
mongoose.connect(config.mongo.host + ':' + config.mongo.port + '/' + config.mongo.db, (err) => {
if (err) throw new Error(err.message);
console.log('Connected to the database: ' + config.mongo.host + ':' + config.mongo.port + '/' + config.mongo.db);
mongoose.Promise = require('bluebird');
});
});