Compare commits
14
Commits
94d377c0c2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b28cf38e99 | ||
|
|
8823fa808a
|
||
|
|
1e27d7629f
|
||
|
|
cefa98cdec
|
||
|
|
7f7ac559ac | ||
|
|
6ec8b00eb6 | ||
|
|
ed826ac810 | ||
|
|
4d93d4332e | ||
|
|
0c2a8f3d98 | ||
|
|
bdbf33098f | ||
|
|
3da7f369a5 | ||
|
|
169c4faa7d | ||
|
|
652b391d6f | ||
|
|
ac99cef842 |
@@ -2,3 +2,4 @@
|
|||||||
tmp.*
|
tmp.*
|
||||||
*.log
|
*.log
|
||||||
.env
|
.env
|
||||||
|
p.vim
|
||||||
|
|||||||
@@ -37,6 +37,15 @@ Metrics/MethodLength:
|
|||||||
Metrics/ClassLength:
|
Metrics/ClassLength:
|
||||||
Enabled: false
|
Enabled: false
|
||||||
|
|
||||||
|
Metrics/BlockLength:
|
||||||
|
Enabled: false
|
||||||
|
|
||||||
|
Layout/FirstHashElementIndentation:
|
||||||
|
Enabled: false
|
||||||
|
|
||||||
|
Layout/FirstArrayElementIndentation:
|
||||||
|
Enabled: false
|
||||||
|
|
||||||
Layout/EmptyLineAfterGuardClause:
|
Layout/EmptyLineAfterGuardClause:
|
||||||
Enabled: false
|
Enabled: false
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
source "https://rubygems.org"
|
|
||||||
|
|
||||||
gem "base64"
|
|
||||||
gem "json"
|
|
||||||
gem "net-http"
|
|
||||||
gem "sequel"
|
|
||||||
gem "sinatra"
|
|
||||||
gem "uri"
|
|
||||||
gem "xxhash"
|
|
||||||
gem "zlib"
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
GEM
|
|
||||||
remote: https://rubygems.org/
|
|
||||||
specs:
|
|
||||||
base64 (0.3.0)
|
|
||||||
bigdecimal (3.2.2)
|
|
||||||
json (2.12.2)
|
|
||||||
logger (1.7.0)
|
|
||||||
mustermann (3.0.3)
|
|
||||||
ruby2_keywords (~> 0.0.1)
|
|
||||||
net-http (0.6.0)
|
|
||||||
uri
|
|
||||||
rack (3.1.16)
|
|
||||||
rack-protection (4.1.1)
|
|
||||||
base64 (>= 0.1.0)
|
|
||||||
logger (>= 1.6.0)
|
|
||||||
rack (>= 3.0.0, < 4)
|
|
||||||
rack-session (2.1.1)
|
|
||||||
base64 (>= 0.1.0)
|
|
||||||
rack (>= 3.0.0)
|
|
||||||
ruby2_keywords (0.0.5)
|
|
||||||
sequel (5.93.0)
|
|
||||||
bigdecimal
|
|
||||||
sinatra (4.1.1)
|
|
||||||
logger (>= 1.6.0)
|
|
||||||
mustermann (~> 3.0)
|
|
||||||
rack (>= 3.0.0, < 4)
|
|
||||||
rack-protection (= 4.1.1)
|
|
||||||
rack-session (>= 2.0.0, < 3)
|
|
||||||
tilt (~> 2.0)
|
|
||||||
tilt (2.6.0)
|
|
||||||
uri (1.0.3)
|
|
||||||
xxhash (0.6.0)
|
|
||||||
zlib (3.2.1)
|
|
||||||
|
|
||||||
PLATFORMS
|
|
||||||
ruby
|
|
||||||
x86_64-linux
|
|
||||||
|
|
||||||
DEPENDENCIES
|
|
||||||
base64
|
|
||||||
json
|
|
||||||
net-http
|
|
||||||
sequel
|
|
||||||
sinatra
|
|
||||||
uri
|
|
||||||
xxhash
|
|
||||||
zlib
|
|
||||||
|
|
||||||
BUNDLED WITH
|
|
||||||
2.6.9
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Infinsweeper Game.
|
||||||
|
|
||||||
|
It's like minesweeper, but with an infinite board.
|
||||||
|
|
||||||
|
The web-app is here: [infinsweeper.syedm.dev](https://infinsweeper.syedm.dev/)
|
||||||
|
|
||||||
|
## Working
|
||||||
|
|
||||||
|
- This game has some crazy optimizations.
|
||||||
|
- It uses cryptography hashes of a seed provided to the game api (randomly generated) and uses that with the cell index to generate the board.
|
||||||
|
- This allows for not having to save board data if it is off the screen if that area is maked as solved.
|
||||||
|
- When bought back into view it will be re-generated with the same seed.
|
||||||
|
- It also uses compression algorithms to store compressed form of the data in the browser storage.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Also has full account control with email and password and resets and everything necessary.
|
||||||
|
- It originally aims to be an example of a full stack web-app, but now it's just a game.
|
||||||
|
- The full sinatra based web-app can be hosted using this repo.
|
||||||
|
- It also has a ton of animations made using pure JavaScript Canvas API.
|
||||||
|
- The entire game is made using just the JS Canvas API while the backend is made using Sinatra (Ruby) and SQLite.
|
||||||
|
|
||||||
|
## A screenshot
|
||||||
|
|
||||||
|

|
||||||
@@ -1,30 +0,0 @@
|
|||||||
set pipe_path /tmp/infin
|
|
||||||
set oldsum (cat (find . \( -name '*.rb' -o -name '*.js' \) | sort) | md5sum)
|
|
||||||
if not test -e infinsweeper.db
|
|
||||||
sqlite3 infinsweeper.db < schema.sql
|
|
||||||
end
|
|
||||||
pkill ruby
|
|
||||||
ruby main.rb -p8080 &
|
|
||||||
echo "" > $pipe_path
|
|
||||||
while true
|
|
||||||
sleep 1
|
|
||||||
set newsum (cat (find . \( -name '*.rb' -o -name '*.js' \) | sort) | md5sum)
|
|
||||||
echo $newsum $oldsum
|
|
||||||
if test "$oldsum" != "$newsum"
|
|
||||||
set oldsum $newsum
|
|
||||||
pkill ruby
|
|
||||||
ruby main.rb -p8080 &
|
|
||||||
end
|
|
||||||
if set line (cat $pipe_path)
|
|
||||||
echo $line
|
|
||||||
if test "$line" = "die"
|
|
||||||
pkill ruby
|
|
||||||
echo "" > $pipe_path
|
|
||||||
exit
|
|
||||||
end
|
|
||||||
if test "$line" = "open"
|
|
||||||
echo "" > $pipe_path
|
|
||||||
xdg-open http://localhost:8080
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
Generated
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1790185690,
|
||||||
|
"narHash": "sha256-xJ+X4hBtOcAFGBOe5nAMyMUeF9foJBmIOu3NjBqBycU=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "4975466d324710c576dc11ad614684e6bd8cad8e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
description = "Infinsweeper";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs =
|
||||||
|
{ nixpkgs, ... }:
|
||||||
|
let
|
||||||
|
system = "x86_64-linux";
|
||||||
|
pkgs = nixpkgs.legacyPackages.${system};
|
||||||
|
|
||||||
|
ruby = pkgs.ruby.withPackages (
|
||||||
|
p: with p; [
|
||||||
|
sqlite3
|
||||||
|
sequel
|
||||||
|
rackup
|
||||||
|
puma
|
||||||
|
sinatra
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
app = pkgs.stdenv.mkDerivation {
|
||||||
|
pname = "infinsweeper";
|
||||||
|
version = "0.1.0";
|
||||||
|
src = ./.;
|
||||||
|
buildInputs = [ ruby ];
|
||||||
|
installPhase = ''
|
||||||
|
mkdir -p $out
|
||||||
|
cp -r . $out/
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
|
||||||
|
server = pkgs.writeShellApplication {
|
||||||
|
name = "infinsweeper";
|
||||||
|
runtimeInputs = [ ruby ];
|
||||||
|
text = ''
|
||||||
|
set -euo pipefail
|
||||||
|
export DB="''${INFINSWEEPER_DB:-/var/lib/infinsweeper.db}"
|
||||||
|
exec ruby ${app}/main.rb
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
packages.${system}.default = app;
|
||||||
|
|
||||||
|
apps.${system}.default = {
|
||||||
|
type = "app";
|
||||||
|
program = "${server}/bin/infinsweeper";
|
||||||
|
};
|
||||||
|
|
||||||
|
devShells.${system}.default = pkgs.mkShell {
|
||||||
|
packages = [
|
||||||
|
ruby
|
||||||
|
pkgs.sqlite
|
||||||
|
];
|
||||||
|
|
||||||
|
env.INFINSWEEPER_DB = "./infinsweeper.db";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
require "xxhash"
|
|
||||||
|
|
||||||
# Game logic main class
|
# Game logic main class
|
||||||
class GameLogic
|
class GameLogic
|
||||||
attr_reader :pos
|
attr_reader :pos
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
+46
-12
@@ -6,9 +6,18 @@
|
|||||||
<meta
|
<meta
|
||||||
name="viewport"
|
name="viewport"
|
||||||
content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
|
content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
|
||||||
|
/>
|
||||||
|
<meta name="signed_in" content="<%= @signed_in %>">
|
||||||
|
<meta name="csrf" content="<%= @csrf_token %>">
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link
|
||||||
|
href="https://fonts.googleapis.com/css2?family=WDXL+Lubrifont+JP+N&display=swap"
|
||||||
|
rel="stylesheet"
|
||||||
/>
|
/>
|
||||||
<link rel="stylesheet" href="src/assets/style.css" />
|
<link rel="stylesheet" href="src/assets/style.css" />
|
||||||
<script type="module" src="src/js/accounts.js"></script>
|
<script type="module" src="src/js/accounts.js"></script>
|
||||||
|
<script type="module" src="src/js/game.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="header">
|
<div class="header">
|
||||||
@@ -20,39 +29,63 @@
|
|||||||
/>
|
/>
|
||||||
</a>
|
</a>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
|
<button class="account-button" id="reset-button">RESET GAME</button>
|
||||||
|
<button class="account-button" id="logout-button">LOGOUT</button>
|
||||||
<button class="account-button" id="login-button">LOGIN</button>
|
<button class="account-button" id="login-button">LOGIN</button>
|
||||||
<button class="account-button" id="signup-button">SIGN UP</button>
|
<button class="account-button" id="signup-button">SIGN UP</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<span id="message"><%= @message %></span>
|
||||||
<canvas id="main-canvas"></canvas>
|
<canvas id="main-canvas"></canvas>
|
||||||
<script type="module" src="src/js/game.js"></script>
|
<div class="popup" id="popup">
|
||||||
<div class="popup">
|
<span class="close" id="close">×</span>
|
||||||
<div class="popup-tab" id="login">
|
<div class="popup-tab" id="login">
|
||||||
<span class="info" id="login-info"></span>
|
|
||||||
<form id="login-form" class="form">
|
<form id="login-form" class="form">
|
||||||
|
<label for="username">USERNAME</label>
|
||||||
<input type="text" name="username" placeholder="Username" required />
|
<input type="text" name="username" placeholder="Username" required />
|
||||||
|
<label for="pass">PASSWORD</label>
|
||||||
<input type="password" name="pass" placeholder="Password" required />
|
<input type="password" name="pass" placeholder="Password" required />
|
||||||
<button type="submit">Login</button>
|
<button type="submit">LOGIN</button>
|
||||||
|
<span class="link" id="forgot-link">Forgot password?</span>
|
||||||
|
<span class="info" id="login-info"></span>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
<div class="popup-tab" id="signup">
|
<div class="popup-tab" id="signup">
|
||||||
<form id="signup-form" class="form">
|
<form id="signup-form" class="form">
|
||||||
<span class="info" id="signup-info"></span>
|
<label for="username">USERNAME</label>
|
||||||
<input type="text" name="username" placeholder="Username" required />
|
<input type="text" name="username" placeholder="Username" required />
|
||||||
<input type="email" name="email" placeholder="Email" required />
|
<label for="email">EMAIL</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
name="email"
|
||||||
|
placeholder="Email"
|
||||||
|
required
|
||||||
|
autocapitalize="off"
|
||||||
|
/>
|
||||||
|
<label for="pass">PASSWORD</label>
|
||||||
<input type="password" name="pass" placeholder="Password" required />
|
<input type="password" name="pass" placeholder="Password" required />
|
||||||
<button type="submit">Sign Up</button>
|
<button type="submit">SIGN UP</button>
|
||||||
|
<span class="info" id="signup-info"></span>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="popup-tab" id="settings">
|
||||||
|
<!-- TODO: settings -->
|
||||||
|
</div>
|
||||||
<div class="popup-tab" id="forgot-pass">
|
<div class="popup-tab" id="forgot-pass">
|
||||||
<span class="info" id="forgot-info"></span>
|
|
||||||
<form id="forgot-form" class="form">
|
<form id="forgot-form" class="form">
|
||||||
<input type="email" name="email" placeholder="Email" />
|
<input
|
||||||
<button type="submit">Submit</button>
|
type="email"
|
||||||
|
name="email"
|
||||||
|
placeholder="Email"
|
||||||
|
required
|
||||||
|
autocapitalize="off"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<button type="submit">SUBMIT</button>
|
||||||
|
<span class="info" id="forgot-info"></span>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
<div class="popup-tab" id="reset-pass">
|
<div class="popup-tab" id="reset-pass">
|
||||||
<span class="info" id="reset-info"></span>
|
|
||||||
<form id="reset-form" class="form">
|
<form id="reset-form" class="form">
|
||||||
<input type="password" name="pass" placeholder="Password" required />
|
<input type="password" name="pass" placeholder="Password" required />
|
||||||
<input
|
<input
|
||||||
@@ -61,7 +94,8 @@
|
|||||||
placeholder="Confirm Password"
|
placeholder="Confirm Password"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<button type="submit">Submit</button>
|
<button type="submit">SUBMIT</button>
|
||||||
|
<span class="info" id="reset-info"></span>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
# module for logging
|
# module for logging
|
||||||
module Logman
|
module Logman
|
||||||
def self.log(log)
|
def self.log(log)
|
||||||
File.write("log/main.log", "[#{Time.now}] #{log}\n", mode: "a")
|
file, line = caller(1, 1)[0].split(":")
|
||||||
|
File.write("log/main.log", "[#{Time.now}] {#{file}:#{line}} #{log}\n", mode: "a") if ENV["ENV"] == "dev"
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.imp(log)
|
def self.imp(log)
|
||||||
File.write("log/imp.log", "[#{Time.now}] #{log}\n", mode: "a")
|
File.write("log/imp.log", "[#{Time.now}] #{log}\n", mode: "a") if ENV["ENV"] == "dev"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
# Mailer module
|
# Mailer module
|
||||||
|
|
||||||
module Mail
|
module Mail
|
||||||
def send(to, subject, body)
|
def send(to, subject, body)
|
||||||
from_email = "infinsweeper@syedm.dev"
|
from_email = "infinsweeper@domain.com"
|
||||||
from_name = "InfinSweeper"
|
from_name = "InfinSweeper"
|
||||||
to = Array(to).map { |addr| { email_address: { address: addr, name: "" } } }
|
to = Array(to).map { |addr| { email_address: { address: addr, name: "" } } }
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ module Mail
|
|||||||
|
|
||||||
uri = URI("https://api.zeptomail.com/v1.1/email")
|
uri = URI("https://api.zeptomail.com/v1.1/email")
|
||||||
req = Net::HTTP::Post.new(uri)
|
req = Net::HTTP::Post.new(uri)
|
||||||
req["Authorization"] = "Zoho-enczapikey #{ENV_HASH["ZOHO_PASS"]}"
|
req["Authorization"] = "Zoho-enczapikey #{ENV["ZOHO_PASS"]}"
|
||||||
req["Content-Type"] = "application/json"
|
req["Content-Type"] = "application/json"
|
||||||
req.body = payload.to_json
|
req.body = payload.to_json
|
||||||
|
|
||||||
@@ -27,5 +28,6 @@ module Mail
|
|||||||
|
|
||||||
return if response.is_a?(Net::HTTPSuccess)
|
return if response.is_a?(Net::HTTPSuccess)
|
||||||
Logman.imp "[ZeptoMail ERROR] #{response.body}"
|
Logman.imp "[ZeptoMail ERROR] #{response.body}"
|
||||||
|
raise "Email failed."
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,42 +1,56 @@
|
|||||||
require "base64"
|
require "base64"
|
||||||
|
require "erb"
|
||||||
require "json"
|
require "json"
|
||||||
require "net/http"
|
require "net/http"
|
||||||
require "sequel"
|
require "sequel"
|
||||||
require "sinatra"
|
require "sinatra"
|
||||||
require "uri"
|
require "uri"
|
||||||
require "xxhash"
|
|
||||||
require "zlib"
|
require "zlib"
|
||||||
|
|
||||||
ALPHANUM = [*"0".."9", *"A".."Z", *"a".."z", "-", "_"].freeze
|
ALPHANUM = [*"0".."9", *"A".."Z", *"a".."z", "-", "_"].freeze
|
||||||
|
|
||||||
env_data = File.read(".env")
|
load "logman.rb"
|
||||||
ENV_HASH = {}
|
# Logman.log ENV.inspect
|
||||||
|
|
||||||
env_data.each_line do |line|
|
db_file = File.expand_path(ENV.fetch("INFINSWEEPER_DB", "infinsweeper.db"))
|
||||||
if (match = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/))
|
puts db_file
|
||||||
_, key, val = match
|
|
||||||
ENV_HASH[key] = val
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
CODE_ENV = :dev
|
|
||||||
|
|
||||||
db_file = File.expand_path("infinsweeper.db")
|
|
||||||
DB = Sequel.connect("sqlite:///#{db_file}", single_threaded: false)
|
DB = Sequel.connect("sqlite:///#{db_file}", single_threaded: false)
|
||||||
DB.run("PRAGMA foreign_keys = ON;")
|
DB.run("PRAGMA foreign_keys = ON;")
|
||||||
|
DB.create_table? :Players do
|
||||||
|
String :username, primary_key: true
|
||||||
|
String :email, unique: true
|
||||||
|
File :digest
|
||||||
|
File :data
|
||||||
|
String :activation_code
|
||||||
|
String :new_pass_code
|
||||||
|
DateTime :created_at, default: Sequel::CURRENT_TIMESTAMP
|
||||||
|
end
|
||||||
|
DB.create_table? :SignedInUsers do
|
||||||
|
String :code, primary_key: true
|
||||||
|
String :player
|
||||||
|
DateTime :created_at, default: Sequel::CURRENT_TIMESTAMP
|
||||||
|
DateTime :last_used_at, default: Sequel::CURRENT_TIMESTAMP
|
||||||
|
foreign_key [:player], :Players, key: :username, on_delete: :cascade
|
||||||
|
end
|
||||||
$active_users = DB[:SignedInUsers].all.map { |x| [x[:code], x[:player]] }.to_h
|
$active_users = DB[:SignedInUsers].all.map { |x| [x[:code], x[:player]] }.to_h
|
||||||
|
|
||||||
load "logman.rb"
|
|
||||||
load "mailer.rb"
|
load "mailer.rb"
|
||||||
load "players.rb"
|
load "players.rb"
|
||||||
load "session.rb"
|
load "session.rb"
|
||||||
|
|
||||||
|
set :port, ENV.fetch("PORT", 5161)
|
||||||
|
set :bind, '0.0.0.0'
|
||||||
|
set :host_authorization, { permitted_hosts: ["infinsweeper.syedm.dev"] }
|
||||||
set :public_folder, "public"
|
set :public_folder, "public"
|
||||||
|
|
||||||
get "/" do
|
get "/" do
|
||||||
session = Sessions.new request, response
|
session = Sessions.new request, response
|
||||||
Logman.log session["message"]
|
@message = session.message || ""
|
||||||
send_file "index.html"
|
session.message = ""
|
||||||
|
@signed_in = session.signed_in?.nil? ? false : true
|
||||||
|
@csrf_token = Array.new(32) { ALPHANUM.sample }.join
|
||||||
|
session["csrf_token"] = @csrf_token
|
||||||
|
ERB.new(File.read("index.erb")).result(binding)
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/debug" do
|
get "/debug" do
|
||||||
@@ -46,24 +60,38 @@ end
|
|||||||
|
|
||||||
post "/signup" do
|
post "/signup" do
|
||||||
session = Sessions.new request, response
|
session = Sessions.new request, response
|
||||||
|
uid = session["user"]
|
||||||
|
session.logout unless uid.nil? || $active_users[uid].nil?
|
||||||
data = JSON.parse(request.body.read)
|
data = JSON.parse(request.body.read)
|
||||||
|
unless session.csrf_auth?
|
||||||
|
status 401
|
||||||
|
return { "message" => "Unauthorized (invalid CSRF token)!" }.to_json
|
||||||
|
end
|
||||||
|
session["csrf_token"] = Array.new(32) { ALPHANUM.sample }.join
|
||||||
|
status 401
|
||||||
|
return { "message" => "New signups are disabled right now.", "csrf_token" => session["csrf_token"] }.to_json
|
||||||
if data["email"].nil? || data["pass"].nil? || data["username"].nil?
|
if data["email"].nil? || data["pass"].nil? || data["username"].nil?
|
||||||
status 400
|
status 400
|
||||||
return { "message" => "Bad request made!" }.to_json
|
return { "message" => "Bad request made!", "csrf_token" => session["csrf_token"] }.to_json
|
||||||
end
|
end
|
||||||
signup_status = Players.mk_player(data["username"], data["email"], data["pass"])
|
signup_status = Players.mk_player(data["username"], data["email"], data["pass"])
|
||||||
if signup_status[0] == 200
|
if signup_status[0] == 200
|
||||||
login_status = session.login(data["username"], data["pass"])
|
login_status = session.login(data["username"], data["pass"])
|
||||||
status login_status[0]
|
if login_status[0] == 200
|
||||||
return { "message" => login_status[1] }.to_json
|
status 200
|
||||||
|
return { "message" => login_status[1], "success" => "true", "csrf_token" => session["csrf_token"] }.to_json
|
||||||
|
else
|
||||||
|
status login_status[0]
|
||||||
|
return { "message" => login_status[1], "csrf_token" => session["csrf_token"] }.to_json
|
||||||
|
end
|
||||||
end
|
end
|
||||||
status signup_status[0]
|
status signup_status[0]
|
||||||
return { "message" => signup_status[1] }.to_json
|
return { "message" => signup_status[1], "csrf_token" => session["csrf_token"] }.to_json
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/verify/:code" do
|
get "/verify/:code" do
|
||||||
session = Sessions.new request, response
|
session = Sessions.new request, response
|
||||||
session["message"] = Players.verify(params[:code]) ? "Verified successfully!" : "Verification failed!"
|
session.message = Players.verify(params[:code]) ? "Verified successfully!" : "Verification failed!"
|
||||||
redirect "/"
|
redirect "/"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -71,13 +99,30 @@ post "/login" do
|
|||||||
data = JSON.parse(request.body.read)
|
data = JSON.parse(request.body.read)
|
||||||
session = Sessions.new request, response
|
session = Sessions.new request, response
|
||||||
uid = session["user"]
|
uid = session["user"]
|
||||||
if $active_users[uid] && !session.logout(uid)
|
Logman.log(request.env["HTTP_X_CSRF_TOKEN"].to_s + " " + session["csrf_token"].to_s)
|
||||||
|
unless session.csrf_auth?
|
||||||
|
status 401
|
||||||
|
return { "message" => "Unauthorized (invalid CSRF token)!" }.to_json
|
||||||
|
end
|
||||||
|
session["csrf_token"] = Array.new(32) { ALPHANUM.sample }.join
|
||||||
|
if $active_users[uid] && !session.logout
|
||||||
status 500
|
status 500
|
||||||
return { "message" => "Internal server error when signing the existing session out!" }.to_json
|
return {
|
||||||
|
"message" => "Internal server error when signing the existing session out!",
|
||||||
|
"csrf_token" => session["csrf_token"],
|
||||||
|
}.to_json
|
||||||
|
end
|
||||||
|
if data["username"].nil? || data["pass"].nil?
|
||||||
|
status 400
|
||||||
|
return { "message" => "Bad request made!", "csrf_token" => session["csrf_token"] }.to_json
|
||||||
end
|
end
|
||||||
login_status = session.login(data["username"], data["pass"])
|
login_status = session.login(data["username"], data["pass"])
|
||||||
status login_status[0]
|
status login_status[0]
|
||||||
return { "message" => login_status[1] }.to_json
|
if login_status[0] == 200
|
||||||
|
return { "message" => login_status[1], "success" => "true", "csrf_token" => session["csrf_token"] }.to_json
|
||||||
|
else
|
||||||
|
return { "message" => login_status[1], "csrf_token" => session["csrf_token"] }.to_json
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
post "/logout" do
|
post "/logout" do
|
||||||
@@ -85,14 +130,22 @@ post "/logout" do
|
|||||||
uid = session["user"]
|
uid = session["user"]
|
||||||
if $active_users[uid].nil?
|
if $active_users[uid].nil?
|
||||||
status 400
|
status 400
|
||||||
return { "message" => "Not signed in!" }.to_json
|
return { "message" => "Not logged in!" }.to_json
|
||||||
end
|
end
|
||||||
unless session.logout(uid)
|
unless session.logout
|
||||||
status 500
|
status 500
|
||||||
return { "message" => "Internal server error when signing you out!" }.to_json
|
return { "message" => "Internal server error when logging you out!" }.to_json
|
||||||
end
|
end
|
||||||
status 200
|
status 200
|
||||||
return { "message" => "Signed out successfully!" }.to_json
|
return { "message" => "Logged out successfully!", "success" => "true" }.to_json
|
||||||
|
end
|
||||||
|
|
||||||
|
get "/logout" do
|
||||||
|
session = Sessions.new request, response
|
||||||
|
uid = session["user"]
|
||||||
|
session.logout unless $active_users[uid].nil?
|
||||||
|
session.message = "Logged out successfully!"
|
||||||
|
redirect "/"
|
||||||
end
|
end
|
||||||
|
|
||||||
post "/forgot_password" do
|
post "/forgot_password" do
|
||||||
@@ -101,9 +154,28 @@ post "/forgot_password" do
|
|||||||
status 400
|
status 400
|
||||||
return { "message" => "Bad request made (Email not provided)!" }.to_json
|
return { "message" => "Bad request made (Email not provided)!" }.to_json
|
||||||
end
|
end
|
||||||
Players.pass_req(data["email"])
|
if Players.pass_req(data["email"])
|
||||||
status 200
|
status 200
|
||||||
return { "message" => "Email sent successfully!" }.to_json
|
return { "message" => "Email sent successfully!" }.to_json
|
||||||
|
else
|
||||||
|
status 400
|
||||||
|
return { "message" => "Couldn't send email!" }.to_json
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
post "/pass_reset?" do
|
||||||
|
data = JSON.parse(request.body.read)
|
||||||
|
if data["code"].nil?
|
||||||
|
status 400
|
||||||
|
return { "message" => "Bad request made!" }.to_json
|
||||||
|
end
|
||||||
|
if Players.pass_reset?(data["code"])
|
||||||
|
status 200
|
||||||
|
return { "message" => "Password reset link exists!" }.to_json
|
||||||
|
else
|
||||||
|
status 400
|
||||||
|
return { "message" => "Code doesn't exist!" }.to_json
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/reset_password/:code" do
|
get "/reset_password/:code" do
|
||||||
@@ -132,7 +204,7 @@ delete "/rm_player" do
|
|||||||
status 400
|
status 400
|
||||||
return { "message" => "Not signed in!" }.to_json
|
return { "message" => "Not signed in!" }.to_json
|
||||||
end
|
end
|
||||||
if session.logout(uid) && Players.rm_player($active_users[uid])
|
if session.logout && Players.rm_player($active_users[uid])
|
||||||
status 200
|
status 200
|
||||||
return { "message" => "Sorry to see you go.." }.to_json
|
return { "message" => "Sorry to see you go.." }.to_json
|
||||||
else
|
else
|
||||||
@@ -140,3 +212,7 @@ delete "/rm_player" do
|
|||||||
return { "message" => "Couldn't delete!" }.to_json
|
return { "message" => "Couldn't delete!" }.to_json
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
get "*" do
|
||||||
|
redirect "/"
|
||||||
|
end
|
||||||
|
|||||||
+69
-10
@@ -9,27 +9,30 @@ module Players
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.mk_player(username, email, pass)
|
def self.mk_player(username, email, pass)
|
||||||
raise ArgumentError, "Email format is wrong!" unless email.match?(/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/)
|
# rubocop:disable Layout/LineLength
|
||||||
|
raise ArgumentError, "Email format is wrong!" unless
|
||||||
|
email.match?(%r[(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])])
|
||||||
|
# rubocop:enable Layout/LineLength
|
||||||
raise ArgumentError, "Username must be at least 4 characters long and of valid format." unless
|
raise ArgumentError, "Username must be at least 4 characters long and of valid format." unless
|
||||||
username.match?(/\A[a-zA-Z][a-zA-Z0-9_.-]+\z/) && username.length >= 4
|
username.match?(/\A[a-zA-Z][a-zA-Z0-9_.-]+\z/) && username.length >= 4
|
||||||
raise ArgumentError, "Password must be at least 8 characters and of valid format." unless
|
raise ArgumentError, "Password must be at least 8 characters and of valid format." unless
|
||||||
pass.match?(/\A[a-zA-Z0-9_.!?@#$%^&*()+=-]+\z/) && pass.length >= 8
|
pass.match?(/\A[a-zA-Z0-9_.!?@#$%^&*()+=-]+\z/) && pass.length >= 8
|
||||||
|
|
||||||
digest = XXhash.xxh32(pass, ENV_HASH["SALT"])
|
digest = Zlib.crc32(pass, ENV["SALT"])
|
||||||
code = CODE_ENV == :prod ? Array.new(24) { ALPHANUM.sample }.join : "!"
|
code = ENV["ENV"] == "prod" ? Array.new(24) { ALPHANUM.sample }.join : "!"
|
||||||
|
|
||||||
DB[
|
DB[
|
||||||
"insert into Players (username, digest, email, activation_code) values (?, ?, ?, ?)",
|
"insert into Players (username, digest, email, activation_code) values (?, ?, ?, ?)",
|
||||||
username, digest, email, code
|
username, digest, email, code
|
||||||
].insert
|
].insert
|
||||||
|
|
||||||
send_email(:new, email, username, code) if CODE_ENV == :prod
|
send_email(:new, email, username, code) if ENV["ENV"] == "prod"
|
||||||
|
|
||||||
[200, "Successfully signed up!"]
|
[200, "Successfully signed up!"]
|
||||||
rescue ArgumentError => e
|
rescue ArgumentError => e
|
||||||
[400, e.message]
|
[400, e.message]
|
||||||
rescue Sequel::UniqueConstraintViolation
|
rescue Sequel::UniqueConstraintViolation
|
||||||
[400, "Account already exists with this username or username!"]
|
[400, "Account already exists with this email or username!"]
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.verify(code)
|
def self.verify(code)
|
||||||
@@ -41,29 +44,42 @@ module Players
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.pass_req(email)
|
def self.pass_req(email)
|
||||||
return unless self[email]
|
return false unless by_email(email)
|
||||||
|
|
||||||
code = Array.new(24) { ALPHANUM.sample }.join
|
code = Array.new(24) { ALPHANUM.sample }.join
|
||||||
DB["update Players set new_pass_code = ? where email = ?", code, email].update
|
DB["update Players set new_pass_code = ? where email = ?", code, email].update
|
||||||
|
|
||||||
|
Logman.log "Pass req: #{email} & #{code}"
|
||||||
|
|
||||||
send_email(:pass_req, email, code)
|
send_email(:pass_req, email, code)
|
||||||
|
|
||||||
|
true
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.pass_reset(new_pass, code)
|
def self.pass_reset(pass, code)
|
||||||
digest = XXhash.xxh32(new_pass, ENV_HASH["SALT"])
|
digest = Zlib.crc32(pass, ENV["SALT"])
|
||||||
DB["update Players set digest = ?, new_pass_code = ? where new_pass_code = ?", digest, "", code].update != 0
|
DB["update Players set digest = ?, new_pass_code = ? where new_pass_code = ?", digest, "", code].update != 0
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.pass_reset?(code)
|
||||||
|
DB["select * from Players where new_pass_code = ?", code].first
|
||||||
|
end
|
||||||
|
|
||||||
def self.[](username)
|
def self.[](username)
|
||||||
DB["select * from Players where username = ?", username].first
|
DB["select * from Players where username = ?", username].first
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.by_email(email)
|
||||||
|
DB["select * from Players where email = ?", email].first
|
||||||
|
end
|
||||||
|
|
||||||
def self.[]=(username, data)
|
def self.[]=(username, data)
|
||||||
DB["update Players set data = ? where username = ?", data, username].update
|
DB["update Players set data = ? where username = ?", data, username].update
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.authorized?(username, pass)
|
def self.authorized?(username, pass)
|
||||||
digest = XXhash.xxh32(pass, ENV_HASH["SALT"])
|
digest = Zlib.crc32(pass, ENV["SALT"])
|
||||||
|
Logman.log "Authorized: #{username} & #{digest}"
|
||||||
player = self[username]
|
player = self[username]
|
||||||
player && player[:digest].to_i == digest.to_i ? player : false
|
player && player[:digest].to_i == digest.to_i ? player : false
|
||||||
end
|
end
|
||||||
@@ -74,13 +90,56 @@ module Players
|
|||||||
player && player[:activation_code] == "!"
|
player && player[:activation_code] == "!"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.send_email(type, email, *args)
|
||||||
|
case type
|
||||||
|
when :new
|
||||||
|
username, code = args
|
||||||
|
|
||||||
|
Mail.send(
|
||||||
|
email,
|
||||||
|
"Verify your InfinSweeper account",
|
||||||
|
<<~HTML
|
||||||
|
<h2>Welcome to InfinSweeper, #{ERB::Util.html_escape(username)}!</h2>
|
||||||
|
<p>Thanks for signing up.</p>
|
||||||
|
<p>
|
||||||
|
Please verify your email by clicking
|
||||||
|
<a href="https://your-domain.com/verify/#{ERB::Util.url_encode(code)}">
|
||||||
|
this link
|
||||||
|
</a>.
|
||||||
|
</p>
|
||||||
|
HTML
|
||||||
|
)
|
||||||
|
|
||||||
|
when :pass_req
|
||||||
|
code = args.first
|
||||||
|
|
||||||
|
Mail.send(
|
||||||
|
email,
|
||||||
|
"Reset your InfinSweeper password",
|
||||||
|
<<~HTML
|
||||||
|
<h2>Password reset</h2>
|
||||||
|
<p>You requested a password reset for your InfinSweeper account.</p>
|
||||||
|
<p>
|
||||||
|
<a href="https://your-domain.com/reset_password/#{ERB::Util.url_encode(code)}">
|
||||||
|
Click here to reset your password
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p>If you didn't request this, you can safely ignore this email.</p>
|
||||||
|
HTML
|
||||||
|
)
|
||||||
|
|
||||||
|
else
|
||||||
|
raise ArgumentError, "Unknown email type: #{type.inspect}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
Thread.new do
|
Thread.new do
|
||||||
loop do
|
loop do
|
||||||
unverified.each do |player|
|
unverified.each do |player|
|
||||||
rm_player(player[:username]) if player[:created_at] + 24 * 60 * 60 < Time.now
|
rm_player(player[:username]) if player[:created_at] + 24 * 60 * 60 < Time.now
|
||||||
end
|
end
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
Logman.log "Thread error: #{e.message}\n"
|
Logman.log "Thread error: #{e.message}"
|
||||||
ensure
|
ensure
|
||||||
sleep 60 * 60
|
sleep 60 * 60
|
||||||
end
|
end
|
||||||
|
|||||||
Binary file not shown.
+172
-12
@@ -1,15 +1,10 @@
|
|||||||
|
@import url("https://fonts.googleapis.com/css2?family=WDXL+Lubrifont+JP+N&display=swap");
|
||||||
|
|
||||||
body {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: "Changa";
|
|
||||||
src: url("fonts/changa.woff") format("opentype");
|
|
||||||
font-weight: normal;
|
|
||||||
font-style: normal;
|
|
||||||
}
|
|
||||||
|
|
||||||
.header {
|
.header {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 90px;
|
height: 90px;
|
||||||
@@ -18,7 +13,71 @@ body {
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
font-family: "Changa";
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message {
|
||||||
|
color: white;
|
||||||
|
position: absolute;
|
||||||
|
background-color: #1b262c;
|
||||||
|
width: calc(100vw - 10px);
|
||||||
|
padding: 5px;
|
||||||
|
display: block;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 21px;
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
opacity: 1;
|
||||||
|
transition: opacity 0.5s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message.hide {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message::after {
|
||||||
|
content: "X";
|
||||||
|
color: white;
|
||||||
|
position: absolute;
|
||||||
|
right: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message:hover::after {
|
||||||
|
color: #90bdd9;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message:empty:after {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
font-size: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
outline: none;
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
font-size: 18px;
|
||||||
|
background-color: white;
|
||||||
|
color: #1b262c;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link {
|
||||||
|
color: #90bdd9;
|
||||||
|
text-decoration: none;
|
||||||
|
cursor: pointer;
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link:hover {
|
||||||
|
color: #adcee3;
|
||||||
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
.logo {
|
.logo {
|
||||||
@@ -32,21 +91,122 @@ body {
|
|||||||
top: 50%;
|
top: 50%;
|
||||||
left: 50%;
|
left: 50%;
|
||||||
transform: translate(-50%, -50%);
|
transform: translate(-50%, -50%);
|
||||||
width: 500px;
|
width: 400px;
|
||||||
height: 500px;
|
padding-top: 20px;
|
||||||
background-color: rgba(0, 0, 0, 0.5);
|
background-color: #1b262c70;
|
||||||
display: flex;
|
backdrop-filter: blur(8px);
|
||||||
|
display: none;
|
||||||
|
border-radius: 30px;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
z-index: 9999;
|
z-index: 9999;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.close {
|
||||||
|
position: absolute;
|
||||||
|
top: 5px;
|
||||||
|
right: 15px;
|
||||||
|
font-size: 24px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 29px;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.close:hover {
|
||||||
|
color: #fa908c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup.active {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
.popup-tab {
|
.popup-tab {
|
||||||
display: none;
|
display: none;
|
||||||
|
width: calc(100% - 60px);
|
||||||
|
height: calc(100% - 60px);
|
||||||
|
padding: 20px 30px;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
color: white;
|
||||||
|
font-weight: bold;
|
||||||
|
opacity: none;
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info:empty::before {
|
||||||
|
content: "\00a0";
|
||||||
|
visibility: hidden;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info.active {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
height: 80%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form input {
|
||||||
|
padding: 10px;
|
||||||
|
width: 80%;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form label {
|
||||||
|
font-size: 16px;
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form button {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 10px;
|
||||||
|
background-color: #3498db;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
width: 25%;
|
||||||
|
border-radius: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form button:hover {
|
||||||
|
background-color: #2980b9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-tab.active {
|
||||||
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.header-right {
|
.header-right {
|
||||||
margin-right: 20px;
|
margin-right: 20px;
|
||||||
|
display: flex;
|
||||||
|
white-space: nowrap;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.account-button {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #90bdd9;
|
||||||
|
font-size: 23px;
|
||||||
|
font-family: "WDXL Lubrifont JP N", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.account-button:hover {
|
||||||
|
color: #adcee3;
|
||||||
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
.pixelart {
|
.pixelart {
|
||||||
|
|||||||
+158
-36
@@ -1,43 +1,165 @@
|
|||||||
const login_form = document.getElementById("login-form");
|
const csrfMeta = document.querySelector('meta[name="csrf"]');
|
||||||
const login_button = document.getElementById("login-button");
|
var csrf = csrfMeta?.content;
|
||||||
const signup_form = document.getElementById("signup-form");
|
window.onload = async () => {
|
||||||
const signup_button = document.getElementById("signup-button");
|
const popup = document.getElementById("popup");
|
||||||
|
const loginSection = document.getElementById("login");
|
||||||
|
const signupSection = document.getElementById("signup");
|
||||||
|
const forgotPassSection = document.getElementById("forgot-pass");
|
||||||
|
const resetPassSection = document.getElementById("reset-pass");
|
||||||
|
|
||||||
login_button.onclick = () => {
|
const loginForm = document.getElementById("login-form");
|
||||||
document.getElementById("login").style.display = "block";
|
const signupForm = document.getElementById("signup-form");
|
||||||
};
|
const forgotForm = document.getElementById("forgot-form");
|
||||||
|
const resetForm = document.getElementById("reset-form");
|
||||||
|
|
||||||
signup_button.onclick = () => {
|
const loginInfo = document.getElementById("login-info");
|
||||||
document.getElementById("signup").style.display = "block";
|
const signupInfo = document.getElementById("signup-info");
|
||||||
};
|
const forgotInfo = document.getElementById("forgot-info");
|
||||||
|
const resetInfo = document.getElementById("reset-info");
|
||||||
|
|
||||||
login_form.onsubmit = async (e) => {
|
const loginButton = document.getElementById("login-button");
|
||||||
e.preventDefault();
|
const signupButton = document.getElementById("signup-button");
|
||||||
const username = login_form.username.value;
|
const logoutButton = document.getElementById("logout-button");
|
||||||
const pass = login_form.pass.value;
|
const forgotButton = document.getElementById("forgot-link");
|
||||||
let response = await fetch("/login", {
|
const closeButton = document.getElementById("close");
|
||||||
method: "POST",
|
|
||||||
headers: {
|
const message = document.getElementById("message");
|
||||||
"Content-Type": "application/json",
|
message.onclick = () => message.classList.add("hide");
|
||||||
},
|
|
||||||
body: JSON.stringify({ username, pass }),
|
const signedInMeta = document.querySelector('meta[name="signed_in"]');
|
||||||
|
const isSignedIn = signedInMeta?.content === "true";
|
||||||
|
if (isSignedIn) {
|
||||||
|
loginButton.style.display = "none";
|
||||||
|
signupButton.style.display = "none";
|
||||||
|
} else {
|
||||||
|
logoutButton.style.display = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
const showPopup = (section) => {
|
||||||
|
popup.classList.add("active");
|
||||||
|
loginSection.classList.remove("active");
|
||||||
|
signupSection.classList.remove("active");
|
||||||
|
forgotPassSection.classList.remove("active");
|
||||||
|
resetPassSection.classList.remove("active");
|
||||||
|
if (section) section.classList.add("active");
|
||||||
|
};
|
||||||
|
|
||||||
|
const hidePopup = () => {
|
||||||
|
popup.classList.remove("active");
|
||||||
|
loginSection.classList.remove("active");
|
||||||
|
signupSection.classList.remove("active");
|
||||||
|
forgotPassSection.classList.remove("active");
|
||||||
|
resetPassSection.classList.remove("active");
|
||||||
|
};
|
||||||
|
|
||||||
|
loginButton?.addEventListener("click", () => showPopup(loginSection));
|
||||||
|
signupButton?.addEventListener("click", () => showPopup(signupSection));
|
||||||
|
logoutButton?.addEventListener("click", async () => {
|
||||||
|
const res = await fetch("/logout", { method: "POST" });
|
||||||
|
const data = await res.json();
|
||||||
|
message.innerText = data.message;
|
||||||
|
message.classList.remove("hide");
|
||||||
|
if (data.success == "true") {
|
||||||
|
loginButton.style.display = "block";
|
||||||
|
signupButton.style.display = "block";
|
||||||
|
logoutButton.style.display = "none";
|
||||||
|
}
|
||||||
});
|
});
|
||||||
response = await response.json();
|
forgotButton?.addEventListener("click", () => showPopup(forgotPassSection));
|
||||||
document.getElementById("login-info").innerText = response.message;
|
closeButton?.addEventListener("click", hidePopup);
|
||||||
};
|
|
||||||
|
|
||||||
signup_form.onsubmit = async (e) => {
|
loginForm?.addEventListener("submit", async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const username = signup_form.username.value;
|
const { username, pass } = loginForm;
|
||||||
const email = signup_form.email.value;
|
const res = await fetch("/login", {
|
||||||
const pass = signup_form.pass.value;
|
method: "POST",
|
||||||
let response = await fetch("/signup", {
|
headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf },
|
||||||
method: "POST",
|
body: JSON.stringify({ username: username.value, pass: pass.value }),
|
||||||
headers: {
|
});
|
||||||
"Content-Type": "application/json",
|
const data = await res.json();
|
||||||
},
|
loginInfo.innerText = data.message;
|
||||||
body: JSON.stringify({ username, email, pass }),
|
csrf = data.csrf_token;
|
||||||
|
if (data.success == "true") {
|
||||||
|
loginButton.style.display = "none";
|
||||||
|
signupButton.style.display = "none";
|
||||||
|
logoutButton.style.display = "block";
|
||||||
|
message.innerText = data.message;
|
||||||
|
message.classList.remove("hide");
|
||||||
|
hidePopup();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
response = await response.json();
|
|
||||||
document.getElementById("signup-info").innerText = response.message;
|
signupForm?.addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const { username, email, pass } = signupForm;
|
||||||
|
const res = await fetch("/signup", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf },
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: username.value,
|
||||||
|
email: email.value,
|
||||||
|
pass: pass.value,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
signupInfo.innerText = data.message;
|
||||||
|
csrf = data.csrf_token;
|
||||||
|
if (data.success == "true") {
|
||||||
|
loginButton.style.display = "none";
|
||||||
|
signupButton.style.display = "none";
|
||||||
|
logoutButton.style.display = "block";
|
||||||
|
message.innerText = data.message;
|
||||||
|
message.classList.remove("hide");
|
||||||
|
hidePopup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
forgotForm?.addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const email = forgotForm.email.value;
|
||||||
|
const res = await fetch("/forgot_password", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
forgotInfo.innerHTML = data.message;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle reset code in URL
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const resetCode = params.get("reset_code");
|
||||||
|
|
||||||
|
if (resetCode) {
|
||||||
|
const res = await fetch("/pass_reset?", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ code: resetCode }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status === 200) {
|
||||||
|
showPopup(resetPassSection);
|
||||||
|
|
||||||
|
resetForm?.addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const pass = resetForm.pass.value;
|
||||||
|
const passConfirm = resetForm.pass_confirm.value;
|
||||||
|
|
||||||
|
if (pass !== passConfirm) {
|
||||||
|
resetInfo.innerText = "Passwords do not match";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`/reset_password/${resetCode}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ pass }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
resetInfo.innerText = data.message;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
window.location.href = "/";
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -18,4 +18,8 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
*/
|
*/
|
||||||
window.game = new GameController();
|
window.game = new GameController();
|
||||||
window.game.init();
|
window.game.init();
|
||||||
|
|
||||||
|
document.getElementById("reset-button").addEventListener("click", () => {
|
||||||
|
window.game.reset();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -147,6 +147,7 @@ export default class GameController {
|
|||||||
* @param {number} tries - Number of times the game has been reset
|
* @param {number} tries - Number of times the game has been reset
|
||||||
*/
|
*/
|
||||||
async reset(tries = 0) {
|
async reset(tries = 0) {
|
||||||
|
this.bus.emit("clear_save");
|
||||||
this._clearGameState();
|
this._clearGameState();
|
||||||
this._generateNewSeed();
|
this._generateNewSeed();
|
||||||
await this.start(tries);
|
await this.start(tries);
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ export default class Saver {
|
|||||||
this.bus.on("load_save", this.load.bind(this));
|
this.bus.on("load_save", this.load.bind(this));
|
||||||
/** @listens EventBus#delete_save */
|
/** @listens EventBus#delete_save */
|
||||||
this.bus.on("delete_save", this.deleteSave.bind(this));
|
this.bus.on("delete_save", this.deleteSave.bind(this));
|
||||||
|
/** @listens EventBus#clear_save */
|
||||||
|
this.bus.on("clear_save", this.clearSave.bind(this));
|
||||||
/** @listens EventBus#start_autosaver */
|
/** @listens EventBus#start_autosaver */
|
||||||
this.bus.on("start_autosaver", this.startAutosaver.bind(this));
|
this.bus.on("start_autosaver", this.startAutosaver.bind(this));
|
||||||
/** @listens EventBus#stop_autosaver */
|
/** @listens EventBus#stop_autosaver */
|
||||||
@@ -154,6 +156,14 @@ export default class Saver {
|
|||||||
this.delete_save = true;
|
this.delete_save = true;
|
||||||
this.stopAutosaver();
|
this.stopAutosaver();
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* @function clearSave
|
||||||
|
* @description clears the save
|
||||||
|
*/
|
||||||
|
clearSave() {
|
||||||
|
localStorage.removeItem("save");
|
||||||
|
this.delete_save = false;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* @function loadFromFile
|
* @function loadFromFile
|
||||||
* @description Loads the game data from a file
|
* @description Loads the game data from a file
|
||||||
|
|||||||
+67
-58
@@ -3,19 +3,50 @@ class Sessions
|
|||||||
def initialize(request, response)
|
def initialize(request, response)
|
||||||
@request = request
|
@request = request
|
||||||
@response = response
|
@response = response
|
||||||
|
@session = load_session
|
||||||
end
|
end
|
||||||
|
|
||||||
def signed_in?(code)
|
def save
|
||||||
$active_users[code]
|
compressed = Zlib::Deflate.deflate(JSON.generate(@session))
|
||||||
|
encoded = Base64.strict_encode64(compressed)
|
||||||
|
@response.set_cookie(
|
||||||
|
"session",
|
||||||
|
value: encoded,
|
||||||
|
path: "/",
|
||||||
|
expires: Time.now + 360 * 24 * 60 * 60,
|
||||||
|
httponly: true,
|
||||||
|
secure: ENV["ENV"] == "prod",
|
||||||
|
samesite: :strict
|
||||||
|
)
|
||||||
|
uid = @session["user"]
|
||||||
|
if uid
|
||||||
|
DB["UPDATE SignedInUsers SET last_used_at = CURRENT_TIMESTAMP WHERE code = ?", uid].update
|
||||||
|
end
|
||||||
|
rescue Sequel::Error => e
|
||||||
|
Logman.log "DB Error: #{e.message} when updating last_used_at for #{uid}"
|
||||||
end
|
end
|
||||||
|
|
||||||
def logout(uid)
|
def load_session
|
||||||
|
cookie = @request.cookies["session"]
|
||||||
|
return {} unless cookie
|
||||||
|
JSON.parse(Zlib::Inflate.inflate(Base64.strict_decode64(cookie)))
|
||||||
|
rescue JSON::ParserError, Zlib::Error, ArgumentError
|
||||||
|
@response.delete_cookie("session")
|
||||||
|
{}
|
||||||
|
end
|
||||||
|
|
||||||
|
def signed_in?
|
||||||
|
$active_users[self["user"]]
|
||||||
|
end
|
||||||
|
|
||||||
|
def logout
|
||||||
|
uid = self["user"]
|
||||||
$active_users.delete(uid)
|
$active_users.delete(uid)
|
||||||
delete("user")
|
delete("user")
|
||||||
DB["delete from SignedInUsers where code = ?", uid].delete
|
DB["delete from SignedInUsers where code = ?", uid].delete
|
||||||
true
|
true
|
||||||
rescue Sequel::Error => e
|
rescue Sequel::Error => e
|
||||||
Logman.log "DB Error: #{e.message}\n"
|
Logman.log "DB Error: #{e.message}"
|
||||||
false
|
false
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -23,76 +54,54 @@ class Sessions
|
|||||||
player = Players.authorized?(username, pass)
|
player = Players.authorized?(username, pass)
|
||||||
if player
|
if player
|
||||||
code = Array.new(24) { ALPHANUM.sample }.join
|
code = Array.new(24) { ALPHANUM.sample }.join
|
||||||
self["user", code] = code
|
self["user"] = code
|
||||||
$active_users[code] = username
|
$active_users[code] = username
|
||||||
begin
|
begin
|
||||||
DB["insert into SignedInUsers (code, player) values (?, ?)", code, username].insert
|
DB["insert into SignedInUsers (code, player) values (?, ?)", code, username].insert
|
||||||
rescue Sequel::Error => e
|
rescue Sequel::Error => e
|
||||||
Logman.log "DB Error: #{e.message}\n"
|
Logman.log "DB Error: #{e.message}"
|
||||||
return [500, "Internal server error when signing you in!"]
|
return [500, "Internal server error when signing you in!"]
|
||||||
end
|
end
|
||||||
return [200, "Remember to verify your email!"] unless Players.verified?(username)
|
return [200, "Remember to verify your email!"] unless Players.verified?(username)
|
||||||
[200, "Signed in successfully!"]
|
[200, "Signed in successfully!"]
|
||||||
else
|
else
|
||||||
[200, "Couldn't sign you in (Username or password incorrect)!"]
|
[401, "Couldn't sign you in (Username or password incorrect)!"]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def []=(key, uid, val)
|
def [](key)
|
||||||
session = @request.cookies["session"]
|
@session[key]
|
||||||
session = session.nil? ? "{}" : Zlib::Inflate.inflate(Base64.decode64(session))
|
|
||||||
session = JSON.parse(session)
|
|
||||||
session[key] = val
|
|
||||||
compressed = Zlib::Deflate.deflate(JSON.generate(session))
|
|
||||||
encoded = Base64.encode64(compressed)
|
|
||||||
@response.set_cookie("session",
|
|
||||||
value: encoded,
|
|
||||||
path: "/",
|
|
||||||
expires: Time.now + 360 * 24 * 60 * 60)
|
|
||||||
DB["UPDATE SignedInUsers SET last_used_at = CURRENT_TIMESTAMP WHERE code = ?", uid].update if uid
|
|
||||||
rescue JSON::ParserError, Zlib::Error
|
|
||||||
@response.delete_cookie("session")
|
|
||||||
rescue Sequel::Error => e
|
|
||||||
Logman.log "DB Error: #{e.message} when updating last_used_at for #{uid}\n"
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def [](key, uid: nil)
|
def []=(key, val)
|
||||||
session = @request.cookies["session"]
|
@session[key] = val
|
||||||
session = session.nil? ? "{}" : Zlib::Inflate.inflate(Base64.decode64(session))
|
save
|
||||||
session = JSON.parse(session)
|
|
||||||
begin
|
|
||||||
DB["UPDATE SignedInUsers SET last_used_at = CURRENT_TIMESTAMP WHERE code = ?", uid].update if uid
|
|
||||||
rescue Sequel::Error => e
|
|
||||||
Logman.log "DB Error: #{e.message} when updating last_used_at for #{uid}\n"
|
|
||||||
end
|
|
||||||
session[key]
|
|
||||||
rescue JSON::ParserError, Zlib::Error
|
|
||||||
@response.delete_cookie("session")
|
|
||||||
""
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def all
|
def all
|
||||||
session = @request.cookies["session"]
|
@session
|
||||||
session = session.nil? ? "{}" : Zlib::Inflate.inflate(Base64.decode64(session))
|
end
|
||||||
JSON.parse(session)
|
|
||||||
rescue JSON::ParserError, Zlib::Error
|
def message=(val)
|
||||||
@response.delete_cookie("session")
|
@response.set_cookie("message",
|
||||||
{}
|
value: val,
|
||||||
|
path: "/",
|
||||||
|
expires: Time.now + 360 * 24 * 60 * 60,
|
||||||
|
secure: ENV["ENV"] == "prod",
|
||||||
|
samesite: :strict)
|
||||||
|
end
|
||||||
|
|
||||||
|
def message
|
||||||
|
@request.cookies["message"]
|
||||||
|
end
|
||||||
|
|
||||||
|
def csrf_auth?
|
||||||
|
@request.env["HTTP_X_CSRF_TOKEN"] == self["csrf_token"]
|
||||||
end
|
end
|
||||||
|
|
||||||
def delete(key)
|
def delete(key)
|
||||||
session = @request.cookies["session"]
|
@session.delete(key)
|
||||||
session = session.nil? ? "{}" : Zlib::Inflate.inflate(Base64.decode64(session))
|
save
|
||||||
session = JSON.parse(session)
|
|
||||||
session.delete(key)
|
|
||||||
compressed = Zlib::Deflate.deflate(JSON.generate(session))
|
|
||||||
encoded = Base64.encode64(compressed)
|
|
||||||
@response.set_cookie("session",
|
|
||||||
value: encoded,
|
|
||||||
path: "/",
|
|
||||||
expires: Time.now + 360 * 24 * 60 * 60)
|
|
||||||
rescue JSON::ParserError, Zlib::Error
|
|
||||||
@response.delete_cookie("session")
|
|
||||||
end
|
end
|
||||||
|
|
||||||
Thread.new do
|
Thread.new do
|
||||||
@@ -106,16 +115,16 @@ class Sessions
|
|||||||
begin
|
begin
|
||||||
DB[:SignedInUsers].where(code: session[:code]).delete
|
DB[:SignedInUsers].where(code: session[:code]).delete
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
Logman.log "Thread DB error: #{e.message} on #{session[:code]} for #{session[:player]}\n"
|
Logman.log "Thread DB error: #{e.message} on #{session[:code]} for #{session[:player]}"
|
||||||
end
|
end
|
||||||
$active_users.delete(session[:code])
|
$active_users.delete(session[:code])
|
||||||
puts "Auto-logged out: #{session[:player]} (expired session)"
|
Logman.log "Auto-logged out: #{session[:player]} (expired session)"
|
||||||
end
|
end
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
Logman.log "Thread error: #{e.message}\n"
|
Logman.log "Thread error: #{e.message}"
|
||||||
ensure
|
ensure
|
||||||
sleep 60 * 60 * 24
|
sleep 60 * 60 * 24
|
||||||
Logman.log "Thread sleeping\n"
|
Logman.log "Thread sleeping"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user