Skip to content
This repository has been archived by the owner on Oct 30, 2022. It is now read-only.

Commit

Permalink
updated api and other fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
roby2014 committed Feb 24, 2022
1 parent 12608d6 commit 533d860
Show file tree
Hide file tree
Showing 11 changed files with 227 additions and 80 deletions.
23 changes: 23 additions & 0 deletions controller/player.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package controller

import (
"encoding/json"
"net/http"

"github.com/gorilla/mux"
"github.com/robyzzz/csl-backend/model"
"github.com/robyzzz/csl-backend/utils"
)

// GET /api/playerstats/{steamid} - returns {steamid}'s stats or 404 if not found
func GetPlayerStats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

player, err := model.GetPlayerStats(mux.Vars(r)["steamid"])
if err != nil {
utils.APIErrorRespond(w, utils.ErrorResponse{Code: http.StatusNotFound, ErrorMsg: err.Error()})
return
}

json.NewEncoder(w).Encode(player)
}
52 changes: 47 additions & 5 deletions controller/steam_user.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,66 @@
package controller

import (
"log"
"encoding/json"
"net/http"

"github.com/gorilla/mux"
"github.com/robyzzz/csl-backend/config"
"github.com/robyzzz/csl-backend/model"
"github.com/robyzzz/csl-backend/utils"
"github.com/solovev/steam_go"
)

// GET /api/player/{steamid}
// Returns {steamid}'s steam data or 404 if not found
func GetSteamUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

player, err := model.GetSteamUser(mux.Vars(r)["steamid"])
if err != nil {
utils.APIErrorRespond(w, utils.ErrorResponse{Code: http.StatusNotFound, ErrorMsg: err.Error()})
return
}

json.NewEncoder(w).Encode(player)
}

// Not an API function
// Called when user logs in with steam
func CreateSteamUser(user *steam_go.PlayerSummaries) error {
return model.CreateSteamUser(utils.PlayerSummariesToSteamUser(user))
}

func UpdateSteamUser(steamID string) error {
// Not an API function
// Called when we want to update our logged user steam data using his session ID
// Updates steam data or internal server error if smt bad happened
func UpdateSteamUser(w http.ResponseWriter, r *http.Request) {
steamID := config.GetSessionID(r)

exists, err := model.DoesSteamUserExist(steamID)
if err != nil {
utils.APIErrorRespond(w, utils.ErrorResponse{Code: http.StatusInternalServerError, ErrorMsg: err.Error()})
return
}

updatedUser, err := steam_go.GetPlayerSummaries(steamID, config.STEAM_API_KEY)
if err != nil {
log.Printf("Failed to get PlayerSummaries @UpdateSteamUser: %s", err.Error())
return err
utils.APIErrorRespond(w, utils.ErrorResponse{Code: http.StatusInternalServerError, ErrorMsg: err.Error()})
return
}

steamUser := utils.PlayerSummariesToSteamUser(updatedUser)
var result error
if exists {
result = model.UpdateSteamUser(steamUser)
} else {
result = model.CreateSteamUser(steamUser)
}

if result != nil {
utils.APIErrorRespond(w, utils.ErrorResponse{Code: http.StatusInternalServerError, ErrorMsg: err.Error()})
return
}

return model.UpdateSteamUser(utils.PlayerSummariesToSteamUser(updatedUser))
http.Redirect(w, r, "/", http.StatusFound)
}
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ require (

)

require github.com/gorilla/securecookie v1.1.1 // indirect
require (
github.com/gorilla/securecookie v1.1.1 // indirect
github.com/jmoiron/sqlx v1.3.4 // indirect
)
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/jmoiron/sqlx v1.3.4 h1:wv+0IJZfL5z0uZoUjlpKgHkgaFSYD+r9CfrXjEXsO7w=
github.com/jmoiron/sqlx v1.3.4/go.mod h1:2BljVx/86SuTyjE+aPYlHCTNvZrnJXghYGpNiXLBMCQ=
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.10.4 h1:SO9z7FRPzA03QhHKJrH5BXA6HU1rS4V2nIVrrNC1iYk=
github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/solovev/steam_go v0.0.0-20170222182106-48eb5aae6c50 h1:5wu+B07+rk5rr6KYxYK+5fRr+m8ikSblPSgDTdrFUE4=
github.com/solovev/steam_go v0.0.0-20170222182106-48eb5aae6c50/go.mod h1:wDBDgAJlQWhdrpQeJcw6+FZwMddaNWFUo8u8bSfzA50=
29 changes: 11 additions & 18 deletions middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,19 @@ import (

"github.com/robyzzz/csl-backend/config"
"github.com/robyzzz/csl-backend/controller"
"github.com/robyzzz/csl-backend/utils"
)

// Authentication middleware called on routes that need to know if user is logged in.
// Returns to root page if session already exists.
// i.e usage: /login
func IsAuthenticated(h func(w http.ResponseWriter, r *http.Request)) http.Handler {
// Used to update steam user data when acessing a route or to let them log in
// If user is already logged in, we update, else we redirect to login page
// Usage: /login
func IsLogged(h func(w http.ResponseWriter, r *http.Request)) http.Handler {
next := http.HandlerFunc(h)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if config.SessionAlreadyExists(r) {
err := controller.UpdateSteamUser(config.GetSessionID(r))
if err != nil {
utils.APIErrorRespond(w, utils.ErrorResponse{http.StatusInternalServerError, err.Error()})
return
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if config.SessionAlreadyExists(r) {
controller.UpdateSteamUser(w, r)
} else {
next.ServeHTTP(w, r)
}

http.Redirect(w, r, "/", http.StatusFound)
return
}

next.ServeHTTP(w, r)
})
})
}
38 changes: 17 additions & 21 deletions model/db.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
package model

