forked from jacobecox/Gym-Guru-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
182 lines (156 loc) · 5.51 KB
/
server.js
File metadata and controls
182 lines (156 loc) · 5.51 KB
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
// Dependencies
import express from 'express';
import mongoose from 'mongoose';
import MongoStore from "connect-mongo";
import cors from 'cors';
import passport from 'passport';
import keys from './src/app/config/keys.js'
import User from './src/app/models/user.js';
import session from "express-session";
import GoogleStrategy from 'passport-google-oauth20';
import config from './config.js';
import './src/app/services/passport.js';
// Routes
import Authentication from "./src/app/controllers/authentication.js"
import getAPICategories from './src/app/routes/getAPICategories.js'
import getAllAPIExercises from './src/app/routes/getAPIAllExercises.js'
import getCategories from './src/app/routes/getCategories.js'
import getAllExercises from './src/app/routes/getAllExercises.js'
import postSavedExercises from './src/app/routes/postSavedExercises.js'
import deleteSavedExercises from './src/app/routes/deleteSavedExercises.js'
import getSavedExercises from './src/app/routes/getSavedExercises.js'
import getWorkoutDays from './src/app/routes/getWorkoutDays.js'
import postWorkoutExercise from './src/app/routes/postWorkoutExercise.js'
import deleteWorkoutExercise from './src/app/routes/deleteWorkoutExercise.js'
import deleteWorkoutDay from './src/app/routes/deleteWorkoutDay.js'
const app = express();
app.use(express.json());
const GOOGLE_CLIENT_SECRET = config.GOOGLE_CLIENT_SECRET;
const GOOGLE_CLIENT_ID = config.GOOGLE_CLIENT_ID;
const BASE_URL = config.BASE_URL
const FRONTEND_URL = config.FRONTEND_URL
const MONGO_URI = config.MONGO_URI
const allowedOrigins = [
'http://localhost:3000', // Local development
FRONTEND_URL // Production frontend
];
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true // Allows cookies and auth headers
}));
// Storing sessions inside db used
app.use(
session({
secret: "passkeysecret",
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: MONGO_URI,
collectionName: "sessions",
})
})
);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
// Google Oauth functionality. We send client details through link which reroutes user to Google to login. Google returns via callback route with user's data
passport.use(
"google",
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: `${BASE_URL}/auth/google/callback`,
},
async (accessToken, refreshToken, profile, done) => {
try {
// Check if the user already exists
const existingUser = await User.findOne({ googleId: profile.id });
if (existingUser) {
return done(null, existingUser);
}
// Create new user with google id if one doesn't exist
const newUser = await new User({
googleId: profile.id,
username: profile.displayName,
email: profile.emails[0].value,
}).save();
return done(null, newUser);
} catch (err) {
return done(err, null);
}
}
)
);
const googleAuth = passport.authenticate("google", {
scope: ["profile", "email"] })
// Handles when google send user back with data. We store user data with token in url params to be sent back when redirected to our success page
const handleAuthRedirect = async (req, res) => {
if (req.isAuthenticated() && req.user) {
try {
const token = await Authentication.userToken(req.user); // ✅ Await the token properly
res.redirect(`${FRONTEND_URL}/pages/login-success?token=${encodeURIComponent(token)}`);
} catch (error) {
console.error("Error generating token:", error);
res.redirect(`${FRONTEND_URL}/pages/login?error=token_generation_failed`);
}
} else {
console.error("User not authenticated");
res.redirect(`${FRONTEND_URL}/pages/login?error=auth_failed`);
}
};
const requireAuth = passport.authenticate('jwt');
const requireLogin = passport.authenticate('local');
const keySet = await keys();
mongoose
.connect(keySet.MONGO_URI)
.then(() => {
console.log('🚀 DB Connected!');
if (process.env.NODE_ENV !== "test") { // Prevent server from starting in test mode
const port = process.env.PORT || 8080;
console.log('port:', port)
console.log('mongo URI:', keySet.MONGO_URI)
app.listen(port, () => {
console.log('😎 Server listening on PORT', port);
});
}
})
.catch((err) => {
console.log(`❌ DB Connection Error: ${err.message}`);
});
// Non-login required routes
app.use('/api', getAPICategories)
app.use('/api', getAllAPIExercises)
app.use(getCategories)
app.use(getAllExercises)
app.use(getWorkoutDays)
app.use(postWorkoutExercise)
app.use(deleteWorkoutExercise)
app.use(deleteWorkoutDay)
// Login required routes
app.post('/auth/login', requireLogin, Authentication.login);
app.post('/auth/create-account', Authentication.createAccount);
app.get('/auth/current-user', requireAuth, Authentication.currentUser);
app.use(postSavedExercises);
app.use(deleteSavedExercises);
app.use(getSavedExercises);
// Google login and logout routes
app.get("/auth/google", googleAuth);
app.get("/auth/google/callback", googleAuth, handleAuthRedirect)
export default app;