Skip to content

Commit

Permalink
refactor: add typing to client config options
Browse files Browse the repository at this point in the history
  • Loading branch information
TurtIeSocks committed Sep 12, 2023
1 parent a3c10a0 commit addb5f3
Show file tree
Hide file tree
Showing 47 changed files with 479 additions and 507 deletions.
13 changes: 10 additions & 3 deletions packages/types/lib/config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export interface Config<Client extends boolean = false>
excludeFromTutorial: (keyof BaseConfig['authentication']['perms'])[]
alwaysEnabledPerms: (keyof BaseConfig['authentication']['perms'])[]
aliases: { role: string; name: string }[]
methods: string[]
strategies: [
{
trialPeriod: {
Expand Down Expand Up @@ -77,21 +78,27 @@ export interface Config<Client extends boolean = false>
titles: string[]
components: CustomComponent[]
footerButtons: CustomComponent[]
} & BaseConfig['map']['messageOfTheDay']
} & Omit<
BaseConfig['map']['messageOfTheDay'],
'settings' | 'titles' | 'components' | 'footerButtons'
>
donationPage: {
settings: {
parentStyle: Record<string, string> // should be CSS properties but performance seems to die
} & BaseConfig['map']['donationPage']['settings']
titles: string[]
components: CustomComponent[]
footerButtons: CustomComponent[]
} & BaseConfig['map']['donationPage']
} & Omit<
BaseConfig['map']['donationPage'],
'settings' | 'titles' | 'components' | 'footerButtons'
>
loginPage: {
settings: {
parentStyle: Record<string, string> // should be CSS properties but performance seems to die
} & BaseConfig['map']['loginPage']['settings']
components: CustomComponent[]
} & BaseConfig['map']['loginPage']
} & Omit<BaseConfig['map']['loginPage'], 'settings' | 'components'>
} & BaseConfig['map']
multiDomains: (BaseConfig['map'] & { domain: string })[]
multiDomainsObj: Record<string, BaseConfig['map'] & { domain: string }>
Expand Down
1 change: 1 addition & 0 deletions packages/types/lib/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import NestSubmissionModel = require('server/src/models/NestSubmission')
import GymBadgeModel = require('server/src/models/Badge')
import type { FullModel } from './utility'
import type { Permissions } from './server'
import { Strategy } from './general'