import (
"database/sql"
"fmt"
"log"
"time"

"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
env "github.com/robyzzz/csl-backend/config"
)

var db *sql.DB
var db *sqlx.DB
var err error

func Connect() {
db, err = sql.Open("postgres", connToString())
db, err = sqlx.Open("postgres", connToString())
if err != nil {
log.Fatalf("Error connecting to the DB: %s\n", err.Error())
}
Expand All @@ -22,30 +23,25 @@ func Connect() {
log.Fatalf("Error: Could not ping database: %s\n", err.Error())
}

_, err = db.Query(`CREATE TABLE IF NOT EXISTS steam_user (
id SERIAL PRIMARY KEY,
steamid TEXT,
personaname TEXT,
lastlogoff INTEGER,
profileurl TEXT,
avatar TEXT,
avatarmedium TEXT,
avatarfull TEXT,
realname TEXT,
primaryclanid TEXT,
timecreated INTEGER,
loccountrycode TEXT,
gameid INTEGER
);`)
db.MustExec(schema)
log.Printf("Database connection done successfully: %p\n", db)

users := []SteamUser{}
err := db.Select(&users, "SELECT * FROM steam_user;")
if err != nil {
log.Fatalf("Error: Could not create table steam_users: %s\n", err.Error())
log.Fatalf("Error: Could not ping get player: %s\n", err.Error())
}

log.Printf("Database connection done successfully: %p\n", db)
fmt.Println(users)
}

// Return a string for our db connection info
func connToString() string {
return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
env.POSTGRES_URL, env.POSTGRES_PORT, env.POSTGRES_USER, env.POSTGRES_PASSWORD, env.POSTGRES_DB)
}

// Returns date formatted as PQ's NOW()
func DBGetDateNow() string {
t := time.Now()
return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d:%04d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0)
}
31 changes: 31 additions & 0 deletions model/player.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package model

type CSLPlayerStats struct {
ID uint64 `json:"id"`
Player_SteamID string `json:"player_steamid"`
Map_ID int `json:"map_id"`
Kills int `json:"kills"`
Deaths int `json:"deaths"`
Assists int `json:"assists"`
Shots int `json:"shots"`
Hits int `json:"hits"`
Damage int `json:"damage"`
First_Blood int `json:"first_blood"`
Aces int `json:"aces"`
Headshots int `json:"headshots"`
No_Scope int `json:"no_scope"`
Count int `json:"count"`
Playtime int `json:"playtime"`
Match_Win int `json:"match_win"`
Match_Lose int `json:"match_lose"`
Match_Draw int `json:"match_draw"`
Rounds_Won int `json:"rounds_won"`
Rounds_Lost int `json:"rounds_lost"`
Mvp int `json:"mvp"`
}

func GetPlayerStats(steamID string) (CSLPlayerStats, error) {
user := CSLPlayerStats{}
err := db.Get(&user, "SELECT * FROM player_stats WHERE player_steamid = $1;", steamID)
return user, err
}
56 changes: 56 additions & 0 deletions model/schema.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package model

var schema = `
DROP TABLE IF EXISTS steam_user;
DROP TABLE IF EXISTS player_stats;
CREATE TABLE IF NOT EXISTS "steam_user" (
"id" SERIAL PRIMARY KEY,
"steamid" TEXT,
"personaname" TEXT,
"lastlogoff" INTEGER,
"profileurl" TEXT,
"avatar" TEXT,
"avatarmedium" TEXT,
"avatarfull" TEXT,
"realname" TEXT,
"primaryclanid" TEXT,
"timecreated" INTEGER,
"loccountrycode" TEXT,
"gameid" INTEGER,
"created_at" TIMESTAMP,
"updated_at" TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS "player_stats" (
"id" SERIAL PRIMARY KEY,
"player_steamid" TEXT,
"map_id" INT,
"kills" INT DEFAULT 0,
"deaths" INT DEFAULT 0,
"assists" INT DEFAULT 0,
"shots" INT DEFAULT 0,
"hits" INT DEFAULT 0,
"damage" INT DEFAULT 0,
"first_blood" INT DEFAULT 0,
"aces" INT DEFAULT 0,
"headshots" INT DEFAULT 0,
"no_scope" INT DEFAULT 0,
"count" INT DEFAULT 0,
"playtime" INT DEFAULT 0,
"match_win" INT DEFAULT 0,
"match_lose" INT DEFAULT 0,
"match_draw" INT DEFAULT 0,
"rounds_won" INT DEFAULT 0,
"rounds_lost" INT DEFAULT 0,
"mvp" INT DEFAULT 0
);
INSERT INTO steam_user(steamid, personaname, lastlogoff, profileurl, avatar, avatarmedium,
avatarfull, realname, primaryclanid, timecreated, loccountrycode, gameid, created_at)
VALUES ('steamid','bozo',123,'kkk','a', 'b', 'c', 'yes', '13', 123, 'dd', 123, NOW());
INSERT INTO player_stats(player_steamid, map_id) VALUES ('76561198226912040',1);
`

