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

added database, not working yet

parent 9f12b196
No related branches found
No related tags found
No related merge requests found
package main package main
import ( import (
"database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
...@@ -10,6 +11,7 @@ import ( ...@@ -10,6 +11,7 @@ import (
"sync" "sync"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"golang.org/x/crypto/bcrypt"
) )
/******************** DATA STRUCTS ***********************/ /******************** DATA STRUCTS ***********************/
...@@ -43,7 +45,7 @@ var ( ...@@ -43,7 +45,7 @@ var (
idCounter int idCounter int
idCounterMutex sync.RWMutex idCounterMutex sync.RWMutex
// database *sql.DB database *sql.DB
) )
/************** MAIN FUNCTION **********************/ /************** MAIN FUNCTION **********************/
...@@ -52,14 +54,19 @@ func main() { ...@@ -52,14 +54,19 @@ func main() {
// Initialise global variables // Initialise global variables
gameData = make(map[int]*Game) gameData = make(map[int]*Game)
// database, err := sql.Open("sqlite3", "./database.db") connStr := "dbname=bigtactoe sslmode=require"
// if err != nil { database, err := sql.Open("postgres", connStr)
// log.Fatal("could not connect to database") if err != nil {
// } log.Fatal("could not connect to database")
// defer database.Close() }
defer database.Close()
// statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT, wins INTEGER)") statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE, password TEXT, wins INTEGER)")
// statement.Exec() statement.Exec()
// test query
database.QueryRow("INSERT INTO users(username, password, wins) VALUES($1, $2, $3);",
"alex123", "qwerty", 0)
http.HandleFunc("/", hello) http.HandleFunc("/", hello)
...@@ -83,10 +90,15 @@ func main() { ...@@ -83,10 +90,15 @@ func main() {
/************************ HANDLERS ************************/ /************************ HANDLERS ************************/
func hello(w http.ResponseWriter, r *http.Request) { func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Big Tac Toe") fmt.Fprintf(w, "Welcome to Big Tac Toe")
} }
func move(w http.ResponseWriter, r *http.Request) { func move(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprintf(w, "Invalid request method")
return
}
jsonData := readJsonFromRequest(r) jsonData := readJsonFromRequest(r)
var move Move var move Move
...@@ -113,6 +125,12 @@ func move(w http.ResponseWriter, r *http.Request) { ...@@ -113,6 +125,12 @@ func move(w http.ResponseWriter, r *http.Request) {
// Creates a game with one player // Creates a game with one player
func createGame(w http.ResponseWriter, r *http.Request) { func createGame(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprintf(w, "Invalid request method")
return
}
jsonData := readJsonFromRequest(r) jsonData := readJsonFromRequest(r)
var playerData struct { var playerData struct {
...@@ -138,6 +156,12 @@ func createGame(w http.ResponseWriter, r *http.Request) { ...@@ -138,6 +156,12 @@ func createGame(w http.ResponseWriter, r *http.Request) {
// Adds a 2nd player to a game, given the game id // Adds a 2nd player to a game, given the game id
func joinGame(w http.ResponseWriter, r *http.Request) { func joinGame(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprintf(w, "Invalid request method")
return
}
jsonData := readJsonFromRequest(r) jsonData := readJsonFromRequest(r)
var join struct { var join struct {
...@@ -164,6 +188,12 @@ func joinGame(w http.ResponseWriter, r *http.Request) { ...@@ -164,6 +188,12 @@ func joinGame(w http.ResponseWriter, r *http.Request) {
// Returns if the 2nd player has joined the game yet // Returns if the 2nd player has joined the game yet
func checkJoinGame(w http.ResponseWriter, r *http.Request) { func checkJoinGame(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprintf(w, "Invalid request method")
return
}
jsonData := readJsonFromRequest(r) jsonData := readJsonFromRequest(r)
var gameID struct { var gameID struct {
...@@ -188,124 +218,111 @@ func checkJoinGame(w http.ResponseWriter, r *http.Request) { ...@@ -188,124 +218,111 @@ func checkJoinGame(w http.ResponseWriter, r *http.Request) {
} }
// /************** User authentication and other ****************/ // /************** User authentication and other ****************/
// func createUser(w http.ResponseWriter, r *http.Request) { func createUser(w http.ResponseWriter, r *http.Request) {
// jsonData := readJsonFromRequest(r) jsonData := readJsonFromRequest(r)
// var account struct { var account struct {
// Username string `json:"username"` Username string `json:"username"`
// Password string `json:"password"` Password string `json:"password"`
// } }
// err := json.Unmarshal(jsonData, &account) err := json.Unmarshal(jsonData, &account)
// if err != nil { if err != nil {
// log.Println("could not decode json data") log.Println("could not decode json data")
// } }
// // response will be an error message and success boolean // response will be an error message and success boolean
// response, ok := newAccount(account.Username, account.Password) response, ok := newAccount(account.Username, account.Password)
// if !ok { if !ok {
// fmt.Fprintf(w, response) fmt.Fprintf(w, response)
// } else { } else {
// fmt.Fprintf(w, account.Username) // if success, return the username fmt.Fprintf(w, account.Username) // if success, return the username
// } }
// } }
// func login(w http.ResponseWriter, r *http.Request) { func login(w http.ResponseWriter, r *http.Request) {
// jsonData := readJsonFromRequest(r) jsonData := readJsonFromRequest(r)
// var account struct { var account struct {
// Username string `json:"username"` Username string `json:"username"`
// Password string `json:"password"` Password string `json:"password"`
// } }
// err := json.Unmarshal(jsonData, &account) err := json.Unmarshal(jsonData, &account)
// if err != nil { if err != nil {
// log.Println("could not decode json data") log.Println("could not decode json data")
// } }
// // response will be the new user's ID if successful, otherwise, will be other message // response will be the new user's ID if successful, otherwise, will be other message
// authenticated := authenticate(account.Username, account.Password) authenticated := authenticate(account.Username, account.Password)
// if authenticated { if authenticated {
// fmt.Fprintf(w, "logged in") fmt.Fprintf(w, "logged in")
// } else { } else {
// fmt.Fprintf(w, "wrong password") fmt.Fprintf(w, "wrong password")
// } }
// } }
// // returns a map[username]wins as json // returns a map[username]wins as json
// func leaderboard(w http.ResponseWriter, r *http.Request) { func leaderboard(w http.ResponseWriter, r *http.Request) {
// usernames, ok := getLeaderboard() usernames, ok := getLeaderboard()
// if !ok { if !ok {
// fmt.Fprintf(w, "Could not get leaderboard") fmt.Fprintf(w, "Could not get leaderboard")
// return return
// } }
// jsonString, err := json.Marshal(usernames) jsonString, err := json.Marshal(usernames)
// if err != nil { if err != nil {
// log.Println("could not marshal leaderboard usernames into json") log.Println("could not marshal leaderboard usernames into json")
// } }
// w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
// w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
// w.Write(jsonString) w.Write(jsonString)
// } }
// /************** Database operations ****************/ /************** Database operations ****************/
// // Inserts new account into users table, returns true or false success and message // Inserts new account into users table, returns true or false success and message
// func newAccount(username string, password string) (string, bool) { func newAccount(username string, password string) (string, bool) {
// hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
// if err != nil { if err != nil {
// return "Internal server error occurred while hashing your password.", false return "Internal server error occurred while hashing your password.", false
// } }
// statement, _ := database.Prepare("INSERT INTO users (username, password, wins) VALUES (?, ?, ?)") var userID string
// defer statement.Close() err = database.QueryRow("INSERT INTO users(username, password, wins) VALUES($1, $2, $3) RETURNING id;",
// statement.Exec(username, hashedPassword, 0) username, hashedPassword, 0).Scan(&userID)
// if err != nil { if err != nil {
// return "That username has been taken", false return "That username has been taken", false
// } }
// return "", true return "", true
// } }
// // Authenticates a user, used to login. Returns true if successful // Authenticates a user, used to login. Returns true if successful
// func authenticate(username string, password string) bool { func authenticate(username string, password string) bool {
// var hashed []byte var hashed []byte
// // err := database.QueryRow("SELECT password FROM users WHERE username=$1;", database.QueryRow("SELECT password FROM users WHERE username=$1;",
// // username).Scan(&hashed) username).Scan(&hashed)
// // if err != nil {
// // return false err := bcrypt.CompareHashAndPassword(hashed, []byte(password))
// // } if err != nil {
return false
// statement, err := database.Prepare("select password from users where username = ?") }
// if err != nil { return true
// log.Fatal(err) }
// }
// defer statement.Close() func getLeaderboard() (map[string]int, bool) {
// err = statement.QueryRow(username).Scan(&hashed) rows, err := database.Query("SELECT username, wins FROM users;")
// if err != nil { if err != nil {
// log.Fatal(err) return nil, false
// } }
var usernames map[string]int
// err = bcrypt.CompareHashAndPassword(hashed, []byte(password)) for rows.Next() {
// if err != nil { var username string
// return false var wins int64
// } rows.Scan(&username, &wins)
// return true usernames[username] = int(wins)
// } }
return usernames, 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
// }
/************** Helper functions *******************/ /************** Helper functions *******************/
......
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