export interface Backup {
id: number
Expand Down
2 changes: 1 addition & 1 deletion server/src/graphql/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ async function startApollo(httpServer) {
filterCount || 0,
)

if (returned) {
if (returned && config.getSafe('sentry.server.enabled')) {
contextValue.transaction.setMeasurement(
`${endpoint}.returned`,
returned,
Expand Down
2 changes: 1 addition & 1 deletion server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ passport.deserializeUser(async (user, done) => {
if (user.perms.map) {
done(null, user)
} else {
done(null, false)
done('User does not have map permissions', null)
}
})

Expand Down
192 changes: 33 additions & 159 deletions server/src/routes/rootRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@ const authRouter = require('./authRouter')
const clientRouter = require('./clientRouter')
const { Event, Db } = require('../services/initialization')
const { version } = require('../../../package.json')
const buildDefaultFilters = require('../services/filters/builder/base')
const advMenus = require('../services/ui/advMenus')
const areaPerms = require('../services/functions/areaPerms')
const generateUi = require('../services/ui/primary')
const clientOptions = require('../services/ui/clientOptions')
const getServerSettings = require('../services/functions/getServerSettings')

const rootRouter = express.Router()

Expand Down Expand Up @@ -128,7 +125,7 @@ rootRouter.get('/api/settings', async (req, res, next) => {
try {
if (
config.authentication.alwaysEnabledPerms.length ||
!config.authMethods.length
!config.authentication.methods.length
) {
if (req.session.tutorial === undefined) {
req.session.tutorial = !config.map.forceTutorial
Expand Down Expand Up @@ -163,186 +160,63 @@ rootRouter.get('/api/settings', async (req, res, next) => {
}
req.session.save()

const getUser = async () => {
if (config.authMethods.length && req.user) {
try {
const user = await Db.query('User', 'getOne', req.user.id)
if (user) {
if (!user.selectedWebhook) {
const newWebhook = req.user.perms.webhooks.find(
(n) => n in Event.webhookObj,
)
await Db.query('User', 'updateWebhook', user.id, newWebhook)
if (req.session?.user) {
req.session.user.selectedWebhook = newWebhook
req.session.save()
}
}
delete user.password

return {
...req.user,
...user,
valid: true,
username: user.username || req.user.username,
if (config.authentication.methods.length && req.user) {
try {
const user = await Db.query('User', 'getOne', req.user.id)
if (user) {
if (!user.selectedWebhook) {
const newWebhook = req.user.perms.webhooks.find(
(n) => n in Event.webhookObj,
)
await Db.query('User', 'updateWebhook', user.id, newWebhook)
if (req.session?.user) {
req.session.user.selectedWebhook = newWebhook
req.session.save()
}
}
log.info(
HELPERS.session,
'Legacy user detected, forcing logout, User ID:',
req?.user?.id,
)
req.logout(() => {})
return { valid: false, tutorial: !config.map.forceTutorial }
} catch (e) {
log.warn(
HELPERS.session,
'Issue finding user, User ID:',
req?.user?.id,
e,
)
return { valid: false, tutorial: !config.map.forceTutorial }
}
} else if (req.session.perms) {
return { ...req.session, valid: true }
} catch (e) {
log.warn(
HELPERS.session,
'Issue finding user, User ID:',
req?.user?.id,
e,
)
}
return { valid: false, tutorial: !config.map.forceTutorial }
}
const serverSettings = {
user: await getUser(),
settings: {},
authMethods: config.authMethods,
userBackupLimits: config.database.settings.userBackupLimits,
config: {
map: {
...config.map,
...config.multiDomainsObj[req.headers.host.replaceAll('.', '_')],
general: undefined,
customRoutes: undefined,
links: undefined,
misc: undefined,
loginPage: !!config.map.loginPage.components.length,
donationPage: undefined,
messageOfTheDay: undefined,
customFloatingIcons: undefined,
excludeList: config.authentication.excludeFromTutorial,
polling: config.api.polling,
authCounts: {
areaRestrictions: config.authentication.areaRestrictions.length,
webhooks: config.webhooks.filter((w) => w.enabled).length,
scanner: Object.values(config.scanner).filter((s) => s.enabled)
.length,
},
},
tileServers: Object.fromEntries(
config.tileServers.map((s) => [s.name, s]),
),
navigation: Object.fromEntries(
config.navigation.map((n) => [n.name, n]),
),
navigationControls: {
react: {},
leaflet: {},
},
gymValidDataLimit:
Date.now() / 1000 - config.api.gymValidDataLimit * 86400,
},
extraUserFields: config.database.settings.extraUserFields,
}
const settings = getServerSettings(req)

// add user options here from the config that are structured as objects
if (serverSettings.user.valid) {
serverSettings.loggedIn = !!req.user

// keys that are being sent to the frontend but are not options
const ignoreKeys = [
'map',
'limit',
'icons',
'scanner',
'gymValidDataLimit',
]

Object.keys(serverSettings.config).forEach((setting) => {
try {
if (!ignoreKeys.includes(setting)) {
const category = serverSettings.config[setting]
Object.keys(category).forEach((option) => {
category[option].name = option
})
if (
config.map[setting] &&
typeof config.map[setting] !== 'object'
) {
serverSettings.settings[setting] = config.map[setting]
} else {
serverSettings.settings[setting] =
category[Object.keys(category)[0]].name
}
}
} catch (e) {
log.warn(
HELPERS.config,
`Error setting ${setting}, most likely means there are no options set in the config`,
e,
)
}
})

if ('perms' in settings.user) {
if (
serverSettings.user.perms.pokemon &&
settings.user.perms.pokemon &&
config.api.queryOnSessionInit.pokemon
) {
Event.setAvailable('pokemon', 'Pokemon', Db, false)
}
if (
config.api.queryOnSessionInit.raids &&
(serverSettings.user.perms.raids || serverSettings.user.perms.gyms)
(settings.user.perms.raids || settings.user.perms.gyms)
) {
Event.setAvailable('gyms', 'Gym', Db, false)
}
if (
config.api.queryOnSessionInit.quests &&
(serverSettings.user.perms.quests ||
serverSettings.user.perms.pokestops ||
serverSettings.user.perms.invasions ||
serverSettings.user.perms.lures)
(settings.user.perms.quests ||
settings.user.perms.pokestops ||
settings.user.perms.invasions ||
settings.user.perms.lures)
) {
Event.setAvailable('pokestops', 'Pokestop', Db, false)
}
if (
serverSettings.user.perms.nests &&
config.api.queryOnSessionInit.nests
) {
if (settings.user.perms.nests && config.api.queryOnSessionInit.nests) {
Event.setAvailable('nests', 'Nest', Db, false)
}
if (Object.values(config.api.queryOnSessionInit).some((v) => v)) {
if (Object.values(config.api.queryOnSessionInit).some(Boolean)) {
Event.addAvailable()
}

serverSettings.defaultFilters = buildDefaultFilters(
serverSettings.user.perms,
Db,
)

// Backup in case there are Pokemon/Quests/Raids etc that are not in the masterfile
// Primary for quest rewards that are form unset, despite normally have a set form

serverSettings.ui = generateUi(
serverSettings.defaultFilters,
serverSettings.user.perms,
)

serverSettings.menus = advMenus()

const { clientValues, clientMenus } = clientOptions(
serverSettings.user.perms,
)

serverSettings.userSettings = clientValues
serverSettings.clientMenus = clientMenus
}
res.status(200).json({ serverSettings })

res.status(200).json(settings)
} catch (error) {
res.status(500).json({ error: error.message, status: 500 })
next(error)
Expand Down
Loading

0 comments on commit addb5f3

Please sign in to comment.