// TODO: add fkeys (map id, steamid, ..)
30 changes: 23 additions & 7 deletions model/steam_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ type SteamUser struct {
TimeCreated int `json:"timecreated"`
LocCountryCode string `json:"loccountrycode"`
GameID int `json:"gameid"`
Created_At string `json:"created_at"`
Updated_At string `json:"updated_at"`
}

func GetSteamUser(steamID string) (SteamUser, error) {
user := SteamUser{}
err := db.Get(&user, "SELECT * FROM steam_user WHERE steamid = $1;", steamID)
return user, err
}

func CreateSteamUser(user SteamUser) error {
Expand All @@ -30,25 +38,33 @@ func CreateSteamUser(user SteamUser) error {
return UpdateSteamUser(user)
}

query := `INSERT INTO steam_user(steamid, personaname, lastlogoff, profileurl, avatar, avatarmedium, avatarfull, realname, primaryclanid, timecreated, loccountrycode, gameid) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12);`
query := `INSERT INTO steam_user(steamid, personaname, lastlogoff, profileurl, avatar, avatarmedium,
avatarfull, realname, primaryclanid, timecreated, loccountrycode, gameid, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);`

_, err = db.Exec(query, user.SteamID, user.PersonaName, user.LastLogOff, user.ProfileUrl, user.Avatar, user.AvatarMedium, user.AvatarFull, user.RealName, user.PrimaryClanID, user.TimeCreated, user.LocCountryCode, user.GameID)
_, err = db.Exec(query, user.SteamID, user.PersonaName, user.LastLogOff, user.ProfileUrl, user.Avatar, user.AvatarMedium,
user.AvatarFull, user.RealName, user.PrimaryClanID, user.TimeCreated, user.LocCountryCode, user.GameID, "NOW()")

if err != nil {
log.Printf("Error creating steam user @CreateSteamUser: %s\n", err.Error())
log.Printf("Error creating SteamUser @CreateSteamUser: %s\n", err.Error())
return err
}

return nil
}

func UpdateSteamUser(user SteamUser) error {
query := `UPDATE steam_user SET personaname = $1::text, lastlogoff = $2, profileurl = $3::text, avatar = $4::text, avatarmedium = $5::text, avatarfull = $6::text, realname = $7::text, primaryclanid = $8::text, timecreated = $9, loccountrycode = $10::text, gameid = $11 WHERE steamid=$12::text ;`
query := `UPDATE steam_user SET personaname = $1::text, lastlogoff = $2, profileurl = $3::text,
avatar = $4::text, avatarmedium = $5::text, avatarfull = $6::text, realname = $7::text,
primaryclanid = $8::text, timecreated = $9, loccountrycode = $10::text, gameid = $11, updated_at = NOW()
WHERE steamid=$12::text ;`

_, err = db.Exec(query, user.PersonaName, user.LastLogOff, user.ProfileUrl, user.Avatar, user.AvatarMedium, user.AvatarFull, user.RealName, user.PrimaryClanID, user.TimeCreated, user.LocCountryCode, user.GameID, user.SteamID)
_, err = db.Exec(query, user.PersonaName, user.LastLogOff, user.ProfileUrl,
user.Avatar, user.AvatarMedium, user.AvatarFull, user.RealName,
user.PrimaryClanID, user.TimeCreated, user.LocCountryCode, user.GameID, user.SteamID)

if err != nil {
log.Printf("Error updating steam user @UpdateSteamUser: %s\n", err.Error())
log.Printf("Error updating SteamUser @UpdateSteamUser: %s\n", err.Error())
return err
}

Expand All @@ -59,7 +75,7 @@ func DoesSteamUserExist(steamid string) (bool, error) {
var count int
err := db.QueryRow("SELECT COUNT(*) FROM steam_user WHERE steamid = '" + steamid + "';").Scan(&count)
if err != nil {
log.Printf("Error querying steam user @DoesSteamUserExist: %s\n", err.Error())
log.Printf("Error querying SteamUser @DoesSteamUserExist: %s\n", err.Error())
return false, err
}

Expand Down
Loading

0 comments on commit 533d860

Please sign in to comment.