safety commit before system upgrade

This commit is contained in:
peter
2020-01-30 15:22:05 +01:00
parent 78ad241526
commit f7f770a40c
36 changed files with 651 additions and 125 deletions
@@ -1,6 +1,6 @@
import { RPCInterface } from "rpclibrary";
import { Inject, Module } from "../../Injector/ServiceDecorator";
import { TableDefiniton, Character } from "../../Types/Types";
import { TableDefiniton, Character, Spec, User } from "../../Types/Types";
import { CharacterManagerIfc } from "./RPCInterface";
import { FrontworkComponent } from "../../Types/FrontworkComponent";
import { getSpecTableData, SpecT } from "../../Types/PlayerSpecs";
@@ -18,12 +18,21 @@ implements FrontworkComponent<CharacterManagerIfc, RPCInterface>, ICharacterMana
private admin: IAdmin
@Inject(ILoginManager)
private loginManager : any
private loginManager : ILoginManager
exportRPCs = () => [
{
name: 'getSpecId' as 'getSpecId',
call: this.getSpecId
name: 'getSpecId' as 'getSpecId',
call: this.getSpecId
},{
name: 'getCharacterByName' as 'getCharacterByName',
call: this.getCharacterByName
},{
name: 'getCharacters' as 'getCharacters',
call: this.getCharacters
},{
name: 'getCharactersOfUser' as 'getCharactersOfUser',
call: this.getCharactersOfUser
}
]
@@ -44,7 +53,7 @@ implements FrontworkComponent<CharacterManagerIfc, RPCInterface>, ICharacterMana
name: 'characters',
tableBuilder: (table) => {
table.increments("id").primary()
table.string("name").notNullable().unique()
table.string("charactername").notNullable().unique()
table.integer("specid").notNullable()
table.foreign("specid").references("specs.id")
table.integer("userid").notNullable()
@@ -55,8 +64,8 @@ implements FrontworkComponent<CharacterManagerIfc, RPCInterface>, ICharacterMana
tableBuilder: (table) => {
table.increments("id")
table.string('class')
table.string('name')
table.unique(['class', 'name'])
table.string('specname')
table.unique(['class', 'specname'])
}
}
]
@@ -64,17 +73,14 @@ implements FrontworkComponent<CharacterManagerIfc, RPCInterface>, ICharacterMana
private initialized = false
initialize = async () => {
if(!this.initialized)
this.initialized = true
//initialize spec table
getLogger('CharacterManager').debug('inserting specs')
if(this.initialized) return
this.initialized = true
await this.admin.knex('specs').insert(getSpecTableData()).catch(e => { console.log("skipping spec insertion") })
}
createCharacter = async (userToken: string, character : Character) : Promise<Character> => {
try{
character.charactername = character.charactername.toLowerCase()
const user = this.loginManager.getUserRecordByToken(userToken)
await this.admin.knex('characters').insert(character)
const char : Character = await this.admin.knex.select('*').from('characters').where(character).first()
@@ -90,12 +96,33 @@ implements FrontworkComponent<CharacterManagerIfc, RPCInterface>, ICharacterMana
return this.admin.knex.select('*').from('characters')
}
getCharacterByName = async(charactername: string) : Promise<(Character & User & Spec) | void> => {
charactername = charactername.toLowerCase()
return await this.admin.knex('characters as c')
.join('specs as s', 's.id', '=', 'c.specid')
.join('users as u', 'u.id', '=', 'c.userid')
.select('charactername', 'class', 'specname', 'username', 'rank', 'locked', )
.where('charactername', '=', charactername)
.first()
}
getCharactersOfUser = async(username: string) : Promise<(Character & Spec)[]> => {
username = username.toLowerCase()
return await this.admin.knex('characters as c')
.join('users as u', 'u.id', '=', 'c.userid')
.join('specs as s', 's.id', '=', 'c.specid')
.select('class', 'charactername', 'class', 'specname')
.where('u.username', '=', username)
}
getSpecId = async <c extends keyof SpecT>(clazz: c, name: SpecT[c]) => await this.admin.knex
.from('specs')
.select('id')
.where({
.where(<Spec>{
class: clazz,
name: name
}).first().then(spec => spec.id)
specname: name
})
.first()
.then(spec => spec.id)
}
@@ -1,4 +1,4 @@
import { Character } from "../../Types/Types"
import { Character, Spec, User } from "../../Types/Types"
import { SpecT } from "../../Types/PlayerSpecs"
@@ -6,4 +6,6 @@ export class ICharacterManager{
createCharacter: (usertoken: string, char : Character) => Promise<Character>
getSpecId: <c extends keyof SpecT>(clazz: c, name: SpecT[c]) => Promise<number>
getCharacters: () => Promise<Character[]>
getCharacterByName: (charactername: string) => Promise<(Character & User & Spec) | void>
getCharactersOfUser: (username: string) => Promise<(Character & Spec)[]>
}
@@ -5,6 +5,8 @@ export type CharacterManagerIfc = {
CharacterManager: {
getSpecId : ICharacterManager['getSpecId']
getCharacters : ICharacterManager['getCharacters']
getCharacterByName : ICharacterManager['getCharacterByName']
getCharactersOfUser: ICharacterManager['getCharactersOfUser']
}
}
+8 -9
View File
@@ -44,7 +44,7 @@ implements FrontworkComponent<ItemManagerIfc, ItemManagerFeatureIfc>, TableDefin
try{
return <Item>{
name: r.wowhead.item[0].name[0],
itemname: r.wowhead.item[0].name[0],
iconname: r.wowhead.item[0].icon[0]._,
url: r.wowhead.item[0].link[0],
quality: r.wowhead.item[0].quality[0]._,
@@ -58,20 +58,19 @@ implements FrontworkComponent<ItemManagerIfc, ItemManagerFeatureIfc>, TableDefin
getTableDefinitions(): TableDefiniton[] {
return [
{
name: 'reservations',
name: 'tokens',
tableBuilder: (table) => {
table.integer("user_id").primary()
table.foreign("user_id").references("id").inTable('users')
table.integer("item_id").primary()
table.foreign("item_id").references("id").inTable('items')
table.integer("raid_id").primary()
table.foreign("raid_id").references("id").inTable('raids')
table.integer("characterid").primary()
table.foreign("characterid").references("id").inTable('characters')
table.integer("itemid").primary()
table.foreign("itemid").references("id").inTable('items')
table.integer("level")
}
},{
name: 'items',
tableBuilder: (table) => {
table.increments("id").primary()
table.string('name').unique().notNullable()
table.string('itemname').unique().notNullable()
table.string('iconname').notNullable()
table.string('url').notNullable()
table.string('quality').defaultTo('Epic').notNullable()
+3 -2
View File
@@ -1,11 +1,12 @@
import { Auth, Rank, User, RPCPermission } from "../../Types/Types"
import { Auth, Rank, User, RPCPermission, UserRecord } from "../../Types/Types"
export class ILoginManager{
login: (username:string, pwHash:string) => Promise<Auth>
logout: (username: string, tokenValue :string) => Promise<void>
getAuth: (tokenValue: string) => Promise<Auth>
getAuth: (tokenValue: string) => Promise<Auth | void>
createUser: (user:User) => Promise<User>
setPermission: (perm: RPCPermission) => Promise<void>
getPermissions: () => Promise<RPCPermission[]>
checkToken: (token: string, rank: Rank) => boolean
getUserRecordByToken: (tokenValue: string) => UserRecord | void
}
+50 -34
View File
@@ -7,10 +7,10 @@ import { RaidManager } from "../Raid/RaidManager";
import { CharacterManager } from "../Character/CharacterManager";
import { LoginManagerIfc, LoginManagerFeatureIfc } from "./RPCInterface";
import { FrontworkComponent } from "../../Types/FrontworkComponent";
import { Rank, User, Auth, _Rank, TableDefiniton, RPCPermission, FrontcraftFeatureIfc, AnyRPCExporter, Token } from "../../Types/Types";
import { Rank, User, Auth, _Rank, TableDefiniton, RPCPermission, FrontcraftFeatureIfc, AnyRPCExporter, Token, UserRecord } from "../../Types/Types";
import { IAdmin } from "../../Admin/Interface";
import { ILoginManager } from "./Interface";
import { getLogger } from "log4js";
import { getLogger, Logger } from "log4js";
const uuid = require('uuid/v4')
@@ -45,11 +45,7 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
exporters :any[] = []
rankServers : {[rank in Rank] : Serverstate}
userLogins : {[username in string] : {
user: User
connections: {[port in number]: Socket}
auth: Auth
}} = {}
userLogins : {[username in string] : UserRecord} = {}
exportRPCs = () => [
{
@@ -89,7 +85,7 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
name: 'users',
tableBuilder: (table) => {
table.increments("id").primary()
table.string("name").notNullable().unique()
table.string("username").notNullable().unique()
table.string("pwhash").notNullable()
table.string("rank").notNullable()
table.string("email").nullable().unique()
@@ -98,7 +94,7 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
},{
name: 'rpcpermissions',
tableBuilder: (table) => {
table.string("name").primary().notNullable()
table.string("rpcname").primary().notNullable()
_Rank.forEach(r => {
if(r === 'ADMIN')
table.boolean(r).defaultTo(true).notNullable()
@@ -118,7 +114,7 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
await Promise.all(
[this, ...this.exporters].flatMap(exp => exp.exportRPCFeatures().map(async (feature) => {
try{
await this.admin.knex.insert({ name: feature.name }).into('rpcpermissions')
await this.admin.knex.insert({ rpcname: feature.name }).into('rpcpermissions')
}catch(e){
console.log(e);
}
@@ -163,32 +159,37 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
Object.values(this.userLogins).map(userLogin => {
const auth = userLogin.auth
if(!this.checkToken(auth.token.value, auth.user.rank)){
this.logout(auth.user.name, auth.token.value)
this.logout(auth.user.username, auth.token.value)
}
})
}
checkConnection = async (socket: Socket) => {
let data : any
let tries = 0
while(!data){
tries ++
if(tries === 5){
getLogger('LoginManager').debug('Connection check failed for connection *'+socket.port)
socket.destroy()
return
return false
}
data = await Promise.race([socket.call('getUserData'), new Promise((res, rej) => { setTimeout(res, 250);})])
}
this.userLogins[data.user.name].connections[socket.port] = socket
data = await Promise.race([socket.call('getUserData'), new Promise((res, rej) => { setTimeout(res, 1000);})])
}
if(!this.userLogins[data.user.username]){
await this.logout(data.user.username, data.token.value)
return false
}
this.userLogins[data.user.username].connections[socket.port] = socket
await socket.call('navigate', ["/frontcraft/dashboard"])
return true
}
setPermission = async (permission: RPCPermission) => {
await this.admin.knex('rpcpermissions')
.where('rpcname', '=', permission.name)
.where('rpcname', '=', permission.rpcnamename)
.update(permission)
}
@@ -200,7 +201,7 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
const perm : RPCPermission[] = await this.admin.knex
.select(rank)
.from('rpcpermissions')
.where('name', '=', <string>feature)
.where('rpcname', '=', <string>feature)
if(perm.length === 0) return false
return perm[0][rank]
@@ -233,6 +234,8 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
user.locked = false
}
user.username = user.username.toLowerCase()
await this.admin.knex('users')
.insert(user)
@@ -246,10 +249,20 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
logout = async (username:string, tokenValue : string) : Promise<void> => {
try{
username = username.toLowerCase()
const maybeRecord = this.getUserRecordByToken(tokenValue)
if(maybeRecord && maybeRecord.auth.user.username != username){
getLogger('LoginManager').warn(`Bad logout attempt
token by: ${maybeRecord.auth.user.username}
tried to logout: ${username}`)
return
}
await Promise.all (Object.values(this.userLogins[username].connections).map(async (sock) => {
await sock.call('navigate', '/auth/login')
}))
if(this.userLogins[username]){
await Promise.all (Object.values(this.userLogins[username].connections).map(async (sock) => {
await sock.call('navigate', '/auth/login')
}))
}
Object.values(this.rankServers)
.forEach(state => {
@@ -263,10 +276,11 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
}
login = async(username:string, pwHash:string) : Promise<Auth> => {
username = username.toLowerCase()
const res:User[] = await this.admin.knex
.select('*')
.from('users')
.where({ name: username })
.where({ username: username })
if(res.length > 0 && pwHash === res[0].pwhash){
const user:User = res[0]
@@ -284,9 +298,8 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
port: this.rankServers[user.rank].port
}
this.userLogins[user.name] = {connections: {}, auth: userAuth, user:user}
this.userLogins[user.username] = {connections: {}, auth: userAuth, user:user}
this.rankServers[user.rank].allowed.push(token.value)
return userAuth
}
@@ -294,16 +307,14 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
}
getUserRecordByToken(tokenValue: string){
const maybeRecord = Object.values(this.userLogins).find(login => login.auth.token.value === tokenValue)
return maybeRecord?maybeRecord:undefined
return Object.values(this.userLogins).find(login => login.auth.token.value === tokenValue)
}
getAuth = async (tokenValue:string) : Promise<Auth> => {
getAuth = async (tokenValue:string) : Promise<Auth | void> => {
const maybeAuth = this.getUserRecordByToken(tokenValue)
if(maybeAuth)
return maybeAuth.auth
throw new Error("Bad token")
return
}
startRankServer = async (rank : Rank, port: number) : Promise<RPCServer> => {
@@ -322,9 +333,14 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
},
connectionHandler: (socket) => {
this.checkConnection(socket).catch((e) => {
console.log(e);
}) //sometimes times out if you go too fast
this.checkConnection(socket).then(res => {
if(!res){
socket.destroy();
}
}).catch((e) => {
socket.destroy();
getLogger('LoginManager').warn(e);
})
},
errorHandler: (socket, e, rpcName, args) => {
console.log(rpcName, args);
@@ -346,8 +362,8 @@ implements FrontworkComponent<LoginManagerIfc, LoginManagerFeatureIfc>, ILoginMa
createToken = (user:User): Token => {
if(this.userLogins[user.name]){
return this.userLogins[user.name].auth.token
if(this.userLogins[user.username]){
return this.userLogins[user.username].auth.token
}
const token:Token = {
+2 -2
View File
@@ -1,4 +1,4 @@
import { User, Raid, Signup } from "../../Types/Types"
import { Raid, Signup, Character } from "../../Types/Types"
export class IRaidManager{
getRaids: () => Promise<Raid[]>
@@ -6,5 +6,5 @@ export class IRaidManager{
addSignup: (signup: Signup) => Promise<any>
removeSignup: (signup: Signup) => Promise<any>
getSignups: (raid:Raid) => Promise<Signup[]>
sign: (user:User, raid:Raid, attending:boolean) => Promise<any>
sign: (userToken: string, character:Character, raid:Raid, attending:boolean) => Promise<any>
}
+32 -18
View File
@@ -1,9 +1,10 @@
import { Inject, Module } from "../../Injector/ServiceDecorator";
import { RaidManagerIfc, RaidManagerFeatureIfc } from "./RPCInterface";
import { FrontworkComponent } from "../../Types/FrontworkComponent";
import { TableDefiniton, Signup, Raid, User } from "../../Types/Types";
import { TableDefiniton, Signup, Raid, User, Character } from "../../Types/Types";
import { IAdmin } from "../../Admin/Interface";
import { IRaidManager } from "./Interface";
import { ILoginManager } from "../Login/Interface";
@Module(IRaidManager)
export class RaidManager
@@ -13,6 +14,9 @@ implements FrontworkComponent<RaidManagerIfc, RaidManagerFeatureIfc>, IRaidManag
@Inject(IAdmin)
private admin: IAdmin
@Inject(ILoginManager)
private login: ILoginManager
exportRPCs = () => [{
name: 'getRaids' as 'getRaids',
call: this.getRaids
@@ -57,11 +61,11 @@ implements FrontworkComponent<RaidManagerIfc, RaidManagerFeatureIfc>, IRaidManag
},{
name: 'signups',
tableBuilder: (table) => {
table.primary(['raid_id', 'user_id'])
table.integer('raid_id')
table.foreign('raid_id').references('id').inTable('raids')
table.integer('user_id')
table.foreign('user_id').references('id').inTable('users')
table.primary(['raidid', 'characterid'])
table.integer('raidid')
table.foreign('raidid').references('id').inTable('raids')
table.integer('characterid')
table.foreign('characterid').references('id').inTable('characters')
}
}
]
@@ -78,8 +82,8 @@ implements FrontworkComponent<RaidManagerIfc, RaidManagerFeatureIfc>, IRaidManag
removeSignup = async (signup: Signup) => await this.admin
.knex('signups')
.where({
raid_id: signup.raid_id,
user_id: signup.user_id
raid_id: signup.raidid,
character_id: signup.characterid
})
.delete()
@@ -87,15 +91,25 @@ implements FrontworkComponent<RaidManagerIfc, RaidManagerFeatureIfc>, IRaidManag
.select('*')
.from('raids')
getSignups = async (raid:Raid) : Promise<Signup[]> => await this.admin.knex
.select('*')
.from('signups')
.where('raid_id', '=', raid.id!)
sign = async (user:User, raid:Raid) => await this.admin
getSignups = async (raid:Raid) : Promise<Signup[]> => await this.admin
.knex('signups')
.insert({
raid_id: raid.id!,
user_id: user.id!
})
.join('characters as c', 'c.id', '=', 'characterid')
.join('specs as s', 's.id', '=', 'specid')
.join('users as u', 'u.id', '=', 'userid')
.select('*')
.where('raidid', '=', raid.id!)
sign = async (usertoken:string, character:Character, raid:Raid) => {
const maybeUserRecord = this.login.getUserRecordByToken(usertoken)
if(!maybeUserRecord || maybeUserRecord.user.id != character.userid){
throw new Error("Bad Usertoken")
}
await this.admin
.knex('signups')
.insert({
raidid: raid.id!,
characterid: character.id!
})
}
}
+3 -3
View File
@@ -13,7 +13,7 @@ export const Injector = new class {
rootInterface : Type<any>
root : Type<any>
rootModules: Type<any>[] = []
modules : {ifc?: Type<any>, implementation: Type<any>}[] = []
modules : {implements?: Type<any>, implementation: Type<any>}[] = []
moduleObjs : {[key in string] : FrontworkComponent} = {}
@@ -31,8 +31,8 @@ export const Injector = new class {
if(target.name === this.rootInterface.name || target.name === this.root.name){
let modules = this.modules.map(m => {
const module = new m.implementation()
if(m.ifc)
this.moduleObjs[m.ifc.name] = module
if(m.implements)
this.moduleObjs[m.implements.name] = module
this.moduleObjs[m.implementation.name] = module
return module
})
+3 -3
View File
@@ -9,7 +9,7 @@ import { FrontworkComponent } from "../Types/FrontworkComponent";
export const Module = (ifc?: Type<any>) : GenericClassDecorator<Type<any>> => {
return (target: Type<any>) => {
Injector.modules.push({
ifc: ifc,
extends: ifc,
implementation: target
})
}
@@ -20,12 +20,12 @@ export const Module = (ifc?: Type<any>) : GenericClassDecorator<Type<any>> => {
* @constructor
*/
export const RootComponent = (config : {
rootInterface : Type<any>
implements : Type<any>
imports : Type<FrontworkComponent>[]
}) : GenericClassDecorator<Type<any>> => {
return (target: Type<any>) => {
Injector.rootModules = config.imports
Injector.rootInterface = config.rootInterface
Injector.rootInterface = config.implements
Injector.root = target
}
}
+16 -2
View File
@@ -1,4 +1,4 @@
import { Spec, _Class } from "./Types"
import { Spec, _Class, Class } from "./Types"
export type SpecT = {
Warrior : 'Arms' | 'Fury' | 'Protection'
@@ -74,9 +74,23 @@ export function getSpecTableData() : Spec[]{
const specNames : string[] = specs[_class]
return specNames.map(specName => {
return {
name: specName,
specname: specName,
class: _class
}
})
})
}
export function getClassColor(c: Class) : string{
switch(c){
case "Warrior": return "#C79C6E"
case "Warlock": return "#8787ED"
case "Shaman": return "#0070DE"
case "Rogue": return "#FFF569"
case "Priest": return "#FFFFFF"
case "Paladin": return "#F58CBA"
case "Mage": return "#40C7EB"
case "Druid": return "#FF7D0A"
case "Hunter": return "#A9D271"
}
}
+13 -8
View File
@@ -1,5 +1,5 @@
import * as Knex from "knex"
import { RPCExporter } from "rpclibrary";
import { RPCExporter, Socket } from "rpclibrary";
import { RaidManagerIfc, RaidManagerFeatureIfc } from "../Components/Raid/RPCInterface";
import { LoginManagerIfc, LoginManagerFeatureIfc } from "../Components/Login/RPCInterface";
import { CharacterManagerIfc, CharacterManagerFeatureIfc } from "../Components/Character/RPCInterface";
@@ -33,14 +33,14 @@ export const _Class : Class[] = ["Warrior" , "Rogue" , "Hunter" , "Mage" , "Warl
export type AnyRPCExporter = RPCExporter<any,any>
export type RPCPermission = {
name: string
rpcnamename: string
} & {
[rank in Rank] : boolean
}
export type Item = {
id?:number
name:string
itemname:string
iconname:string
url:string
quality:string
@@ -49,7 +49,7 @@ export type Item = {
export type User = {
id?: number
name: string
username: string
pwhash: string
rank: Rank
email?: string
@@ -65,13 +65,13 @@ export type Raid = {
}
export type Signup = {
raid_id: number
user_id: number
raidid: number
characterid: number
}
export type Character = {
id? : number
name : string
charactername : string
specid : number
userid : number
}
@@ -84,11 +84,16 @@ export type Token = {
export type Auth = {port: number, user: User, token: Token}
export type UserRecord = {
user: User
connections: {[port in number]: Socket}
auth: Auth
}
export type Spec = {
id?: number,
class: Class,
name: string
specname: string
}
export type SomeOf<T> = {