Request a csrftoken before every request

This commit is contained in:
LoveEevee 2020-03-17 07:20:03 +03:00
parent 841e9d37d1
commit 2232c36182
3 changed files with 73 additions and 53 deletions

View File

@ -397,6 +397,7 @@ class Account{
} }
request(url, obj, get){ request(url, obj, get){
this.lock(true) this.lock(true)
var doRequest = token => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var request = new XMLHttpRequest() var request = new XMLHttpRequest()
request.open(get ? "GET" : "POST", "api/" + url) request.open(get ? "GET" : "POST", "api/" + url)
@ -423,13 +424,19 @@ class Account{
}) })
if(obj){ if(obj){
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8") request.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
request.setRequestHeader("X-CSRFToken", gameConfig._csrf_token) request.setRequestHeader("X-CSRFToken", token)
request.send(JSON.stringify(obj)) request.send(JSON.stringify(obj))
}else{ }else{
request.send() request.send()
} }
}) })
} }
if(get){
return doRequest()
}else{
return loader.getCsrfToken().then(doRequest)
}
}
lock(isLocked){ lock(isLocked){
this.locked = isLocked this.locked = isLocked
if(this.mode === "login" || this.mode === "register"){ if(this.mode === "login" || this.mode === "register"){

View File

@ -396,6 +396,16 @@ class Loader{
request.send() request.send()
}) })
} }
getCsrfToken(){
return this.ajax("api/csrftoken").then(response => {
var json = JSON.parse(response)
if(json.status === "ok"){
return Promise.resolve(json.token)
}else{
return Promise.reject()
}
})
}
clean(error){ clean(error){
var fontDetectDiv = document.getElementById("fontdetectHelper") var fontDetectDiv = document.getElementById("fontdetectHelper")
if(fontDetectDiv){ if(fontDetectDiv){

View File

@ -272,6 +272,7 @@ class ScoreStorage{
} }
sendToServer(obj, retry){ sendToServer(obj, retry){
if(account.loggedIn){ if(account.loggedIn){
return loader.getCsrfToken().then(token => {
var request = new XMLHttpRequest() var request = new XMLHttpRequest()
request.open("POST", "api/scores/save") request.open("POST", "api/scores/save")
var promise = pageEvents.load(request).then(response => { var promise = pageEvents.load(request).then(response => {
@ -296,8 +297,10 @@ class ScoreStorage{
} }
}) })
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8") request.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
request.setRequestHeader("X-CSRFToken", token)
request.send(JSON.stringify(obj)) request.send(JSON.stringify(obj))
return promise return promise
})
}else{ }else{
return Promise.resolve() return Promise.resolve()
} }