Compare commits

..

3 Commits

Author SHA1 Message Date
jane 24acfa5846 use jennifer for db interface 2021-07-24 17:17:10 -04:00
jane 840959ec25 crystal init 2021-07-09 23:03:57 -04:00
jane b018c0e367 remove js backend 2021-07-09 23:02:31 -04:00
83 changed files with 1829 additions and 3372 deletions

16
.gitignore vendored
View File

@ -42,11 +42,6 @@ build/Release
node_modules/
jspm_packages/
/public/build/
.DS_Store
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
@ -113,7 +108,6 @@ dist
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
.vscode/
# yarn v2
.yarn/cache
@ -133,6 +127,10 @@ pnpm-lock.yaml
backend/config.json
*.pem
.env
test_coverage/
target/
/docs/
/lib/
/bin/
/.shards/
*.dwarf
Makefile
.vscode/

2534
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,38 +0,0 @@
[package]
edition = "2018"
name = "backend"
version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-lock = "2.4.0"
async-redis-session = {git = "https://github.com/jbr/async-redis-session", version = "0.2.2"}
async-session = "3.0.0"
async-std = {version = "1.9.0", features = ["attributes"]}
axum = {version = "0.1.1", features = ["headers"]}
chrono = {version = "0.4.0", features = ["serde"]}
diesel = {version = "1.4.7", features = ["postgres", "chrono", "serde_json", "r2d2", "uuidv07"]}
diesel-tracing = {version = "0.1.5", features = ["postgres"]}
diesel_migrations = {version = "1.4.0"}
dotenv = "0.15.0"
fern = "0.6.0"
headers = "0.3.4"
http = "0.2.4"
hyper = {version = "0.14.11", features = ["full"]}
log = "0.4.14"
oauth2 = "4.1.0"
redis = {version = "0.21.0", features = ["aio", "async-std-comp"]}
reqwest = {version = "0.11.4", features = ["json"]}
serde = {version = "1.0.127", features = ["derive"]}
serde-redis = "0.10.0"
serde_json = "1.0.66"
tokio = {version = "1.9.0", features = ["full"]}
tokio-diesel = {git = "https://github.com/mehcode/tokio-diesel", version = "0.3.0"}
tower = {version = "0.4.6", features = ["full"]}
tower-http = {version = "0.1.1", features = ["trace"]}
tracing = {version = "0.1.26", features = ["log-always"]}
tracing-log = {version = "0.1.2", features = ["log-tracer"]}
tracing-subscriber = {version = "0.2.20", features = ["fmt"]}
url = "2.2.2"
uuid = {version = "0.8.2", features = ["serde", "v4"]}

9
backend/.editorconfig Normal file
View File

@ -0,0 +1,9 @@
root = true
[*.cr]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true

5
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf

6
backend/.travis.yml Normal file
View File

@ -0,0 +1,6 @@
language: crystal
# Uncomment the following if you'd like Travis to run specs and check code formatting
# script:
# - crystal spec
# - crystal tool format --check

21
backend/LICENSE Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021 Jane Petrovna <jane@j4.pm>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

27
backend/README.md Normal file
View File

