Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reactivate (some) clan pages #491

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module.exports = function(grunt) {
grunt.registerTask('prod', [
'sass:dist',
'concat:js',
'uglify:dist'
'uglify:dist',
'copy'
]);
};
1 change: 1 addition & 0 deletions config/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const appConfig = {
tokenLifespan: process.env.TOKEN_LIFESPAN || 43200
},
oauth: {
strategy: 'faforever',
clientId: process.env.OAUTH_CLIENT_ID || '12345',
clientSecret: process.env.OAUTH_CLIENT_SECRET || '12345',
url: oauthUrl,
Expand Down
49 changes: 47 additions & 2 deletions fafApp.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ const clanRouter = require("./routes/views/clanRouter")
const accountRouter = require("./routes/views/accountRouter")
const dataRouter = require('./routes/views/dataRouter');
const setupCronJobs = require("./scripts/cron-jobs")
const OidcStrategy = require("passport-openidconnect");
const axios = require("axios");
const refresh = require("passport-oauth2-refresh");

const copyFlashHandler = (req, res, next) => {
res.locals.message = req.flash();
Expand All @@ -33,6 +36,45 @@ const errorHandler = (err, req, res, next) => {
res.status(500).render('errors/500');
}

const loadAuth = () => {
passport.serializeUser((user, done) => done(null, user))
passport.deserializeUser((user, done) => done(null, user))

const authStrategy = new OidcStrategy({
issuer: appConfig.oauth.url + '/',
tokenURL: appConfig.oauth.url + '/oauth2/token',
authorizationURL: appConfig.oauth.publicUrl + '/oauth2/auth',
userInfoURL: appConfig.oauth.url + '/userinfo?schema=openid',
clientID: appConfig.oauth.clientId,
clientSecret: appConfig.oauth.clientSecret,
callbackURL: `${appConfig.host}/${appConfig.oauth.callback}`,
scope: ['openid', 'offline', 'public_profile', 'write_account_data']
}, function (iss, sub, profile, jwtClaims, accessToken, refreshToken, params, verified) {

axios.get(
appConfig.apiUrl + '/me',
{
headers: {'Authorization': `Bearer ${accessToken}`}
}).then((res) => {
const user = res.data
user.token = accessToken
user.refreshToken = refreshToken
user.data.attributes.token = accessToken;
user.data.id = user.data.attributes.userId;

return verified(null, user);
}).catch(e => {
console.error('[Error] views/auth.js::passport::verify failed with "' + e.toString() + '"');

return verified(null, null);
});
}
)

passport.use(appConfig.oauth.strategy, authStrategy)
refresh.use(appConfig.oauth.strategy, authStrategy)
}

module.exports.setupCronJobs = () => {
setupCronJobs()
}
Expand Down Expand Up @@ -63,8 +105,7 @@ module.exports.setup = (app) => {
app.set('views', 'templates/views')
app.set('view engine', 'pug')
app.set('port', appConfig.expressPort)

app.use(middleware.injectServices)

app.use(middleware.initLocals)

app.use(express.static('public', {
Expand All @@ -88,6 +129,10 @@ module.exports.setup = (app) => {
}))
app.use(passport.initialize())
app.use(passport.session())
loadAuth()

app.use(middleware.injectServices)

app.use(flash())
app.use(middleware.username)
app.use(copyFlashHandler)
Expand Down
2 changes: 1 addition & 1 deletion grunt/concurrent.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
dev: {
tasks: ['nodemon', 'concat', 'watch'],
tasks: ['nodemon', 'concat', 'watch', 'copy'],
options: {
logConcurrentOutput: true
}
Expand Down
24 changes: 24 additions & 0 deletions grunt/copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = {
js: {
files:[
{
expand: true,
cwd: 'node_modules/simple-datatables/dist',
src: 'module.js',
dest: 'public/js/',
rename: function(dest, src) {
return dest + 'simple-datatables.js'
}
},
{
expand: true,
cwd: 'node_modules/simple-datatables/dist',
src: 'style.css',
dest: 'public/styles/css/',
rename: function(dest, src) {
return dest + 'simple-datatables.css'
}
}
]
}
}
1 change: 1 addition & 0 deletions lib/ApiErrors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports.AuthFailed = class AuthFailed extends Error {}
61 changes: 61 additions & 0 deletions lib/JavaApiClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const {Axios} = require("axios");
const refresh = require('passport-oauth2-refresh')
const {AuthFailed} = require('./ApiErrors')
const appConfig = require("../config/app")

const getRefreshToken = (user) => {
return new Promise((resolve, reject) => {
refresh.requestNewAccessToken(appConfig.oauth.strategy, user.refreshToken, function(err, accessToken, refreshToken) {
if (err || !accessToken) {
return reject(new AuthFailed('Failed to refresh token'))
}

return resolve([accessToken, refreshToken])
})
})
}

module.exports = (javaApiBaseURL, user) => {
let tokenRefreshRunning = null
const client = new Axios({
baseURL: javaApiBaseURL
})

client.interceptors.request.use(
async config => {
config.headers = {
'Authorization': `Bearer ${user.token}`,
}

return config;
})

client.interceptors.response.use(async (res) => {
if (!res.config._refreshTokenRequest && res.config && res.status === 401) {
res.config._refreshTokenRequest = true;

if (!tokenRefreshRunning) {
tokenRefreshRunning = getRefreshToken(user)
}

const [token, refreshToken] = await tokenRefreshRunning

user.token = token
user.refreshToken = refreshToken

res.config.headers['Authorization'] = `Bearer ${token}`

return client.request(res.config)
}

if (res.status === 401) {
new AuthFailed('Token no longer valid and refresh did not help')
}

return res
})



return client
}
19 changes: 12 additions & 7 deletions lib/LeaderboardRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,18 @@ class LeaderboardRepository {
let leaderboardData = []

data.data.forEach((item, index) => {
leaderboardData.push({
rating: item.attributes.rating,
totalgames: item.attributes.totalGames,
wonGames: item.attributes.wonGames,
date: item.attributes.updateTime,
label: data.included[index].attributes.login,
})
try {
leaderboardData.push({
rating: item.attributes.rating,
totalgames: item.attributes.totalGames,
wonGames: item.attributes.wonGames,
date: item.attributes.updateTime,
label: data.included[index]?.attributes.login || 'unknown user',
})
} catch (e) {
console.error('LeaderboardRepository::mapResponse failed on item with "' + e.toString() + '"')
}

})

return leaderboardData
Expand Down
14 changes: 0 additions & 14 deletions lib/LeaderboardServiceFactory.js

This file was deleted.

135 changes: 135 additions & 0 deletions lib/clan/ClanRepository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
class ClanRepository {
constructor(javaApiClient) {
this.javaApiClient = javaApiClient
}

async fetchAll() {
const response = await this.javaApiClient.get('/data/clan?include=leader&fields[clan]=name,tag,description,leader,memberships,createTime&fields[player]=login&page[number]=1&page[size]=3000')

if (response.status !== 200) {
throw new Error('ClanRepository::fetchAll failed with response status "' + response.status + '"')
}

const responseData = JSON.parse(response.data)

if (typeof responseData !== 'object' || responseData === null) {
throw new Error('ClanRepository::fetchAll malformed response, not an object')
}

if (!responseData.hasOwnProperty('data')) {
throw new Error('ClanRepository::fetchAll malformed response, expected "data"')
}

if (responseData.data.length === 0) {
console.log('[info] clans empty')

return []
}

if (!responseData.hasOwnProperty('included')) {
throw new Error('ClanRepository::fetchAll malformed response, expected "included"')
}

const clans = responseData.data.map((item, index) => ({
id: parseInt(item.id),
leaderName: responseData.included[index]?.attributes.login || '-',
name: item.attributes.name,
tag: item.attributes.tag,
createTime: item.attributes.createTime,
description: item.attributes.description,
population: item.relationships.memberships.data.length
}))

clans.sort((a, b) => {
if (a.population > b.population) {
return -1
}
if (a.population < b.population) {
return 1
}

return 0
});

return await clans
}

async fetchClan(id) {
let response = await this.javaApiClient.get(`/data/clan/${id}?include=memberships.player`)

if (response.status !== 200) {
throw new Error('ClanRepository::fetchClan failed with response status "' + response.status + '"')
}

const data = JSON.parse(response.data)

if (typeof data !== 'object' || data === null) {
throw new Error('ClanRepository::fetchClan malformed response, not an object')
}

if (!data.hasOwnProperty('data')) {
throw new Error('ClanRepository::fetchClan malformed response, expected "data"')
}

if (typeof data.data !== 'object' || data.data === null) {
return null
}

if (typeof data.included !== 'object' || data.included === null) {
throw new Error('ClanRepository::fetchClan malformed response, expected "included"')
}

const clanRaw = data.data.attributes

const clan = {
id: data.data.id,
name: clanRaw.name,
tag: clanRaw.tag,
description: clanRaw.description,
createTime: clanRaw.createTime,
requiresInvitation: clanRaw.requiresInvitation,
tagColor: clanRaw.tagColor,
updateTime: clanRaw.updateTime,
founder: null,
leader: null,
memberships: {},
}

let members = {};

for (let k in data.included) {
switch (data.included[k].type) {
case "player":
const player = data.included[k];
if (!members[player.id]) members[player.id] = {};
members[player.id].id = player.id;
members[player.id].name = player.attributes.login;

if (player.id === data.data.relationships.leader.data.id) {
clan.leader = members[player.id]
}

if (player.id === data.data.relationships.founder.data.id) {
clan.founder = members[player.id]
}

break;

case "clanMembership":
const membership = data.included[k];
const member = membership.relationships.player.data;
if (!members[member.id]) members[member.id] = {};
members[member.id].id = member.id;
members[member.id].membershipId = membership.id;
members[member.id].joinedAt = membership.attributes.createTime;
break;
}
}

clan.memberships = members

return clan
}
}

module.exports = ClanRepository
Loading