-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.mjs
271 lines (237 loc) · 6.98 KB
/
app.mjs
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
import express from 'express'
import path from 'path'
import { fileURLToPath } from 'url';
import './db.mjs';
import mongoose, { isObjectIdOrHexString } from 'mongoose';
import session from 'express-session';
import bcrypt from 'bcryptjs'
import passport from 'passport';
import flash from 'express-flash'
import hbs from 'hbs'
import { Strategy as LocalStrategy} from 'passport-local'
import * as apis from './apis.mjs'
import { Server } from 'socket.io'
import { createServer } from "http";
import "dotenv/config.js"
const Events = mongoose.model('Entire');
const myWebsite = new Events();
const bouts = mongoose.model("bouts");
const massive = new bouts();
const areLive = mongoose.model("liveFight");
const we = new areLive();
const User = mongoose.model('User')
const UserInstance = new User();
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.set('view engine','hbs');
app.use(express.static(path.join(__dirname,"public")));
app.use(express.urlencoded({extended: false}));
app.use(flash())
app.use(session({
secret : process.env.APIKEY,
resave: false,
saveUninitialized: false
}))
app.use(express.json());
app.use(passport.initialize())
app.use(passport.session())
passport.serializeUser(function(user,done) {
done(null,user.id);
})
passport.deserializeUser(function(id,done){
User.findById(id, function(err,user){
done(err,user);
});
});
passport.use(new LocalStrategy(function(username,password,done){
User.findOne({username: username}, function(err, user){
if (err){
return done(err);
}
if (!user){
return done(null,false, {message: 'Incorrect username.'});
}
bcrypt.compare(password, user.password, function (err,res){
if (err) return done(err);
if (res===false){
return done(null,false,{message: 'Incorrect password.'});
}
return done(null,user);
})
})
}))
app.use(function(req, res, next) {
if (!req.user)
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
next();
});
function isLoggedIn(req,res,next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
function isLoggedOut(req,res,next) {
if (req.isAuthenticated()) res.redirect('/');
next();
}
app.get("/",isLoggedIn,(req,res)=>{
res.render("index", {hello: "SUP"});
})
app.get("/Home",isLoggedIn,async function(req,res){
let event = await Events.find({})
let user = await User.find({email: req.user.email})
let FinUser = user.map((users)=>{
let container = {};
container["username"]=req.user.username
container["list"]=users.Fights;
return container;
});
let liveList = []
for (let i =0;i<FinUser[0].list.length;i++){
let temp = await bouts.find({FightId : FinUser[0].list[i]})
let obj = {"F1": temp[0].Fighter1, "F2": temp[0].Fighter2, "Order": temp[0].Order, "FID": temp[0].FightId};
liveList.push(obj);
}
FinUser["display"] = liveList
let FinEnv = event.map((events)=>{
let container = {};
container["EventId"]=events.EventId
container["list"]=events.Name
return container;
});
res.render('index', {FinUser: FinUser, FinEnv: FinEnv});
})
app.post("/Home",isLoggedIn,async function(req,res){
var string = encodeURIComponent(req.body.custId);
res.redirect('/fights?valid=' + string);
})
app.post("/Remove", isLoggedIn, async function(req,res){
let discard = req.body.FightsToDiscard;
if (typeof discard ==='string' || discard instanceof String){
discard = [discard];
}
if (discard===undefined || discard===null || discard ===""){
}else {
for (let i = 0;i<discard.length;i++){
await User.updateOne({username : req.user.username},{$pull: {Fights: discard[i]}});
let print = await User.find({username : req.user.username})
}
}
res.redirect('/Home')
})
app.get('/fights',isLoggedIn, async function(req, res){
let bread = await Events.find({EventId: req.query.valid});
let fightlist = bread[0].bouts
let showList = [];
for (let i =0;i<fightlist.length;i++){
let fight = await bouts.find({FightId: fightlist[i]})
let obj = {"F1": fight[0].Fighter1, "F2": fight[0].Fighter2, "Order": fight[0].Order, "FID": fight[0].FightId}
showList.push(obj);
}
showList.sort((a,b) => a.Order - b.Order);
let userList = await User.find({username: req.user.username});
let storedFights = userList[0].Fights;
showList = showList.filter((user)=>{
if (storedFights.includes(user.FID)){
return false;
}
return true;
});
res.render("damnit",{showList,showList});
})
app.post('/fights',isLoggedIn,async function(req,res){
let fightsToAdd = Object.values(req.body);
for (let i =0;i<fightsToAdd.length;i++){
await User.updateOne({username: req.user.username},{$push: {Fights :fightsToAdd[i]}});
}
res.redirect('/Home');
})
app.get('/login',isLoggedOut,(req, res)=>{
res.render("login")
})
app.post('/login',passport.authenticate('local',{
successRedirect: '/Home',
failureRedirect: '/login?error=true'
}));
app.get('/login?error=true', function(req,res){
res.render("login");
})
app.get('/logout', function (req,res){
req.logOut();
res.redirect('/');
})
app.get('/register', isLoggedOut,function(req,res){
res.render('register')
})
app.post('/register', isLoggedOut,async (req,res)=>{
try {
const exists = await User.exists({username: req.body.username});
if (exists){
res.redirect('/login');
return;
}
} catch (e) {
}
bcrypt.genSalt(10, function (err,salt){
if (err) return next(err);
bcrypt.hash(req.body.password, salt, function(err, hash){
if (err) return next(err)
const newAdmin = new User({
username: req.body.username,
password: hash,
email: req.body.password
})
newAdmin.save(function(err,doc){
if (err){
console.log("something went wrong");
}else{
console.log("All good");
}
});
res.redirect('/login');
})
})
})
app.post('/logout', function(req, res, next){
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/login');
});
});
const httpServer = createServer(app);
const io = new Server(httpServer);
io.on('connection', function(socket){
socket.on('UpdateOnDatabase', function(msg){
socket.broadcast.emit('RefreshPage');
});
});
let endpoint = ["Schedule/UFC/2022","Schedule/UFC/2023"]
setTimeout(()=>{
apis.getData(endpoint[0]);
},10)
setTimeout(()=>{
apis.getData(endpoint[1]);
},5000)
setInterval(()=>{
apis.getData(endpoint[0]);
apis.getData(endpoint[1]);
io.on('connection', function(socket){
socket.emit('UpdateOnDatabase');
});
}, 302400000) // 3.5 day intervals
function FightTime(){
}
async function normal(){
let nextFight = await areLive.find({});
const date = new Date().toLocaleString('en-US', {
timeZone: 'America/Los_Angeles',
hour12: false,
});
apis.change(date);
if (nextFight.DateTime>date){
setTimeOut(normal,30000);
}else{
setTimout(FightTime());
}
}
app.listen(process.env.PORT || 3000);