highscore-server/src/web.v

87 lines
1.3 KiB
V

module main
import vweb
import json
import time
struct Status {
status int
message string
}
struct ErrorStatus {
status int
error string
message string
}
pub fn (mut app App) index() vweb.Result {
if app.config.redirect {
app.redirect(app.config.redirect_url)
}
return app.text("Hello :)")
}
['/api/v1/score/list']
pub fn (mut app App) score_list() vweb.Result {
if !app.auth() {
app.set_status(401, '')
return app.json(
ErrorStatus {
401,
"Unauthorized",
"OAuth token is missing"
}
)
}
scores := app.get_scores()
return app.json(scores)
}
[post]
['/api/v1/score/submit']
pub fn (mut app App) score_submit() vweb.Result {
if !app.auth() {
app.set_status(401, '')
return app.json(
ErrorStatus {
401,
"Unauthorized",
"OAuth token is missing"
}
)
}
body := json.decode(Score, app.req.data) or {
app.set_status(400, '')
return app.json(
ErrorStatus {
400,
"Bad Request",
"Bad JSON object"
}
)
}
app.insert_score(ScoreRes{player:body.player, score:body.score, time:time.now().unix_time()})
return app.json(
Status {
200,
"Success"
}
)
}
fn (mut app App) auth() bool {
app.config = load_config()
auth_header := app.get_header('Authorization')
token := auth_header.after('Bearer ')
return token == app.config.token
}