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

Commit

Permalink
more auth stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
roby2014 committed Feb 24, 2022
1 parent c17aa61 commit c94a4ad
Show file tree
Hide file tree
Showing 9 changed files with 201 additions and 12 deletions.
16 changes: 16 additions & 0 deletions config/store.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"fmt"
"net/http"

"github.com/gorilla/sessions"
Expand All @@ -18,3 +19,18 @@ func CreateSessionID(w http.ResponseWriter, r *http.Request, value string) error
session.Values["session-id"] = value
return session.Save(r, w)
}

func RemoveSessionID(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: SESSION_NAME,
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)
}

func GetSessionID(r *http.Request) string {
session, _ := Store.Get(r, SESSION_NAME)
return fmt.Sprintf("%s", session.Values["session-id"])
}
16 changes: 11 additions & 5 deletions controller/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,24 @@ func Login(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, opId.AuthUrl(), http.StatusTemporaryRedirect)
default:
// login success

// get user
user, err := opId.ValidateAndGetUser(config.STEAM_API_KEY)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

config.CreateSessionID(w, r, user.SteamId)

// TODO: store user info in database
if err = CreateSteamUser(user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

config.CreateSessionID(w, r, user.SteamId)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)
}
}

func Logout(w http.ResponseWriter, r *http.Request) {
config.RemoveSessionID(w, r)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
24 changes: 24 additions & 0 deletions controller/steam_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package controller

import (
"log"

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

func CreateSteamUser(user *steam_go.PlayerSummaries) error {
return model.CreateSteamUser(utils.PlayerSummariesToSteamUser(user))
}

func UpdateSteamUser(steamID string) error {
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
}

return model.UpdateSteamUser(utils.PlayerSummariesToSteamUser(updatedUser))
}
8 changes: 3 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@ go 1.17
require (
github.com/gorilla/mux v1.8.0
github.com/gorilla/sessions v1.2.1
github.com/joho/godotenv v1.4.0
github.com/lib/pq v1.10.4
github.com/solovev/steam_go v0.0.0-20170222182106-48eb5aae6c50

)

require (
github.com/gorilla/securecookie v1.1.1 // indirect
github.com/joho/godotenv v1.4.0 // indirect
github.com/lib/pq v1.10.4 // indirect
)
require github.com/gorilla/securecookie v1.1.1 // indirect
8 changes: 8 additions & 0 deletions middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net/http"

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

// Authentication middleware called on routes that need to know if user is logged in.
Expand All @@ -13,6 +14,13 @@ func IsAuthenticated(h func(w http.ResponseWriter, r *http.Request)) http.Handle
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 {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

http.Redirect(w, r, "/", http.StatusFound)
return
}
Expand Down
24 changes: 22 additions & 2 deletions model/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import (
)

var db *sql.DB
var err error

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

log.Printf("Database connection done successfully\n")
_, 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
);`)
if err != nil {
log.Fatalf("Error: Could not create table steam_users: %s\n", err.Error())
}

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

// Return a string for our db connection info
Expand Down
71 changes: 71 additions & 0 deletions model/steam_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package model

import (
"log"
)

type SteamUser struct {
ID uint64 `json:"id"`
SteamID string `json:"steamid"`
PersonaName string `json:"personaname"`
LastLogOff int `json:"lastlogoff"`
ProfileUrl string `json:"profileurl"`
Avatar string `json:"avatar"`
AvatarMedium string `json:"avatarmedium"`
AvatarFull string `json:"avatarfull"`
RealName string `json:"realname"`
PrimaryClanID string `json:"primaryclanid"`
TimeCreated int `json:"timecreated"`
LocCountryCode string `json:"loccountrycode"`
GameID int `json:"gameid"`
}

func CreateSteamUser(user SteamUser) error {
userExists, err := DoesSteamUserExist(user.SteamID)
if err != nil {
return err
}

if userExists {
return nil
}

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);`

_, 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)

if err != nil {
log.Printf("Error creating steam user @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 ;`

_, 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())
return err
}

return nil
}

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())
return false, err
}

if count == 0 {
return false, nil
} else {
return true, nil
}
}
1 change: 1 addition & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ func setupRouter() {
router = mux.NewRouter()
router.HandleFunc("/", controller.Home)
router.Handle("/login", middleware.IsAuthenticated(controller.Login))
router.HandleFunc("/logout", controller.Logout)
}
45 changes: 45 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package utils

import (
"github.com/robyzzz/csl-backend/model"
"github.com/solovev/steam_go"
)

// Converts PlayerSummaries to SteamUser
func PlayerSummariesToSteamUser(user *steam_go.PlayerSummaries) model.SteamUser {
return model.SteamUser{
ID: 0,
SteamID: user.SteamId,
PersonaName: user.PersonaName,
LastLogOff: user.LastLogOff,
ProfileUrl: user.ProfileUrl,
Avatar: user.Avatar,
AvatarMedium: user.AvatarMedium,
AvatarFull: user.AvatarFull,
RealName: user.RealName,
PrimaryClanID: user.PrimaryClanId,
TimeCreated: user.TimeCreated,
LocCountryCode: user.LocCountryCode,
GameID: user.GameId,
}
}

type PlayerSumm steam_go.PlayerSummaries

func (user *PlayerSumm) ToSteamUser() model.SteamUser {
return model.SteamUser{
ID: 0,
SteamID: user.SteamId,
PersonaName: user.PersonaName,
LastLogOff: user.LastLogOff,
ProfileUrl: user.ProfileUrl,
Avatar: user.Avatar,
AvatarMedium: user.AvatarMedium,
AvatarFull: user.AvatarFull,
RealName: user.RealName,
PrimaryClanID: user.PrimaryClanId,
TimeCreated: user.TimeCreated,
LocCountryCode: user.LocCountryCode,
GameID: user.GameId,
}
}

0 comments on commit c94a4ad

Please sign in to comment.