-
Notifications
You must be signed in to change notification settings - Fork 41
/
app.js
248 lines (218 loc) · 7.71 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
//dependencies for each module used
var express = require('express');
var passport = require('passport');
var InstagramStrategy = require('passport-instagram').Strategy;
var http = require('http');
var path = require('path');
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var dotenv = require('dotenv');
var mongoose = require('mongoose');
var Instagram = require('instagram-node-lib');
var async = require('async');
var app = express();
//local dependencies
var models = require('./models');
//client id and client secret here, taken from .env
dotenv.load();
var INSTAGRAM_CLIENT_ID = process.env.INSTAGRAM_CLIENT_ID;
var INSTAGRAM_CLIENT_SECRET = process.env.INSTAGRAM_CLIENT_SECRET;
var INSTAGRAM_CALLBACK_URL = process.env.INSTAGRAM_CALLBACK_URL;
Instagram.set('client_id', INSTAGRAM_CLIENT_ID);
Instagram.set('client_secret', INSTAGRAM_CLIENT_SECRET);
//connect to database
mongoose.connect(process.env.MONGODB_CONNECTION_URL);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("Database connected succesfully.");
});
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing. However, since this example does not
// have a database of user records, the complete Instagram profile is
// serialized and deserialized.
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
// Use the InstagramStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, an accessToken, refreshToken, and Instagram
// profile), and invoke a callback with a user object.
passport.use(new InstagramStrategy({
clientID: INSTAGRAM_CLIENT_ID,
clientSecret: INSTAGRAM_CLIENT_SECRET,
callbackURL: INSTAGRAM_CALLBACK_URL
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
models.User.findOne({
"ig_id": profile.id
}, function(err, user) {
if (err) {
return done(err);
}
//didnt find a user
if (!user) {
newUser = new models.User({
name: profile.username,
ig_id: profile.id,
ig_access_token: accessToken
});
newUser.save(function(err) {
if(err) {
console.log(err);
} else {
console.log('user: ' + newUser.name + " created.");
}
return done(null, newUser);
});
} else {
//update user here
user.ig_access_token = accessToken;
user.save();
process.nextTick(function () {
// To keep the example simple, the user's Instagram profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the Instagram account with a user record in your database,
// and return that user instead.
return done(null, user);
});
}
});
}
));
//Configures the Template engine
app.engine('handlebars', handlebars({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat',
saveUninitialized: true,
resave: true}));
app.use(passport.initialize());
app.use(passport.session());
//set environment ports and start application
app.set('port', process.env.PORT || 3000);
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
function ensureAuthenticatedInstagram(req, res, next) {
if (req.isAuthenticated() && !!req.user.ig_id) {
return next();
}
res.redirect('/login');
}
//routes
app.get('/', function(req, res){
res.render('login');
});
app.get('/login', function(req, res){
res.render('login', { user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', {user: req.user});
});
app.get('/igphotos', ensureAuthenticatedInstagram, function(req, res){
var query = models.User.where({ ig_id: req.user.ig_id });
query.findOne(function (err, user) {
if (err) return err;
if (user) {
// doc may be null if no document matched
Instagram.users.liked_by_self({
access_token: user.ig_access_token,
complete: function(data) {
console.log(data);
//Map will iterate through the returned data obj
var imageArr = data.map(function(item) {
//create temporary json object
tempJSON = {};
tempJSON.url = item.images.low_resolution.url;
//insert json object into image array
return tempJSON;
});
res.render('photos', {photos: imageArr});
}
});
}
});
});
app.get('/igMediaCounts', ensureAuthenticatedInstagram, function(req, res){
var query = models.User.where({ ig_id: req.user.ig_id });
query.findOne(function (err, user) {
if (err) return err;
if (user) {
Instagram.users.follows({
user_id: user.ig_id,
access_token: user.ig_access_token,
complete: function(data) {
// an array of asynchronous functions
var asyncTasks = [];
var mediaCounts = [];
data.forEach(function(item){
asyncTasks.push(function(callback){
// asynchronous function!
Instagram.users.info({
user_id: item.id,
access_token: user.ig_access_token,
complete: function(data) {
mediaCounts.push(data);
callback();
}
});
});
});
// Now we have an array of functions, each containing an async task
// Execute all async tasks in the asyncTasks array
async.parallel(asyncTasks, function(err){
// All tasks are done now
if (err) return err;
return res.json({users: mediaCounts});
});
}
});
}
});
});
app.get('/visualization', ensureAuthenticatedInstagram, function (req, res){
res.render('visualization');
});
app.get('/c3visualization', ensureAuthenticatedInstagram, function (req, res){
res.render('c3visualization');
});
app.get('/auth/instagram',
passport.authenticate('instagram'),
function(req, res){
// The request will be redirected to Instagram for authentication, so this
// function will not be called.
});
app.get('/auth/instagram/callback',
passport.authenticate('instagram', { failureRedirect: '/login'}),
function(req, res) {
res.redirect('/account');
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});