Files
games-wishlist/main.go

303 lines
7.1 KiB
Go

package main
import (
"embed"
"encoding/json"
"fmt"
"game-wishlist/auth"
"game-wishlist/model"
"log"
"net/http"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/joho/godotenv"
"golang.org/x/crypto/bcrypt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var (
//go:embed web/dist
webOutput embed.FS
)
func sendError(w http.ResponseWriter, msg string, err error, status int) {
m := msg
if err != nil {
m = fmt.Sprintf("%s: %v", msg, err)
}
http.Error(w, m, status)
}
func sendJSON(w http.ResponseWriter, data any, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(data); err != nil {
http.Error(w, err.Error(), 500)
}
}
func main() {
godotenv.Load()
dbPath := os.Getenv("DB_PATH")
if dbPath == "" {
dbPath = "./sqlite.db"
}
db, err := gorm.Open(sqlite.Open(dbPath))
if err != nil {
log.Fatalf("failed to connect to db: %v\n", err)
}
if err := db.AutoMigrate(model.User{}, model.Game{}); err != nil {
log.Fatalf("failed to automigrate db: %v\n", err)
}
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/" {
path = "/index.html"
}
filePath := "web/dist" + path
http.ServeFileFS(w, r, webOutput, filePath)
})
mux.HandleFunc("POST /api/auth/register", func(w http.ResponseWriter, r *http.Request) {
var body struct {
Login string `json:"login"`
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
sendError(w, "invalid request body", err, 400)
return
}
if body.Login == "" || body.Password == "" {
sendError(w, "invalid request, login and password required", nil, 400)
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(body.Password), 10)
if err != nil {
sendError(w, "failed to hash password", err, 500)
return
}
user := &model.User{
Login: body.Login,
Password: string(hash),
}
if tx := db.Create(user); tx.Error != nil {
sendError(w, "failed to create user", tx.Error, 400)
return
}
expiryTime := time.Now().Add(time.Hour * 24 * 7) // 1 week lifetime
token, err := auth.GenerateUserToken(int64(user.ID), expiryTime)
if err != nil {
sendError(w, "failed to generate user token", err, 500)
return
}
auth.SetUserCookie(w, token, expiryTime)
sendJSON(w, user, 201)
})
mux.HandleFunc("POST /api/auth/login", func(w http.ResponseWriter, r *http.Request) {
var body struct {
Login string `json:"login"`
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
sendError(w, "invalid request body", err, 400)
return
}
if body.Login == "" || body.Password == "" {
sendError(w, "invalid request, login and password required", nil, 400)
return
}
user := &model.User{}
if tx := db.First(user, "login = ?", body.Login); tx.Error != nil {
sendError(w, "login not found", tx.Error, 400)
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(body.Password)); err != nil {
sendError(w, "invalid password", err, 400)
return
}
expiryTime := time.Now().Add(time.Hour * 24 * 7) // 1 week lifetime
token, err := auth.GenerateUserToken(int64(user.ID), expiryTime)
if err != nil {
sendError(w, "failed to generate user token", err, 500)
return
}
auth.SetUserCookie(w, token, expiryTime)
sendJSON(w, user, 200)
})
mux.HandleFunc("POST /api/auth/logout", func(w http.ResponseWriter, r *http.Request) {
auth.RemoveUserCookie(w)
sendJSON(w, struct {
Ok bool `json:"ok"`
}{true}, 200)
})
mux.HandleFunc("GET /api/user", func(w http.ResponseWriter, r *http.Request) {
userId, err := auth.GetUserIdFromRequest(r)
if err != nil {
sendError(w, "invalid token", err, 401)
return
}
user := &model.User{}
if tx := db.Preload("Games").First(user, "id = ?", userId); tx.Error != nil {
sendError(w, "user not found", err, 404)
return
}
sendJSON(w, user, 200)
})
mux.HandleFunc("GET /api/search/games", func(w http.ResponseWriter, r *http.Request) {
req, err := http.NewRequest("GET", "https://store.steampowered.com/search/", nil)
if err != nil {
sendError(w, "failed to construct api request", err, 500)
return
}
q := req.URL.Query()
q.Set("term", r.URL.Query().Get("q"))
req.URL.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(req)
if err != nil {
sendError(w, "failed to query api", err, 500)
return
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
sendError(w, "failed to parse html", err, 500)
return
}
type game struct {
Name string `json:"name"`
SteamAppID int `json:"steamAppId"`
Image string `json:"image"`
ReleaseDate string `json:"releaseDate"`
}
games := []game{}
doc.Find(`#search_resultsRows > a`).Each(func(i int, s *goquery.Selection) {
name := s.Find(".search_name > .title").Text()
appId := s.AttrOr("data-ds-appid", "")
if appId == "" {
return
}
id, err := strconv.Atoi(appId)
if err != nil {
return
}
image := s.Find(".search_capsule > img").AttrOr("src", "")
if image == "" {
return
}
releaseDate := s.Find(".search_released").Text()
games = append(games, game{
Name: name,
SteamAppID: id,
Image: image,
ReleaseDate: strings.TrimSpace(releaseDate),
})
})
sendJSON(w, games, 200)
})
mux.HandleFunc("POST /api/user/games", func(w http.ResponseWriter, r *http.Request) {
userId, err := auth.GetUserIdFromRequest(r)
if err != nil {
sendError(w, "unauthorized", err, 401)
return
}
user := &model.User{}
if tx := db.Preload("Games").First(user, "id = ?", userId); tx.Error != nil {
sendError(w, "user not found", err, 404)
return
}
var body struct {
SteamAppID int `json:"steamAppId"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
sendError(w, "invalid request", err, 400)
return
}
if body.SteamAppID == 0 {
sendError(w, "steam appid is required", nil, 400)
return
}
game, err := getSteamGameDetails(body.SteamAppID)
if err != nil {
sendError(w, "steam game not found", err, 404)
return
}
if tx := db.First(&model.Game{SteamAppID: game.SteamAppID}); tx.Error != nil {
// game doesn't exist in db, gonna create it real quick
if tx := db.Create(game); tx.Error != nil {
sendError(w, "failed to create game", err, 400)
return
}
}
alreadyHasGame := !slices.ContainsFunc(user.Games, func(g model.Game) bool {
return g.SteamAppID == game.SteamAppID
})
if !alreadyHasGame {
// user already has this game on the wishlist
sendError(w, "game is already on the wishlist", nil, 400)
return
}
user.Games = append(user.Games, *game)
if tx := db.Save(user); tx.Error != nil {
sendError(w, "failed to add game to user object", tx.Error, 500)
return
}
sendJSON(w, user, 200)
})
log.Print("starting http server on http://localhost:5000")
if err := http.ListenAndServe(":5000", mux); err != nil {
log.Fatalf("failed to start http server: %v\n", err)
}
}