-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
193 lines (166 loc) · 4.29 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
require("dotenv").config();
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");
var session = require("express-session");
var mongoose = require("mongoose");
const mailController = require("./controllers/mail.controller");
const User = require("./models/User");
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const { sendResponse, AppError } = require("./helpers/utils");
const cron = require("node-cron");
var app = express();
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(cors());
app.use(
cors({
origin: process.env.DEPLOY_URL,
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);
const mongoURI = process.env.MONGODB_URI;
mongoose
.connect(mongoURI)
.then(() => {
console.log("DB connected successfully");
// Set email tasks schedule
cron.schedule("* * * * *", mailController.notificationMailer);
})
.catch((err) => console.log(err));
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
// Authorized redirect URIs from Google OAuth2 setting
callbackURL: process.env.GOOGLE_CALLBACK_URL,
userProfile: "https://www.googleapis.com/oauth2/v3/userinfo",
},
async (accessToken, refreshToken, profile, cb) => {
try {
const email = profile.emails[0].value;
const name = profile.displayName;
const avatarUrl = profile.picture;
let user = await User.findOne({ email });
if (!user) {
user = await User.create({
email,
name,
avatarUrl,
// googleId: profile.id,
});
}
const jwtAccessToken = await user.generateToken();
user.googleId = profile.id;
await user.save();
return cb(null, { user, accessToken: jwtAccessToken }); // null: no err
} catch (err) {
return cb(err, null);
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((obj, done) => {
done(null, obj);
});
app.use(
session({
secret: process.env.GOOGLE_CLIENT_SECRET,
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
cookie: {
maxAge: 86400000, // 1d
},
})
);
app.use(passport.initialize());
app.use(passport.session());
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"],
})
);
app.get(
"/auth/google/habit-tracker",
passport.authenticate("google", {
failureRedirect: `${process.env.DEPLOY_URL}/login`,
}),
function (req, res) {
// Successful authentication, redirect
res.redirect(`${process.env.DEPLOY_URL}/google-login`);
}
);
// To get data from Google account
app.get("/google-login/success", async (req, res) => {
if (!req.user) {
throw new AppError(400, "Not authorized", "Google Login error");
}
// return data from req.user
return sendResponse(
res,
200,
true,
{
user: req.user.user,
accessToken: req.user.accessToken,
},
null,
"Google Login success"
);
});
app.get("/logout", (req, res, next) => {
// call Passport logout
if (req.user) {
req.session.destroy();
req.logout((err) => {
if (err) {
console.log("err");
return next(err);
}
res.redirect("/");
});
}
});
var indexRouter = require("./routes/index");
app.use("/api", indexRouter);
// Error handlers
// catch error 404
app.use((req, res, next) => {
const err = new Error("Not found");
err.statusCode = 404;
next(err);
});
app.use((err, req, res, next) => {
console.log(err);
if (err.isOperational) {
return sendResponse(
res,
err.statusCode ? err.statusCode : 500,
false,
null,
{ message: err.message },
err.errorType
);
}
return sendResponse(
res,
err.statusCode ? err.statusCode : 500,
false,
null,
{ message: err.message },
"Internal Server Error"
);
});
module.exports = app;