@ -0,0 +1,27 @@
# backend
TODO: Write a description here
## Installation
TODO: Write installation instructions here
## Usage
TODO: Write usage instructions here
## Development
TODO: Write development instructions here
## Contributing
1. Fork it (<https://github.com/your-github-user/backend/fork>)
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
## Contributors
- [Jane Petrovna](https://github.com/your-github-user) - creator and maintainer

View File

@ -0,0 +1,9 @@
{
"secret": "TEST_SECRET",
"port": 8080,
"db_url": "postgres://postgres:@127.0.0.1/todo",
"mail_host": "smtp.migadu.com",
"mail_port": 465,
"mail_username": "",
"mail_password": ""
}

2
backend/config/config.cr Normal file
View File

@ -0,0 +1,2 @@
require "./initializers/**"
require "../src/models/*"

View File

@ -0,0 +1,16 @@
default: &default
host: localhost
user: postgres
adapter: postgres
development:
<<: *default
db: todo_dev
test:
<<: *default
db: todo_dev
production:
<<: *default
db: todo

View File

@ -0,0 +1,12 @@
require "jennifer"
require "jennifer/adapter/postgres"
APP_ENV = ENV["APP_ENV"]? || "development"
Jennifer::Config.configure do |conf|
conf.read("config/database.yml", APP_ENV)
conf.from_uri(ENV["DATABASE_URI"]) if ENV.has_key?("DATABASE_URI")
conf.logger.level = APP_ENV == "development" ? Log::Severity::Debug : Log::Severity::Info
end
Log.setup "db", :debug, Log::IOBackend.new(formatter: Jennifer::Adapter::DBFormatter)

View File

@ -0,0 +1,3 @@
I18n.load_path += ["./config/locales"]
I18n.init

View File

@ -0,0 +1,19 @@
require "jennifer"
class CreateUsers < Jennifer::Migration::Base
def up
create_table :users do |t|
t.string :id, {:primary => true}
t.string :email
t.bool :discord_only_account
t.string :discord_id, {:null => true}
t.string :password_hash, {:null => true}
t.timestamps
end
end
def down
drop_table :users if table_exists? :users
end
end

View File

@ -0,0 +1,20 @@
require "jennifer"
class CreateUnverifiedusers < Jennifer::Migration::Base
def up
create_table :unverifiedusers do |t|
t.string :id, {:primary => true}
t.string :email
t.bool :discord_only_account
t.string :discord_id, {:null => true}
t.string :password_hash, {:null => true}
t.string :verification_token
t.timestamps
end
end
def down
drop_table :unverifiedusers if table_exists? :unverifiedusers
end
end

View File

@ -0,0 +1,20 @@
require "jennifer"
class CreateTodos < Jennifer::Migration::Base
def up
create_table :todos do |t|
t.string :id, {:primary => true}
t.string :userid # remember: trying to insert a column named the same as
# another model will make the database error :)
t.text :content
t.string :tags, {:array => true, :null => true}
t.bool :complete, {:null => true}
t.date_time :deadline, {:null => true}
t.timestamps
end
end
def down
drop_table :todos if table_exists? :todos
end
end

152
backend/db/structure.sql Normal file
View File

@ -0,0 +1,152 @@
--
-- PostgreSQL database dump
--
-- Dumped from database version 13.3
-- Dumped by pg_dump version 13.3
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: migration_versions; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.migration_versions (
id integer NOT NULL,
version character varying(17) NOT NULL
);
ALTER TABLE public.migration_versions OWNER TO postgres;
--
-- Name: migration_versions_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE public.migration_versions_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.migration_versions_id_seq OWNER TO postgres;
--
-- Name: migration_versions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE public.migration_versions_id_seq OWNED BY public.migration_versions.id;
--
-- Name: todos; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.todos (
id character varying(254) NOT NULL,
userid character varying(254),
content text,
tags character varying(254)[],
complete boolean,
deadline timestamp without time zone,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE public.todos OWNER TO postgres;
--
-- Name: unverifiedusers; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.unverifiedusers (
id character varying(254) NOT NULL,
email character varying(254),
discord_only_account boolean,
discord_id character varying(254),
password_hash character varying(254),
verification_token character varying(254),
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE public.unverifiedusers OWNER TO postgres;
--
-- Name: users; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.users (
id character varying(254) NOT NULL,
email character varying(254),
discord_only_account boolean,
discord_id character varying(254),
password_hash character varying(254),
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE public.users OWNER TO postgres;
--
-- Name: migration_versions id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.migration_versions ALTER COLUMN id SET DEFAULT nextval('public.migration_versions_id_seq'::regclass);
--
-- Name: migration_versions migration_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.migration_versions
ADD CONSTRAINT migration_versions_pkey PRIMARY KEY (id);
--
-- Name: todos todos_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.todos
ADD CONSTRAINT todos_pkey PRIMARY KEY (id);
--
-- Name: unverifiedusers unverifiedusers_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.unverifiedusers
ADD CONSTRAINT unverifiedusers_pkey PRIMARY KEY (id);
--
-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.users
ADD CONSTRAINT users_pkey PRIMARY KEY (id);
--
-- PostgreSQL database dump complete
--

13
backend/sam.cr Normal file
View File

@ -0,0 +1,13 @@
require "./config/*"
require "sam"
require "./db/migrations/*"
load_dependencies "jennifer"
# Here you can define your tasks
# desc "with description to be used by help command"
# task "test" do
# puts "ping"
# end
Sam.help

78
backend/shard.lock Normal file
View File

@ -0,0 +1,78 @@
version: 2.0
shards:
ameba:
git: https://github.com/crystal-ameba/ameba.git
version: 0.14.3
backtracer:
git: https://github.com/sija/backtracer.cr.git
version: 1.2.1
base62:
git: https://github.com/janeptrv/base62.cr.git
version: 0.1.3
db:
git: https://github.com/crystal-lang/crystal-db.git
version: 0.10.1
email:
git: https://github.com/arcage/crystal-email.git
version: 0.6.3
exception_page:
git: https://github.com/crystal-loot/exception_page.git
version: 0.2.0
i18n:
git: https://github.com/techmagister/i18n.cr.git
version: 0.3.1+git.commit.b323291b772c97bc1661888eb9e82dadb722acaa
ifrit:
git: https://github.com/imdrasil/ifrit.git
version: 0.1.3
inflector:
git: https://github.com/phoffer/inflector.cr.git
version: 1.0.0
jennifer:
git: https://github.com/imdrasil/jennifer.cr.git
version: 0.11.0
kemal:
git: https://gitdab.com/luna/kemal.git
version: 1.0.0+git.commit.bba5bef50506f7572db9fcdeb107c65709bf1244
kilt:
git: https://github.com/jeromegn/kilt.git
version: 0.6.1
ksuid:
git: https://github.com/janeptrv/ksuid.cr.git
version: 0.5.2
pg:
git: https://github.com/will/crystal-pg.git
version: 0.23.2
pool:
git: https://github.com/ysbaddaden/pool.git
version: 0.2.4
radix:
git: https://github.com/luislavena/radix.git
version: 0.4.1
redis:
git: https://github.com/stefanwille/crystal-redis.git
version: 2.8.0
sam:
git: https://github.com/imdrasil/sam.cr.git
version: 0.4.1
spec-kemal:
git: https://gitdab.com/luna/spec-kemal.git
version: 1.0.0+git.commit.e4765ff11d66d705438b9c79e77665d85e4ef8f4

37
backend/shard.yml Normal file
View File

@ -0,0 +1,37 @@
name: backend
version: 0.1.0
authors:
- Jane Petrovna <jane@j4.pm>
targets:
backend:
main: src/backend.cr
crystal: 1.0.0
license: MIT
dependencies:
spec-kemal:
git: https://gitdab.com/luna/spec-kemal.git
kemal:
git: https://gitdab.com/luna/kemal.git
ksuid:
github: janeptrv/ksuid.cr
email:
github: arcage/crystal-email
pg:
github: will/crystal-pg
redis:
github: stefanwille/crystal-redis
jennifer:
github: imdrasil/jennifer.cr
version: "~> 0.11.0"
sam:
github: imdrasil/sam.cr
development_dependencies:
ameba:
github: crystal-ameba/ameba
version: ~> 0.14.0

View File

@ -0,0 +1,6 @@
require "spec"
# note: we cannot spec backend.cr
# because kemal will start automatically.
# that's fine, because there's nothing of note there
# anyways.

View File

@ -0,0 +1,61 @@
require "../spec_helper"
require "../../src/utils/config"
describe Config do
before_each {
Config.load_config
}
it "secret is present" do
secret = Config.get_config_value("secret")
secret.is_a?(JSON::Any).should be_true
if secret.is_a?(JSON::Any)
secret.as_s.empty?.should be_false
end
end
it "port is present" do
port = Config.get_config_value("port")
port.is_a?(JSON::Any).should be_true
if port.is_a?(JSON::Any)
port.as_i.is_a?(Int).should be_true
port.as_i.should_not eq(0)
end
end
it "database url is present" do
url = Config.get_config_value("db_url")
url.is_a?(JSON::Any).should be_true
if url.is_a?(JSON::Any)
url.as_s.empty?.should be_false
end
end
it "mail host and port are present" do
host = Config.get_config_value("mail_host")
host.is_a?(JSON::Any).should be_true
if host.is_a?(JSON::Any)
host.as_s.empty?.should be_false
end
port = Config.get_config_value("mail_port")
port.is_a?(JSON::Any).should be_true
if port.is_a?(JSON::Any)
port.as_i.is_a?(Int).should be_true
port.as_i.should_not eq(0)
end
end
it "mail username and password are present" do
uname = Config.get_config_value("mail_username")
uname.is_a?(JSON::Any).should be_true
if uname.is_a?(JSON::Any)
uname.as_s.empty?.should be_false
end
pword = Config.get_config_value("mail_password")
pword.is_a?(JSON::Any).should be_true
if pword.is_a?(JSON::Any)
pword.as_s.empty?.should be_false
end
end
end

32
backend/src/backend.cr Normal file
View File

@ -0,0 +1,32 @@
require "kemal"
require "log"
require "./utils/config"
require "./endpoints/user"
if !Config.is_loaded
puts "loading config"
Config.load_config
end
serve_static false
# replacement for the expressjs/sequelize backend of todo.
# because javascript sucks.
module Backend
VERSION = "0.0.1"
end
get "/api/hello" do
"Hello"
end
# this is a slightly less hilarious way to get the integer value of something
# because now i am using JSON::Any. but i am going to keep this comment
# because i want to.
port = Config.get_config_value("port")
port_to_use = port.is_a?(JSON::Any) ? port.as_i : 8000
Kemal.run do |config|
server = config.server.not_nil!
server.bind_tcp "0.0.0.0", port_to_use
end

View File

View File

View File

@ -0,0 +1,16 @@
require "jennifer"
class Todo < Jennifer::Model::Base
with_timestamps
mapping(
id: {type: String, primary: true},
userid: String,
content: String,
tags: Array(String)?,
complete: Bool?,
deadline: Time?,
created_at: Time?,
updated_at: Time?,
)
end

View File

@ -0,0 +1,16 @@
require "jennifer"
class UnverifiedUser < Jennifer::Model::Base
with_timestamps
mapping(
id: {type: String, primary: true},
email: String,
discord_only_account: {type: Bool, default: false},
discord_id: String?,
password_hash: String?,
verification_token: String,
created_at: Time?,
updated_at: Time?,
)
end

View File

@ -0,0 +1,15 @@
require "jennifer"
class User < Jennifer::Model::Base
with_timestamps
mapping(
id: {type: String, primary: true},
email: String,
discord_only_account: {type: Bool, default: false},
discord_id: String?,
password_hash: String?,
created_at: Time?,
updated_at: Time?,
)
end

View File

@ -0,0 +1,53 @@
require "file"
require "json"
require "log"
class ConfigInstance
@@config = {} of String => JSON::Any
@@loaded = false
def config
@@config
end
def config=(new_value)
@@config = new_value
end
def loaded
@@loaded
end
def loaded=(new_value)
@@loaded = new_value
end
end
Instance = ConfigInstance.new
module Config
extend self
def get_config_value(key) : JSON::Any | Nil
Log.debug { "looking for #{key}" }
if Instance.config.has_key? key
Instance.config[key]
else
nil
end
end
def is_loaded : Bool
Instance.loaded
end
def load_config : Nil
loaded_config = File.open("config.json") do |file|
Hash(String, JSON::Any).from_json(file)
end
Log.debug { "loaded config is #{loaded_config}" }
Instance.config = loaded_config
Instance.loaded = true
Log.debug { "instance config is #{Instance.config}" }
end
end

View File

@ -0,0 +1,5 @@
require "jennifer"
require "redis"
module DatabaseCaching
end

View File

@ -1,5 +0,0 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"

26
env.sh
View File

@ -1,26 +0,0 @@
#!/bin/bash
args=("$@")
if [[ ${1} == "prod" ]]; then
echo "prod build"
export RUSTFLAGS=""
ARGS="--release"
if [[ ${2} ]]; then
cargo ${2} $ARGS ${args[@]:2}
else
echo "defaulting to build"
cargo build $ARGS
fi
else
echo "dev build"
export RUSTFLAGS="-Zinstrument-coverage -Zmacro-backtrace"
ARGS=""
if [[ ${1} ]]; then
cargo ${1} $ARGS ${args[@]:1}
else
echo "defaulting to build+tests"
cargo test
grcov . --binary-path ./target/debug -s . -t html --branch --ignore-not-existing -o ./test_coverage/
fi
fi

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

16
frontend/.prettierrc.yaml Normal file
View File

@ -0,0 +1,16 @@
arrowParens: 'always'
bracketSpacing: true
endOfLine: 'lf'
htmlWhitespaceSensitivity: 'css'
insertPragma: false
jsxBracketSameLine: true
jsxSingleQuote: true
printWidth: 120
proseWrap: 'preserve'
quoteProps: 'consistent'
requirePragma: false
semi: true
singleQuote: true
tabWidth: 2
trailingComma: 'none'
useTabs: false

70
frontend/README.md Normal file
View File

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `yarn build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

50
frontend/package.json Normal file
View File

@ -0,0 +1,50 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.4.0",
"@emotion/styled": "^11.3.0",
"@material-ui/core": "^5.0.0-beta.0",
"@material-ui/icons": "^4.11.2",
"@material-ui/styles": "^4.11.4",
"@reduxjs/toolkit": "^1.6.0",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "BROWSER=none react-scripts start",
"build": "BROWSER=none react-scripts build",
"test": "BROWSER=none react-scripts test",
"eject": "BROWSER=none react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -0,0 +1,13 @@
{
"hosts": {
"localhost:3000": "LOCAL",
"dev.j4.pm": "test",
"todo.j4.pm": "prod"
},
"defaultConfig": {},
"configs": {
"LOCAL": {},
"test": {"apiUrl": "https://dev.j4.pm/api"},
"prod": {"apiUrl": "https://todo.j4.pm/api"}
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
frontend/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

82
frontend/src/App.js Normal file
View File

@ -0,0 +1,82 @@
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
import RootPage from './modules/Root';
import AboutPage from './modules/About';
import AccountPage from './modules/Account';
import LoginPage from './modules/Login';
import OauthPage from './modules/Oauth';
import SignupPage from './modules/Signup';
import TodoPage from './modules/TodoList';
import { connect } from 'react-redux';
import ThemeProvider from './ThemeProvider';
import Navbar from './Navbar';
const App = (props) => {
return (
<ThemeProvider>
<Navbar />
<Router>
<Switch>
<Route path='/about'>
<AboutPage />
</Route>
<Route path='/login'>
<LoginPage />
</Route>
<Route path='/signup'>
<SignupPage />
</Route>
<Route path='/discord'>
<OauthPage />
</Route>
<PRoute path='/todos'>
<TodoPage />
</PRoute>
<PRoute path='/account'>
<AccountPage />
</PRoute>
<PRoute exact path='/'>
<RootPage />
</PRoute>
<Route path='/'>
<Redirect
to={{
pathname: '/'
}}
/>
</Route>
</Switch>
</Router>
</ThemeProvider>
);
};
const PRoute = connect(
(state) => {
return {
token: state.login.token
};
},
(dispatch, props) => {
return {};
}
)(({ children, ...props }) => {
return (
<Route
{...props}
render={({ location }) => {
return props.token !== undefined ? (
children
) : (
<Redirect
to={{
pathname: '/login',
state: { from: location }
}}
/>
);
}}
/>
);
});
export default App;

122
frontend/src/Navbar.js Normal file
View File

@ -0,0 +1,122 @@
import Grid from '@material-ui/core/Grid';
import GroupIcon from '@material-ui/icons/Group';
import SettingsIcon from '@material-ui/icons/Settings';
import AssignmentIndIcon from '@material-ui/icons/AssignmentInd';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/styles';
import { logout } from './reducers/login';
const styles = (theme) => {
return {
container: {
width: '100%'
},
flexbox: {
display: 'flex',
flexGrow: 1,
width: 'auto'
},
buttonWrapper: {
alignItems: 'flex-end'
},
button: {
alignItems: 'flex-end'
},
typography: {
margin: '5px 0px'
}
};
};
const Navbar = (props) => {
const { classes } = props;
return (
<div>
<Grid container direction='row' alignItems='flex-end' justify='flex-end' className={classes.container}>
<Grid item className={classes.flexbox}>
<Box className={classes.flexbox} />
</Grid>
<Grid item alignItems='flex-end' justify='flex-end'>
<LoginLogoutButton className={classes.buttonWrapper} {...props} />
</Grid>
</Grid>
</div>
);
};
const LoginLogoutButton = connect(
(state) => {
return {
token: state.login.token
};
},
(dispatch, props) => {
return {};
}
)(({ children, ...props }) => {
const { classes } = props;
return props.token !== undefined ? (
<>
<Button
variant='contained'
color='primary'
onClick={() => {
window.location.pathname = '/account';
}}
className={classes.button}>
<SettingsIcon />
<Typography>Settings</Typography>
</Button>
<Button
variant='contained'
color='primary'
onClick={() => {
props.logout();
}}
className={classes.button}>
<ExitToAppIcon />
<Typography className={classes.typography}>Log Out</Typography>
</Button>
</>
) : (
<>
<Button
variant='contained'
color='primary'
onClick={() => {
window.location.pathname = '/login';
}}
className={classes.button}>
<GroupIcon />
<Typography className={classes.typography}>Log In</Typography>
</Button>
<Button
variant='contained'
color='primary'
onClick={() => {
window.location.pathname = '/signup';
}}
className={classes.button}>
<AssignmentIndIcon />
<Typography className={classes.typography}>Sign Up</Typography>
</Button>
</>
);
});
export default connect(
(state, props) => {
return {};
},
(dispatch, props) => {
return {
logout: () => {
dispatch(logout());
}
};
}
)(withStyles(styles)(Navbar));

View File

@ -0,0 +1,37 @@
import CssBaseline from '@material-ui/core/CssBaseline';
import { withStyles, withTheme } from '@material-ui/styles';
import { createTheme, ThemeProvider } from '@material-ui/core/styles';
import theme from './theme';
const styles = () => {
return {
root: {
height: '100vh',
zIndex: 1,
overflow: 'hidden',
position: 'relative',
display: 'flex'
},
content: {
zIndex: 3,
flexGrow: 1
},
spacing: (n) => {
return `${n * 2}px`;
}
};
};
const ThemeWrapper = (props) => {
const { children, classes } = props;
return (
<ThemeProvider theme={createTheme(theme)}>
<CssBaseline />
<div id='main' className={classes.content}>
{children}
</div>
</ThemeProvider>
);
};
export default withTheme(withStyles(styles)(ThemeWrapper));

79
frontend/src/index.js Normal file
View File

@ -0,0 +1,79 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { configureStore } from '@reduxjs/toolkit';
import RootReducer from './reducers';
import axios from 'axios';
import logger from 'redux-logger';
const defaultConfig = {
apiUrl: 'http://localhost:8080/api'
};
const renderApp = ({ config, user }) => {
const isDev = process.env.NODE_ENV !== 'production';
const store = configureStore({
devTools: isDev,
preloadedState: {
config: config,
login: user
},
reducer: RootReducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger)
});
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
};
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
const findConfig = (fullConfig) => {
return Object.assign(fullConfig.defaultConfig, fullConfig.configs[fullConfig.hosts[window.location.host]]);
};
axios
.get('/config.json')
.then(
(success) => {
return Object.assign(defaultConfig, findConfig(success.data));
},
() => {
return defaultConfig;
}
)
.then((config) => {
const details = JSON.parse(localStorage.getItem('userDetails') || '{}');
return axios
.get(`${config.apiUrl}/user/authorized`, {
headers: {
id: details.id,
Authorization: details.token
}
})
.then(
(success) => {
return {
config,
user: details || {}
};
},
() => {
return {
config,
user: {}
};
}
);
})
.then(({ config, user }) => {
renderApp({ config, user });
});

View File

@ -0,0 +1,5 @@
const AboutPage = (props) => {
return <div></div>;
};
export default AboutPage;

View File

@ -0,0 +1,5 @@
const AccountPage = (props) => {
return <div></div>;
};
export default AccountPage;

View File

@ -0,0 +1,174 @@
import { login, forgotPassword } from '../../reducers/login';
import { useState } from 'react';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import InputAdornment from '@material-ui/core/InputAdornment';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/styles';
const styles = (theme) => { };
const LoginPage = (props) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [visible, setVisible] = useState(false);
const [error, setError] = useState(false);
const [forgotPassword, setForgotPassword] = useState(false);
const handleForgotPassword = () => {
if (!!email) {
props.forgotPassword(email);
setForgotPassword(false);
setError(false);
setEmail('');
} else {
setError(true);
}
};
return (
<Grid container alignItems='center' justify='center'>
<Grid item>
<form>
<div>
<Typography align='center' variant='h6' gutterBottom>
{forgotPassword ? 'Reset Password' : 'Sign in'}
</Typography>
<TextField
autoComplete='current-email'
error={error}
label='Email'
name='email'
type='email'
value={email}
variant='outlined'
onChange={(event) => {
return setEmail(event.target.value ?? '');
}}
onKeyPress={(event) => {
if (event.key === 'Enter') {
forgotPassword ? props.forgotPassword(email) : props.login(email, password);
}
}}
/>
{forgotPassword === false ? (
<>
<div>
<TextField
autoComplete='current-password'
label='Password'
name='password'
type={visible ? 'text' : 'password'}
value={password}
variant='outlined'
onChange={(event) => {
setPassword(event.target.value ?? '');
}}
onKeyPress={(event) => {
if (event.key === 'Enter') {
props.login(email, password);
}
}}
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<IconButton
aria-label='toggle password visibility'
onClick={() => {
return setVisible(!visible);
}}
edge='end'>
{visible ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
)
}}
/>
<div>
<Button
id='forgot-password-toggle-button'
color='secondary'
onClick={() => {
return setForgotPassword(true);
}}
size='small'>
Forgot Password?
</Button>
</div>
</div>
<Button
id='login-button'
variant='contained'
color='primary'
onClick={() => {
props.login(email, password);
}}>
Login
</Button>
</>
) : (
<Grid container>
<Grid item>
<Button
id='forgot-password-cancel-button'
variant='contained'
fullWidth
color='primary'
onClick={() => {
setForgotPassword(false);
setError(false);
}}>
Cancel
</Button>
</Grid>
<Grid item>
<Button
id='forgot-password-submit-button'
variant='contained'
color='secondary'
fullWidth
onClick={() => {
handleForgotPassword();
}}>
Continue
</Button>
</Grid>
<Grid item>
<Button
id='login-with-discord'
variant='contained'
fullWidth
color='secondary'
onClick={()=>{
}}
>Sign in with Discord</Button>
</Grid>
</Grid>
)}
</div>
</form>
</Grid>
</Grid>
);
};
export default connect(
(state) => {
return {};
},
(dispatch, props) => {
return {
login: (email, password) => {
dispatch(login(email, password));
},
forgotPassword: (email) => {
dispatch(forgotPassword(email));
}
};
}
)(withStyles(styles)(LoginPage));

View File

@ -0,0 +1,17 @@
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/styles';
const styles = (theme) => { };
const OauthPage = (props) => {
return <div>test</div>
}
export default connect(
(state) => {
return {};
},
(dispatch, props) => {
return {};
}
)(withStyles(styles)(OauthPage));

View File

@ -0,0 +1,5 @@
const RootPage = (props) => {
return <div></div>;
};
export default RootPage;

View File

@ -0,0 +1,162 @@
import { signup } from '../../reducers/login';
import { useState } from 'react';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import InputAdornment from '@material-ui/core/InputAdornment';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/styles';
const styles = (theme) => {};
const SignupPage = (props) => {
//const { classes } = props;
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [visible, setVisible] = useState(false);
const [error, setError] = useState(false);
const checkSignup = () => {
if (password !== confirmPassword) {
setError(true);
} else {
setError(false);
}
};
return (
<Grid container alignItems='center' justify='center'>
<Grid item alignItems='center' justify='center'>
<form>
<div>
<Typography align='center' variant='h6' gutterBottom>
Sign Up
</Typography>
<TextField
autoComplete='new-email'
label='Email'
name='email'
type='email'
value={email}
variant='outlined'
fullWidth
onChange={(event) => {
return setEmail(event.target.value ?? '');
}}
onKeyPress={(event) => {
if (event.key === 'Enter') {
checkSignup();
if (!error) {
props.signup(email, password);
}
}
}}
/>
<div>
<TextField
autoComplete='new-password'
label='Password'
name='password'
type={visible ? 'text' : 'password'}
value={password}
variant='outlined'
fullWidth
onChange={(event) => {
setPassword(event.target.value ?? '');
}}
onKeyPress={(event) => {
if (event.key === 'Enter') {
checkSignup();
if (!error) {
props.signup(email, password);
}
}
}}
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<IconButton
aria-label='toggle password visibility'
onClick={() => {
return setVisible(!visible);
}}
edge='end'>
{visible ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
)
}}
/>
</div>
<div>
<TextField
autoComplete='confirm-password'
label='Confirm Password'
name='confirm-password'
type={visible ? 'text' : 'password'}
error={error}
value={confirmPassword}
variant='outlined'
fullWidth
onChange={(event) => {
setConfirmPassword(event.target.value ?? '');
}}
onKeyPress={(event) => {
checkSignup();
if (event.key === 'Enter') {
if (!error) {
props.signup(email, password);
}
}
}}
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<IconButton
aria-label='toggle confirm password visibility'
onClick={() => {
return setVisible(!visible);
}}
edge='end'>
{visible ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
)
}}
/>
</div>
<Button
id='login-button'
variant='contained'
color='primary'
onClick={() => {
checkSignup();
if (!error) {
props.signup(email, password);
}
}}>
Sign Up
</Button>
</div>
</form>
</Grid>
</Grid>
);
};
export default connect(
(state) => {
return {};
},
(dispatch, props) => {
return {
signup: (email, password) => {
dispatch(signup(email, password));
}
};
}
)(withStyles(styles)(SignupPage));

View File

@ -0,0 +1,5 @@
const TodoPage = (props) => {
return <div></div>;
};
export default TodoPage;

View File

@ -0,0 +1,28 @@
import { createAction, createAsyncAction } from './utils';
import { createReducer } from '@reduxjs/toolkit';
const actions = {
refresh: 'LOCAL_STORAGE_REFRESH'
};
export const getConfigValue = createAsyncAction((dispatch, getState, config, key) => {
const payload = {
key: key,
value: JSON.parse(localStorage.getItem(key)) || undefined
};
return dispatch(refreshConfigValue(payload));
});
export const setConfigValue = createAsyncAction((dispatch, getState, config, key, value) => {
localStorage.setItem(key, JSON.stringify(value));
return dispatch(refreshConfigValue({ key: key, value: value }));
});
export const refreshConfigValue = createAction(actions.refresh, (payload) => {
return payload;
});
export default createReducer({}, (builder) => {
builder.addDefaultCase((state, action) => {
state[action.payload?.key] = action.payload?.value;
});
});

View File

@ -0,0 +1,10 @@
import { combineReducers } from '@reduxjs/toolkit';
import LocalStorageReducer from './localStorage';
import LoginReducer from './login';
import ConfigReducer from './config';
export default combineReducers({
localStorage: LocalStorageReducer,
login: LoginReducer,
config: ConfigReducer
});

View File

@ -0,0 +1,28 @@
import { createAction, createAsyncAction } from './utils';
import { createReducer } from '@reduxjs/toolkit';
const actions = {
refresh: 'LOCAL_STORAGE_REFRESH'
};
export const readLocalStorage = createAsyncAction((dispatch, getState, config, key) => {
const payload = {
key: key,
value: JSON.parse(localStorage.getItem(key)) || undefined
};
return dispatch(refreshLocalStorage(payload));
});
export const updateLocalStorage = createAsyncAction((dispatch, getState, config, key, value) => {
localStorage.setItem(key, JSON.stringify(value));
return dispatch(refreshLocalStorage({ key: key, value: value }));
});
export const refreshLocalStorage = createAction(actions.refresh, (payload) => {
return payload;
});
export default createReducer({}, (builder) => {
builder.addDefaultCase((state, action) => {
state[action.payload?.key] = action.payload?.value;
});
});

View File

@ -0,0 +1,120 @@
import axios from 'axios';
import { createAction, createAsyncAction } from './utils';
import { createReducer } from '@reduxjs/toolkit';
import { updateLocalStorage } from './localStorage';
const actions = {
update: 'UPDATE_LOGIN_DETAILS'
};
const updateLoginDetails = createAction(actions.update, (payload) => {
return payload;
});
export const login = createAsyncAction((dispatch, getState, config, email, password) => {
axios
.post(`${config.apiUrl}/user/login`, {
email: email,
password: password
})
.then(
(success) => {
console.error('success', success);
dispatch(
updateLoginDetails({
id: success.data['userid'],
token: success.data['session_token'],
error: false
})
);
dispatch(
updateLocalStorage('userDetails', {
id: success.data['userid'],
token: success.data['session_token']
})
);
window.location.pathname = '/';
},
(reject) => {
console.error(reject);
dispatch(
updateLoginDetails({
id: undefined,
token: undefined,
error: true
})
);
dispatch(
updateLocalStorage('userDetails', {
id: undefined,
token: undefined
})
);
}
);
});
export const signup = createAsyncAction((dispatch, getState, config, email, password) => {
axios
.post(`${config.apiUrl}/user/signup`, {
email: email,
password: password
})
.then(
(success) => {
console.error('success', success);
window.location.pathname = '/login';
},
(reject) => {
console.error(reject);
}
);
});
export const forgotPassword = createAsyncAction((dispatch, getState, config, email) => {});
export const logout = createAsyncAction((dispatch, getState, config) => {
const details = getState().login;
axios
.post(`${config.apiUrl}/user/logout`, {
userid: details.id,
session_token: details.token
})
.then(
(success) => {
dispatch(
updateLoginDetails({
id: undefined,
token: undefined,
error: false
})
);
dispatch(
updateLocalStorage('userDetails', {
id: undefined,
token: undefined
})
);
window.location.pathname = '/login';
},
(reject) => {
console.warn(reject);
console.warn('could not log out.');
}
);
});
export default createReducer(
{
id: undefined,
token: undefined,
error: false
},
(builder) => {
builder.addCase(actions.update, (state, action) => {
console.error(state, action);
state = { ...state, ...action?.payload };
});
}
);

View File

@ -0,0 +1,16 @@
export const createAction = (type, payload) => {
return (...args) => {
return {
type: type,
payload: payload(...args)
};
};
};
export const createAsyncAction = (payload) => {
return (...args) => {
return function (dispatch, getState, config) {
payload(dispatch, getState, getState()?.config, ...args);
};
};
};

View File

@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

13
frontend/src/theme.js Normal file
View File

@ -0,0 +1,13 @@
import grey from '@material-ui/core/colors/grey';
const theme = {
palette: {
primary: {
main: grey[200]
},
secondary: {
main: grey[200]
}
}
};
export default theme;

View File

@ -1,6 +0,0 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View File

@ -1,36 +0,0 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View File

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
DROP TABLE IF EXISTS users;

View File

@ -1,9 +0,0 @@
-- Your SQL goes here
CREATE TABLE IF NOT EXISTS users (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
discord_id VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW() NOT NULL,
updated_at TIMESTAMP DEFAULT NOW() NOT NULL
);
SELECT diesel_manage_updated_at('users');

View File

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
DROP TABLE IF EXISTS blocks;

View File

@ -1,12 +0,0 @@
-- Your SQL goes here
CREATE TABLE IF NOT EXISTS blocks (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
user_id UUID NOT NULL,
block_type VARCHAR(255) NOT NULL,
props JSON NOT NULL,
children TEXT[],
created_at TIMESTAMP DEFAULT NOW() NOT NULL,
updated_at TIMESTAMP DEFAULT NOW() NOT NULL
);
SELECT diesel_manage_updated_at('blocks');

View File

@ -1,15 +0,0 @@
use axum::{prelude::*, routing::BoxRoute};
pub mod block;
pub mod discord;
pub mod user;
async fn hello() -> &'static str {
"Hi"
}
pub fn get_routes() -> BoxRoute<Body> {
route("/api/hello", any(hello))
.nest("/api/auth", discord::get_routes())
.boxed()
}

View File

@ -1,222 +0,0 @@
use async_redis_session::RedisSessionStore;
use async_session::{Session, SessionStore};
use axum::{
async_trait,
extract::{Extension, FromRequest, Query, RequestParts, TypedHeader},
prelude::*,
response::IntoResponse,
routing::BoxRoute,
AddExtensionLayer,
};
use http::{header::SET_COOKIE, StatusCode};
use hyper::Body;
use oauth2::{
basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId,
ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
};
use serde::{Deserialize, Serialize};
use std::env;
static COOKIE_NAME: &str = "SESSION";
pub fn oauth_client() -> BasicClient {
// Environment variables (* = required):
// *"CLIENT_ID" "123456789123456789";
// *"CLIENT_SECRET" "rAn60Mch4ra-CTErsSf-r04utHcLienT";
// "REDIRECT_URL" "http://127.0.0.1:3000/auth/authorized";
// "AUTH_URL" "https://discord.com/api/oauth2/authorize?response_type=code";
// "TOKEN_URL" "https://discord.com/api/oauth2/token";
let client_id = env::var("CLIENT_ID").expect("Missing CLIENT_ID!");
let client_secret = env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET!");
let redirect_url = env::var("REDIRECT_URL")
.unwrap_or_else(|_| "http://127.0.0.1:3000/auth/authorized".to_string());
let auth_url = env::var("AUTH_URL").unwrap_or_else(|_| {
"https://discord.com/api/oauth2/authorize?response_type=code".to_string()
});
let token_url = env::var("TOKEN_URL")
.unwrap_or_else(|_| "https://discord.com/api/oauth2/token".to_string());
let client = BasicClient::new(
ClientId::new(client_id),
Some(ClientSecret::new(client_secret)),
AuthUrl::new(auth_url).unwrap(),
Some(TokenUrl::new(token_url).unwrap()),
)
.set_redirect_uri(RedirectUrl::new(redirect_url).unwrap());
tracing::debug!("client: {:?}", client);
client
}
// The user data we'll get back from Discord.
// https://discord.com/developers/docs/resources/user#user-object-user-structure
#[derive(Debug, Serialize, Deserialize)]
struct DiscordUser {
id: String,
avatar: Option<String>,
username: String,
discriminator: String,
}
// Session is optional
async fn index(user: Option<DiscordUser>) -> impl IntoResponse {
match user {
Some(u) => format!(
"Hey {}! You're logged in!\nYou may now access `/protected`.\nLog out with `/logout`.",
u.username
),
None => "You're not logged in.\nVisit `/auth/discord` to do so.".to_string(),
}
}
async fn discord_auth(Extension(client): Extension<BasicClient>) -> impl IntoResponse {
let (auth_url, _csrf_token) = client
.authorize_url(CsrfToken::new_random)
.add_scope(Scope::new("identify".to_string()))
.url();
// Redirect to Discord's oauth service
Redirect(auth_url.into())
}
// Valid user session required. If there is none, redirect to the auth page
async fn protected(user: DiscordUser) -> impl IntoResponse {
serde_json::to_string(&user).expect("could not serialize user")
}
async fn avatar_url(user: DiscordUser) -> impl IntoResponse {
let cdn_url = env::var("CDN_URL").unwrap_or_else(|_| "https://cdn.discordapp.com".to_string());
match user.avatar {
Some(id) => format!("{}/avatars/{}/{}.webp?size=256", cdn_url, user.id, id),
None => format!("{}/embed/avatars/0.png?size=256", cdn_url),
}
}
async fn logout(
Extension(store): Extension<RedisSessionStore>,
TypedHeader(cookies): TypedHeader<headers::Cookie>,
) -> impl IntoResponse {
let cookie = cookies.get(COOKIE_NAME).unwrap();
let session = match store.load_session(cookie.to_string()).await.unwrap() {
Some(s) => s,
// No session active, just redirect
None => return Redirect("/".to_string()),
};
store.destroy_session(session).await.unwrap();
Redirect("/".to_string())
}
#[derive(Debug, Deserialize)]
struct AuthRequest {
code: String,
state: String,
}
async fn login_authorized(
Query(query): Query<AuthRequest>,
Extension(store): Extension<RedisSessionStore>,
Extension(oauth_client): Extension<BasicClient>,
) -> impl IntoResponse {
// Get an auth token
let token = oauth_client
.exchange_code(AuthorizationCode::new(query.code.clone()))
.request_async(async_http_client)
.await
.unwrap();
// Fetch user data from discord
let client = reqwest::Client::new();
let user_data: DiscordUser = client
// https://discord.com/developers/docs/resources/user#get-current-user
.get("https://discordapp.com/api/users/@me")
.bearer_auth(token.access_token().secret())
.send()
.await
.unwrap()
.json::<DiscordUser>()
.await
.unwrap();
// Create a new session filled with user data
let mut session = Session::new();
session.insert("user", &user_data).unwrap();
// Store session and get corresponding cookie
let cookie = store.store_session(session).await.unwrap().unwrap();
// Build the cookie
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie);
// Set cookie
let r = http::Response::builder()
.header("Location", "/")
.header(SET_COOKIE, cookie)
.status(302);
r.body(Body::empty()).unwrap()
}
// Utility to save some lines of code
struct Redirect(String);
impl IntoResponse for Redirect {
fn into_response(self) -> http::Response<Body> {
let builder = http::Response::builder()
.header("Location", self.0)
.status(StatusCode::FOUND);
builder.body(Body::empty()).unwrap()
}
}
struct AuthRedirect;
impl IntoResponse for AuthRedirect {
fn into_response(self) -> http::Response<Body> {
Redirect("/auth/discord".to_string()).into_response()
}
}
#[async_trait]
impl<B> FromRequest<B> for DiscordUser
where
B: Send,
{
// If anything goes wrong or no session is found, redirect to the auth page
type Rejection = AuthRedirect;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let extract::Extension(store) = extract::Extension::<RedisSessionStore>::from_request(req)
.await
.expect("`RedisSessionStore` extension is missing");
let cookies: TypedHeader<headers::Cookie> =
TypedHeader::<headers::Cookie>::from_request(req)
.await
.expect("could not get cookies");
let session_cookie = cookies.0.get(COOKIE_NAME).ok_or(AuthRedirect)?;
let session = store
.load_session(session_cookie.to_string())
.await
.unwrap()
.ok_or(AuthRedirect)?;
let user = session.get::<DiscordUser>("user").ok_or(AuthRedirect)?;
Ok(user)
}
}
pub fn get_routes() -> BoxRoute<Body> {
route("/", get(index))
.route("/discord", get(discord_auth))
.route("/authorized", get(login_authorized))
.route("/protected", get(protected))
.route("/avatar", get(avatar_url))
.route("/logout", get(logout))
.layer(AddExtensionLayer::new(oauth_client()))
.boxed()
}

View File

@ -1 +0,0 @@

View File

@ -1,2 +0,0 @@
pub mod block;
pub mod user;

View File

@ -1,57 +0,0 @@
use crate::diesel::{prelude::*, QueryDsl};
use crate::models::*;
use crate::schema::*;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel_tracing::pg::InstrumentedPgConnection;
use std::error::Error;
use tokio_diesel::*;
use uuid::Uuid;
pub async fn create_block(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
block: InsertableBlock,
) -> Result<Block, Box<dyn Error>> {
let inserted: Block = diesel::insert_into(blocks::table)
.values(block)
.get_result_async(pool)
.await?;
Ok(inserted)
}
pub async fn update_block(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
block: Block,
) -> Result<Block, Box<dyn Error>> {
use crate::schema::blocks::dsl::*;
let result = diesel::update(blocks.filter(id.eq(block.id)))
.set((
block_type.eq(block.block_type),
children.eq(block.children),
props.eq(block.props),
user_id.eq(block.user_id),
))
.get_result_async(pool)
.await?;
Ok(result)
}
pub async fn find_block_by_id(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
block_id: Uuid,
) -> Result<Block, Box<dyn Error>> {
use crate::schema::blocks::dsl::*;
let result: Block = blocks.find(block_id).get_result_async(pool).await?;
log::error!("{:?}", result);
Ok(result)
}
pub async fn delete_block_by_id(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
block_id: Uuid,
) -> Result<Block, Box<dyn Error>> {
use crate::schema::blocks::dsl::*;
let result: Block = diesel::delete(blocks.filter(id.eq(block_id)))
.get_result_async(pool)
.await?;
Ok(result)
}

View File

@ -1,52 +0,0 @@
use crate::diesel::{prelude::*, QueryDsl};
use crate::models::*;
use crate::schema::*;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel_tracing::pg::InstrumentedPgConnection;
use std::error::Error;
use tokio_diesel::*;
use uuid::Uuid;
pub async fn create_user(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
user: InsertableUser,
) -> Result<User, Box<dyn Error>> {
let inserted: User = diesel::insert_into(users::table)
.values(user)
.get_result_async(pool)
.await?;
Ok(inserted)
}
pub async fn update_user(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
user: User,
) -> Result<User, Box<dyn Error>> {
use crate::schema::users::dsl::*;
let result = diesel::update(users.filter(id.eq(user.id)))
.set((discord_id.eq(user.discord_id),))
.get_result_async(pool)
.await?;
Ok(result)
}
pub async fn find_user_by_id(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
user_id: Uuid,
) -> Result<User, Box<dyn Error>> {
use crate::schema::users::dsl::*;
let result = users.find(user_id).get_result_async::<User>(pool).await?;
log::error!("{:?}", result);
Ok(result)
}
pub async fn delete_user_by_id(
pool: &Pool<ConnectionManager<InstrumentedPgConnection>>,
user_id: Uuid,
) -> Result<User, Box<dyn Error>> {
use crate::schema::users::dsl::*;
let result = diesel::delete(users.filter(id.eq(user_id)))
.get_result_async(pool)
.await?;
Ok(result)
}

View File

@ -1,88 +0,0 @@
use axum::prelude::*;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use async_redis_session::RedisSessionStore;
use axum::AddExtensionLayer;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel_tracing::pg::InstrumentedPgConnection;
use dotenv::dotenv;
use std::env;
use std::str::FromStr;
use tower_http::trace::TraceLayer;
#[macro_use]
extern crate diesel;
extern crate redis;
mod endpoints;
pub mod helpers;
pub mod migration;
pub mod models;
pub mod schema;
pub mod tests;
#[tokio::main]
async fn main() {
dotenv().ok();
let _ = setup_logger();
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
migration::run_migrations(&db_url);
let manager = ConnectionManager::<InstrumentedPgConnection>::new(&db_url);
let pool = Pool::builder()
.build(manager)
.expect("Could not build connection pool");
let redis_url = env::var("REDIS_URL").unwrap_or(String::from("redis://localhost"));
let redis_client =
redis::Client::open(redis_url.as_str()).expect("Could not create redis client.");
let root = endpoints::get_routes()
.layer(TraceLayer::new_for_http())
.layer(AddExtensionLayer::new(RedisSessionStore::from_client(
redis_client,
)))
.layer(AddExtensionLayer::new(pool));
let ip = env::var("IP").unwrap_or(String::from("127.0.0.1"));
let port = env::var("PORT").unwrap_or(String::from("8000"));
let addr = SocketAddr::from((
IpAddr::from_str(ip.as_str()).unwrap_or(IpAddr::from(Ipv4Addr::new(127, 0, 0, 1))),
port.parse().unwrap_or(8000),
));
log::info!("started listening on {:?}", addr);
hyper::Server::bind(&addr)
.serve(root.into_make_service())
.await
.unwrap();
}
fn setup_logger() -> () {
let log_level = env::var("LOG_LEVEL").unwrap_or(String::from("INFO"));
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(
tracing::Level::from_str(log_level.as_str()).unwrap_or(tracing::Level::INFO),
)
.finish();
tracing_log::LogTracer::init().expect("could not init log tracer");
tracing::subscriber::set_global_default(subscriber).expect("could not set default subscriber");
// fern::Dispatch::new()
// .format(|out, message, record| {
// out.finish(format_args!(
// "{} <{}> [{}] {}",
// chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
// record.file().unwrap_or(record.target()),
// record.level(),
// message
// ))
// })
// .level(log::LevelFilter::from_str(log_level.as_str()).unwrap_or(log::LevelFilter::Info))
// .chain(std::io::stdout())
// .chain(fern::log_file("latest.log")?)
// .apply()?;
// Ok(())
}

View File

@ -1,22 +0,0 @@
use diesel::{prelude::*, sql_query};
use diesel_migrations::*;
pub fn reset_database(url: &String) {
let conn = PgConnection::establish(&url).expect(&format!("Error connecting to {}", url));
println!("dropping all tables");
let _ = sql_query("drop table users;").execute(&conn);
let _ = sql_query("drop table unverified_users;").execute(&conn);
let _ = sql_query("drop table blocks;").execute(&conn);
let _ = sql_query("drop table __diesel_schema_migrations;").execute(&conn);
println!("finished resetting db");
}
pub fn run_migrations(url: &String) {
println!("running migrations");
let conn = PgConnection::establish(&url).expect(&format!("Error connecting to {}", url));
let result = run_pending_migrations(&conn);
if result.is_err() {
panic!("could not run migrations: {}", result.err().unwrap());
}
println!("finished migrations");
}

View File

@ -1,38 +0,0 @@
use super::schema::*;
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Queryable, Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct User {
pub id: Uuid,
pub discord_id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
#[derive(Insertable, Debug, Clone, PartialEq)]
#[table_name = "users"]
pub struct InsertableUser {
pub discord_id: String,
}
#[derive(Queryable, Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Block {
pub id: Uuid,
pub user_id: Uuid,
pub block_type: String,
pub props: serde_json::Value,
pub children: Option<Vec<String>>,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
#[derive(Insertable, Debug, Clone, PartialEq)]
#[table_name = "blocks"]
pub struct InsertableBlock {
pub user_id: Uuid,
pub block_type: String,
pub props: serde_json::Value,
pub children: Option<Vec<String>>,
}

View File

@ -1,47 +0,0 @@
table! {
blocks (id) {
id -> Uuid,
user_id -> Uuid,
block_type -> Varchar,
props -> Json,
children -> Nullable<Array<Text>>,
created_at -> Timestamp,
updated_at -> Timestamp,
}
}
table! {
migration_versions (id) {
id -> Int4,
version -> Varchar,
}
}
table! {
unverifiedusers (id) {
id -> Varchar,
email -> Nullable<Varchar>,
discord_only_account -> Nullable<Bool>,
discord_id -> Nullable<Varchar>,
password_hash -> Nullable<Varchar>,
verification_token -> Nullable<Varchar>,
created_at -> Timestamp,
updated_at -> Timestamp,
}
}
table! {
users (id) {
id -> Uuid,
discord_id -> Varchar,
created_at -> Timestamp,
updated_at -> Timestamp,
}
}
allow_tables_to_appear_in_same_query!(
blocks,
migration_versions,
unverifiedusers,
users,
);

View File

@ -1,18 +0,0 @@
pub mod db;
#[cfg(test)]
mod tests {
// a basic test to ensure that tests are executing.
#[test]
fn works() {
assert_eq!(1, 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn db_tests() {
let url = String::from("postgres://postgres@localhost/todo_test");
crate::migration::reset_database(&url);
crate::migration::run_migrations(&url);
super::db::run_tests(&url).await;
}
}

View File

@ -1,131 +0,0 @@
use crate::helpers::*;
use crate::models::*;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel_tracing::pg::InstrumentedPgConnection;
use std::{error::Error, vec::Vec};
use uuid::Uuid;
async fn get_pool(url: &String) -> Pool<ConnectionManager<InstrumentedPgConnection>> {
let manager = ConnectionManager::<InstrumentedPgConnection>::new(url);
Pool::builder()
.build(manager)
.expect("Could not build connection pool")
}
async fn user_tests(pool: &Pool<ConnectionManager<InstrumentedPgConnection>>) {
let user = InsertableUser {
discord_id: String::from("test"),
};
let created_result = user::create_user(pool, user).await;
if created_result.is_err() {
panic!("could not create user: {:?}", created_result.err());
} else {
assert!(created_result.is_ok());
}
let created_user: User = created_result.unwrap();
let mut new_user = created_user.clone();
new_user.discord_id = String::from("test2");
let user_update = new_user.clone();
let updated_result: Result<User, Box<dyn Error>> = user::update_user(pool, user_update).await;
if updated_result.is_err() {
panic!(
"cound not update user {}: {:?}",
created_user.id,
updated_result.err()
);
}
let updated_user = updated_result.unwrap();
assert_eq!(new_user.id, updated_user.id);
assert_eq!(new_user.discord_id, updated_user.discord_id);
let get_result = user::find_user_by_id(pool, created_user.id).await;
if get_result.is_err() {
panic!(
"could not find previously created user {}: {:?}",
created_user.id,
get_result.err()
);
} else {
assert_eq!(updated_user, get_result.unwrap());
}
let delete_result = user::delete_user_by_id(pool, created_user.id).await;
if delete_result.is_err() {
panic!(
"could not delete user {}: {:?}",
created_user.id,
delete_result.err()
);
}
}
async fn block_tests(pool: &Pool<ConnectionManager<InstrumentedPgConnection>>) {
let json = serde_json::from_str("[]");
let block = InsertableBlock {
user_id: Uuid::new_v4(),
block_type: String::from("test"),
children: Some(Vec::new()),
props: json.unwrap(),
};
let created_result = block::create_block(pool, block).await;
if created_result.is_err() {
panic!("could not create block: {:?}", created_result.err());
} else {
assert!(created_result.is_ok());
}
let created_block: Block = created_result.unwrap();
let mut new_block = created_block.clone();
new_block.block_type = String::from("test2");
let block_update = new_block.clone();
let updated_result: Result<Block, Box<dyn Error>> =
block::update_block(pool, block_update).await;
if updated_result.is_err() {
panic!(
"cound not update block {}: {:?}",
created_block.id,
updated_result.err()
);
}
let updated_block = updated_result.unwrap();
assert_eq!(new_block.id, updated_block.id);
assert_eq!(new_block.block_type, updated_block.block_type);
assert_eq!(new_block.user_id, updated_block.user_id);
assert_eq!(new_block.children, updated_block.children);
assert_eq!(new_block.props, updated_block.props);
let get_result = block::find_block_by_id(pool, created_block.id).await;
if get_result.is_err() {
panic!(
"could not find previously created block {}: {:?}",
created_block.id,
get_result.err()
);
} else {
assert_eq!(updated_block, get_result.unwrap());
}
let delete_result = block::delete_block_by_id(pool, created_block.id).await;
if delete_result.is_err() {
panic!(
"could not delete block {}: {:?}",
created_block.id,
delete_result.err()
);
}
}
pub async fn run_tests(url: &String) {
let pool = get_pool(url).await;
user_tests(&pool).await;
block_tests(&pool).await;
}