Skip to content
Snippets Groups Projects
Commit 920f534d authored by Alex Constantin-Gomez's avatar Alex Constantin-Gomez
Browse files

removed database related code

parent 70ad092e
No related branches found
No related tags found
No related merge requests found
...@@ -7,12 +7,8 @@ import ( ...@@ -7,12 +7,8 @@ import (
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
"os"
"strconv" "strconv"
"sync" "sync"
_ "github.com/lib/pq"
"golang.org/x/crypto/bcrypt"
) )
/******************** DATA STRUCTS ***********************/ /******************** DATA STRUCTS ***********************/
...@@ -55,20 +51,6 @@ func main() { ...@@ -55,20 +51,6 @@ func main() {
// Initialise global variables // Initialise global variables
gameData = make(map[int]*Game) gameData = make(map[int]*Game)
connStr := "user=btt password='" + os.Getenv("BTT_PASSWORD") + "' dbname=bigtactoe sslmode=require"
database, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal("could not connect to database")
}
defer database.Close()
// statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE, password TEXT, wins INTEGER, losses INTEGER, draws INTEGER)")
// statement.Exec()
// // test query
// database.QueryRow("INSERT INTO users(username, password, wins) VALUES($1, $2, $3);",
// "user123", "qwerty", 0)
http.HandleFunc("/", hello) http.HandleFunc("/", hello)
// Game processing endpoints // Game processing endpoints
...@@ -77,12 +59,7 @@ func main() { ...@@ -77,12 +59,7 @@ func main() {
http.HandleFunc("/join", joinGame) http.HandleFunc("/join", joinGame)
http.HandleFunc("/wait", checkJoinGame) http.HandleFunc("/wait", checkJoinGame)
// User authentication endpoints err := http.ListenAndServe(":8080", nil)
http.HandleFunc("/create-account", createUser)
http.HandleFunc("/login", login)
http.HandleFunc("/leaderboard", leaderboard)
err = http.ListenAndServe(":8080", nil)
if err != nil { if err != nil {
log.Println("could not start server") log.Println("could not start server")
} }
...@@ -221,126 +198,6 @@ func checkJoinGame(w http.ResponseWriter, r *http.Request) { ...@@ -221,126 +198,6 @@ func checkJoinGame(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, p2) // send player2's name fmt.Fprintf(w, p2) // send player2's name
} }
// /************** User authentication and other ****************/
func createUser(w http.ResponseWriter, r *http.Request) {
jsonData := readJsonFromRequest(r)
var account struct {
Username string `json:"username"`
Password string `json:"password"`
}
err := json.Unmarshal(jsonData, &account)
if err != nil {
fmt.Fprintf(w, "could not decode json data")
return
}
// response will be an error message and success boolean
response, ok := newAccount(account.Username, account.Password)
if !ok {
fmt.Fprintf(w, response)
} else {
fmt.Fprintf(w, account.Username) // if success, return the username
}
}
func login(w http.ResponseWriter, r *http.Request) {
jsonData := readJsonFromRequest(r)
var account struct {
Username string `json:"username"`
Password string `json:"password"`
}
err := json.Unmarshal(jsonData, &account)
if err != nil {
fmt.Fprintf(w, "could not decode json data")
return
}
// response will be the new user's ID if successful, otherwise, will be other message
authenticated := authenticate(account.Username, account.Password)
if authenticated {
fmt.Fprintf(w, "logged in")
} else {
fmt.Fprintf(w, "wrong password")
}
}
// returns a map[username]wins as json
func leaderboard(w http.ResponseWriter, r *http.Request) {
usernames, ok := getLeaderboard()
if !ok {
fmt.Fprintf(w, "Could not get leaderboard")
return
}
jsonString, err := json.Marshal(usernames)
if err != nil {
fmt.Fprintf(w, "could not marshal leaderboard usernames into json")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write(jsonString)
}
/************** Database operations ****************/
// Inserts new account into users table, returns true or false success and message
func newAccount(username string, password string) (string, bool) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "Internal server error occurred while hashing your password.", false
}
var userID string
err = database.QueryRow("INSERT INTO users(username, password, wins) VALUES($1, $2, $3) RETURNING id;",
username, hashedPassword, 0).Scan(&userID)
if err != nil {
return "That username has been taken", false
}
return "", true
}
// Authenticates a user, used to login. Returns true if successful
func authenticate(username string, password string) bool {
var hashed []byte
database.QueryRow("SELECT password FROM users WHERE username=$1;",
username).Scan(&hashed)
err := bcrypt.CompareHashAndPassword(hashed, []byte(password))
if err != nil {
return false
}
return true
}
func getLeaderboard() (map[string]int, bool) {
rows, err := database.Query("SELECT username, wins FROM users;")
if err != nil {
return nil, false
}
var usernames map[string]int
for rows.Next() {
var username string
var wins int64
rows.Scan(&username, &wins)
usernames[username] = int(wins)
}
return usernames, true
}
func incrementWins(username string) (int, bool) {
var wins int
err := database.QueryRow("UPDATE users SET wins=wins+1 WHERE username=$1 RETURNING wins;",
username).Scan(&wins)
if err != nil {
return -1, false
}
return wins, true
}
/************** Helper functions *******************/ /************** Helper functions *******************/
func generateID() int { func generateID() int {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment