-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
280 lines (218 loc) · 6.51 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
require('dotenv').config()
const express = require('express');
const ejs = require('ejs');
const mongoose = require('mongoose');
const https = require("https");
const bodyParser = require('body-parser');
const path = require('path');
const e = require('express');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy
const app = express()
const session = require("express-session");
const passport = require("passport");
const passpostLocalMongoose = require('passport-local-mongoose');
const findOrCreate = require('mongoose-findorcreate')
// uses and set
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
app.use(session({
secret: "Out little secret.",
resave: false,
saveUninitialized: false
}));
var userProfile;
app.use(passport.initialize());
app.use(passport.session());
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb+srv://admin-shivam:[email protected]/Blogs');
}
// defining the schema for user who sign up
const userSchema = new mongoose.Schema({
googleId: String,
facebookId: String,
secret: String
});
// creating a model for user schema
const User = new mongoose.model('User', userSchema);
// plugins for userscheama
userSchema.plugin(passpostLocalMongoose);
userSchema.plugin(findOrCreate);
// defining a schema for blogs upload
const blogSchema = new mongoose.Schema({
title: String,
author: String,
post: String,
});
// creating a model for blog schema
const Blog = new mongoose.model('Blog', blogSchema);
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// sign up with google aurhenciation
passport.use(new GoogleStrategy({
clientID:process.env.GOOGLE_CLIENT_ID,
clientSecret:process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:8080/auth/google/iBlog-website",
passReqToCallback:true
},
function(request, accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
// sign up with facebook authenciation
passport.use(new FacebookStrategy({
clientID: process.env.Facebook_CLIENT_ID, // getting Facebook_CLIENT_ID from .env file
clientSecret: process.env.Facebook_CLIENT_SECRET, //getting Facebook_CLIENT_ID from .env file
callbackURL: "http://localhost:8080/auth/facebook/iBlog-website" // callback url
},
function(accessToken, refreshToken, profile, done) {
//check user table for anyone with a facebook ID of profile.id
User.findOne({
'facebook.id': profile.id
}, function(err, user) {
if (err) {
return done(err);
}
//No user was found... so create a new user with values from Facebook (all the profile. stuff)
if (!user) {
user = new User({
provider: 'facebook',
//now in the future searching on User.findOne({'facebook.id': profile.id } will match because of this next line
facebook: profile._json
});
user.save(function(err) {
if (err) console.log(err);
return done(err, user);
});
} else {
//found user Return
return done(err, user);
}
});
}
));
// root route of app
app.get("/", (req, res) => {
Blog.find((err,results)=>{
if(err){
console.log(err);
}
else{
res.render("index",{posts: results});
}
})
});
app.get("/signup", (req,res)=>{
res.render("login");
});
app.get("/blogs", (req, res) => {
Blog.find((err,results)=>{
if(err){
console.log(err);
}
else{
res.render("blogFeed",{posts: results});
}
})
});
app.get("/contact", (req, res) => {
res.render("contact");
});
app.get("/create", (req, res) => {
if (req.isAuthenticated()) {
res.render("compose"); // render the secrets page
} else {
res.redirect("signup"); // redirect to login route
};
});
app.post("/create", (req, res) => {
postTitle = req.body.postTitle;
postAuthor = req.body.authorName;
postBody = req.body.postBody;
var blog = new Blog({
title: postTitle,
author: postAuthor,
post: postBody
})
blog.save(function(err,result){
if (err){
console.log(err);
}
else{
// console.log(result);
}
})
res.redirect("/")
});
app.get("/posts/:postId",(req,res)=>{
const _id = req.params.postId.trim();
Blog.findById(_id, (err,blogs)=>{
if(err){
console.log(err);
}
else{
res.render("blog",{
title: blogs.title,
author: blogs.author,
content: blogs.post,
id: _id
});
}
})
})
app.get("/delete/:id",(req,res)=>{
const _id = req.params.id.trim();
if(req.isAuthenticated()){
Blog.findByIdAndDelete(_id,(err,result)=>{
if(err){
console.log(err)
}
else{
res.redirect("/")
}
})
}
else{
res.send("<h1>You don't have permission to delete the article</h1>")
}
});
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile','email'] }));
app.get('/auth/google/iBlog-website',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
// authenticate the user from facebook
app.get('/auth/facebook',
passport.authenticate('facebook'));
// authenticate the user from facebook with callback
app.get('/auth/facebook/iBlog-website',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect to Secrets page.
res.redirect('/'); // redirect to secrets page
});
app.get('/logout', function(req, res, next) {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
app.listen(process.env.PORT || 8080, () => {
console.log("Sever is listening at port 8080");
})