-
Notifications
You must be signed in to change notification settings - Fork 18
/
app.js
193 lines (160 loc) · 5.41 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
require('./models');
var bcrypt = require('bcrypt');
var expressSession = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var dotenv = require('dotenv');
dotenv.config();
var User = mongoose.model('User');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
mongoose.connect('mongodb://' + process.env.MONGO_USERNAME + ":" + process.env.MONGO_PASSWORD + '@localhost:27017/saas-tutorial-db', { useNewUrlParser: true, useUnifiedTopology: true });
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');
// Match the raw body to content type application/json
app.post('/pay-success', bodyParser.raw({type: 'application/json'}), (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, process.env.ENDPOINT_SECRET);
} catch (err) {
return response.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the checkout.session.completed event
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
// Fulfill the purchase...
console.log(session);
User.findOne({
email: session.customer_email
}, function(err, user) {
if (user) {
user.subscriptionActive = true;
user.subscriptionId = session.subscription;
user.customerId = session.customer;
user.save();
}
});
}
// Return a response to acknowledge receipt of the event
response.json({received: true});
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({
secret: process.env.EXPRESS_SESSION_SECRET
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy({
usernameField: "email",
passwordField: "password"
}, function(email, password, next) {
User.findOne({
email: email
}, function(err, user) {
if (err) return next(err);
if (!user || !bcrypt.compareSync(password, user.passwordHash)) {
return next({message: 'Email or password incorrect'})
}
next(null, user);
})
}));
passport.use('signup-local', new LocalStrategy({
usernameField: "email",
passwordField: "password"
}, function(email, password, next) {
User.findOne({
email: email
}, function(err, user) {
if (err) return next(err);
if (user) return next({message: "User already exists"});
let newUser = new User({
email: email,
passwordHash: bcrypt.hashSync(password, 10)
})
newUser.save(function(err) {
next(err, newUser);
});
});
}));
passport.serializeUser(function(user, next) {
next(null, user._id);
});
passport.deserializeUser(function(id, next) {
User.findById(id, function(err, user) {
next(err, user);
});
});
app.get('/', function (req, res, next) {
res.render('index', {title: "SaaS Tutorial"})
});
app.get('/billing', function (req, res, next) {
stripe.checkout.sessions.create({
customer_email: req.user.email,
payment_method_types: ['card'],
subscription_data: {
items: [{
plan: process.env.STRIPE_PLAN,
}],
},
success_url: process.env.BASE_URL + ':3000/billing?session_id={CHECKOUT_SESSION_ID}',
cancel_url: process.env.BASE_URL + ':3000/billing',
}, function(err, session) {
if (err) return next(err);
res.render('billing', {STRIPE_PUBLIC_KEY: process.env.STRIPE_PUBLIC_KEY, sessionId: session.id, subscriptionActive: req.user.subscriptionActive})
});
})
app.get('/logout', function(req, res, next) {
req.logout();
res.redirect('/');
});
app.get('/walkthrough', function(req, res, next) {
req.session.sawWalkthrough = true;
res.end();
})
app.get('/complicated', function (req, res, next) {
console.log(req.session.sawWalkthrough);
})
app.get('/main', function (req, res, next) {
res.render('main')
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login-page' }),
function(req, res) {
res.redirect('/main');
});
app.get('/login-page', function(req, res, next) {
res.render('login-page')
})
app.post('/signup',
passport.authenticate('signup-local', { failureRedirect: '/' }),
function(req, res) {
res.redirect('/main');
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;