initial commit

This commit is contained in:
nihonium 2023-01-15 13:53:21 +03:00
commit 3b3c9a9417
Signed by: nihonium
GPG key ID: 0251623741027CFC
258 changed files with 20086 additions and 0 deletions

View file

@ -0,0 +1,17 @@
FROM python:3-slim
RUN useradd -ms /bin/bash volgactf
RUN pip install --no-cache-dir quart nanoid requests flask_sqlalchemy aiohttp psycopg2-binary quart-cors
WORKDIR /home/volgactf/dist
COPY . ./
RUN chown -R volgactf:volgactf /home/volgactf/dist
USER volgactf
CMD python routes.py

View file

@ -0,0 +1,12 @@
from quart import Quart
from flask_sqlalchemy import SQLAlchemy
import os, re
from quart_cors import cors, route_cors
app = Quart(__name__)
app = cors(app, allow_origin=re.compile(r"http:\/\/.*:3000"), allow_credentials=True)#cors(app, allow_origin="http://10.50.20.4:3000", allow_credentials=True)
app.config["REDIRECT_SERVER"] = os.getenv('REDIRECT_SERVER') or "127.0.0.1:8080"#"10.50.20.7:8080"
app.config["CONTENT_SERVER"] = os.getenv('CONTENT_SERVER') or "127.0.0.1:13379"#"10.50.20.6:13379"
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv('SQLALCHEMY_DATABASE_URI') or 'sqlite:///data.db'
app.config["SECRET_KEY"] = 'hack_me'
db = SQLAlchemy(app)

View file

@ -0,0 +1,45 @@
from werkzeug.security import generate_password_hash, check_password_hash
from nanoid import generate
from . import db
class User(db.Model):
def __init__(self, username, blog_url):
self.username = username
self.blog_url = blog_url
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Text, unique=True)
password = db.Column(db.Text)
blog_url = db.Column(db.Text, db.ForeignKey('blogs.url', ondelete='CASCADE'), unique=True)
blog = db.relationship('Blog', backref='blog_user', cascade="all,delete")
def set_password(self, password):
self.password = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password, password)
class Blog(db.Model):
def __init__(self, url, is_private=False):
self.url = url
self.is_private = is_private
__tablename__ = "blogs"
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.Text, unique=True)
is_private = db.Column(db.Boolean, default=False) #TODO this is must be private (VULN)
user = db.relationship('User', backref='blog_user', cascade="all,delete", lazy='dynamic')
posts = db.relationship("Post", cascade="all,delete")
#TODO дописать стуруктуру БД
class Post(db.Model):
def __init__(self, title, body, blog_url):
self.title = title
self.body = body
self.blog_url = blog_url
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
body = db.Column(db.String)
blog_url = db.Column(db.String, db.ForeignKey("blogs.url"))
blog = db.relationship("Blog", cascade="all,delete")

View file

@ -0,0 +1,11 @@
from app import app, db
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
if __name__ == "__main__":
def get_db():
if 'db' not in g:
g.db = SQLAlchemy(current_app)
return g.db
get_db().create_all()
#db.create_all()

View file

@ -0,0 +1,255 @@
from quart import request, Response, render_template, session, redirect, jsonify, abort, current_app, url_for
import aiohttp
from app import app, db
from app.models import User, Blog, Post
from nanoid import generate
from functools import wraps
import json
from quart_cors import route_cors
@app.before_first_request
def create_tables():
db.create_all()
def user_cook(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
if session.get('username'):
return await current_app.ensure_async(f)(*args, **kwargs)
else:
return abort(403)
return decorated_function
@app.route('/health_check')
#@route_cors()
async def health_check():
status1, _, _, _ = await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/health_check")
status2, _, _, _ = await get_request(f"http://{app.config.get('CONTENT_SERVER')}/health_check")
if status1 == 200 and status2 == 200:
return "OK"
else:
return "Not OK", 500
@app.route('/health_check2')
#@route_cors()
async def health_check2():
return "OK"
@app.route('/image/<path>')
#@route_cors()
async def get_image(path): # put application's code here
#if x.get(""): #if valid image (example 404, 405, corrupted_image)
#...
#else:
path2 = request.args.get("another") #путь до картинки (логика хранения картинки как в CDN (начало пути - начало хеша).
filename = request.args.get("filename")
content_server = app.config.get("CONTENT_SERVER")
if path2 == 'secrets' or path == 'secrets':
return abort(403)
status_code, json_data, data_data, headers = await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/{path}/{content_server}?filename={filename}")
if status_code == 200:
if len(filename.split('.')) > 0 and filename.split('.')[-1] == 'png':
content_type = "Content-Type: image/png"
return Response(
response=data_data,
content_type=content_type,
status=status_code
)
else:
status_code, json_data, data_data, headers = await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/{path2}/{content_server}?filename={filename}")
content_type = headers.get("Content-Type")
if len(filename.split('.')) > 0 and filename.split('.')[-1] == 'png':
content_type = "Content-Type: image/png"
return Response(
response=data_data,
content_type=content_type,
status=status_code
)
async def post_request(url, headers={}, json_inp=None, data=None, cookies=None):
async with aiohttp.ClientSession(cookies=cookies, skip_auto_headers={"User-Agent"}) as session:
async with session.post(url, headers=headers, json=json_inp, data=data) as r:
data = ""
json_data = ""
if hasattr(r, "data"):
data = await r.data
if r.content_type == 'application/json':
json_data = await r.json()
return r.status, json_data, data, r.headers
async def get_request(url, headers={}, cookies={}):
async with aiohttp.ClientSession(cookies=cookies, skip_auto_headers={"User-Agent"}) as session:
async with session.get(url, headers=headers) as r:
data = ""
json_data = ""
if r.content_type == 'application/json':
json_data = await r.json()
return r.status, json_data, data, r.headers
if hasattr(r, "data"):
data = r.data
elif hasattr(r, "content"):
data = await r.content.read()
return r.status, json_data, data, r.headers
@app.route('/file/get/<path>', methods=['GET'])
#@route_cors()
@user_cook
async def get_file(path): # put application's code here
async def check_access(username, filename):
status_code, _, _, _ = await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/check_access?filename={filename}&username={username}")
if status_code == 200:
return True
else:
return False
filename = request.args.get("filename")
content_server = app.config.get("CONTENT_SERVER")
if not await check_access(session.get("username"), filename):
return abort(403)
status_code, json_data, data_data, header = await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/{path}/{content_server}?filename={filename}")
content_type = header.get("Content-Type")
if len(filename.split('.')) > 0 and filename.split('.')[-1] == 'png':
content_type = "Content-Type: image/png"
return Response(
response=data_data,
content_type=content_type,
status=status_code
)
@app.route('/file/list')
#@route_cors()
async def file_list():
content_server = app.config.get("CONTENT_SERVER")
path = request.args.get('path')
status_code, json_data, _, headers = await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/file_list/{path}/{content_server}")
return Response(
response=json.dumps(json_data),
content_type=headers.get('Content-Type'),
status=status_code)
@app.route('/file/upload', methods=['POST'])
#@route_cors()
@user_cook
async def upload_image():
if request.method == 'POST':
if 'file' not in await request.files:
return abort(403)
content_server = app.config.get("CONTENT_SERVER")
path = request.args.get("path")
username = session.get("username")
form_data = aiohttp.FormData()
file_bytes = (await request.files).get('file').stream.read()
filename = (await request.files).get("file").filename
form_data.add_field(name='file', value=file_bytes , filename=filename)
form_data.add_field(name="username", value=username)
form_data.add_field(name="filename", value=filename)
status_code, json_data, data_data, headers = await post_request(f"http://{app.config.get('REDIRECT_SERVER')}/{path}/{content_server}",
data=form_data)
return Response(
response=json.dumps(json_data),
content_type=headers.get('Content-Type'),
status=status_code
)
@app.route('/api/auth/sign_up', methods=["POST"])
#@route_cors()
async def sign_up():
username = (await request.json).get("username")
password = (await request.json).get("password")
is_private = (await request.json).get("is_private")
if username and password:
url_id = generate('1234567890abcdef', 12)
user = User(username=username, blog_url=url_id)
user.set_password(password)
blog = Blog(url_id, is_private)
db.session.add(user)
db.session.add(blog)
db.session.commit()
session["username"] = user.username
return jsonify({"Status": "OK"})
else:
return abort(403)
@app.route('/api/auth/sign_in', methods=["POST"])
async def sign_in():
username = (await request.json).get("username")
password = (await request.json).get("password")
if username and password:
user = User.query.filter_by(username=username).first()
if user is None or not user.check_password(password):
return jsonify({"Result": "Bad creads"}), 400
else:
session["username"] = user.username
return jsonify({"Result": "OK"})
@app.route('/api/self_delete')
#@route_cors()
@user_cook
async def self_remove_acc():
username = session.get("username")
user = User.query.filter_by(username=username).first()
db.session.delete(user)
db.session.commit()
await get_request(f"http://{app.config.get('REDIRECT_SERVER')}/delete/{username}/{app.config.get('CONTENT_SERVER')}")
return jsonify({"result": "OK"})
@app.route('/api/blog')
#@route_cors()
@user_cook
async def get_my_blog():
user = User.query.filter_by(username=session.get("username")).first()
blog = Blog.query.filter_by(url=user.blog_url).first()
return jsonify({"url": blog.url, "is_private": blog.is_private})
@app.route('/api/blogs')
#@route_cors()
async def get_blogs():
blogs = Blog.query.with_entities(Blog.url, Blog.is_private).all()
blogs_list = [{"url": i.url, "is_private": i.is_private} for i in blogs]
return jsonify(blogs_list)
@app.route('/api/blog/<url_id>')
#@route_cors()
@user_cook
async def blog_get_posts(url_id):
blog = Blog.query.filter_by(url=url_id).first()
if blog:
if blog.posts:
return jsonify({"posts": list(map(lambda x: {"id":x.id, "title":x.title}, blog.posts))})
else:
return jsonify({"error": "?"})
else:
return jsonify({"error": "?"})
@app.route('/api/blog/<url_id>/create_post', methods=["POST"])
#@route_cors()
@user_cook
async def blog_create_post(url_id):
blog = Blog.query.filter_by(url=url_id).first()
title = (await request.json).get("title")
body = (await request.json).get("body")
post = Post(title=title, body=body, blog_url=blog.url)
db.session.add(post)
db.session.commit()
this_post = Post.query.filter_by(title=title, body=body).all()[-1]
return jsonify({"Result": "OK", "post_id": this_post.id})
@app.route('/api/blog/<url_id>/post/<int:post_id>')
#@route_cors()
@user_cook
async def blog_read_post(url_id, post_id):
post = Post.query.filter_by(blog_url=url_id, id=post_id).first()
return jsonify({"title": post.title, "body": post.body})
if __name__ == '__main__':
app.run(port=13377, host="0.0.0.0", debug=False)

View file

@ -0,0 +1,16 @@
FROM python:3-slim
RUN useradd -ms /bin/bash volgactf
RUN pip install --no-cache-dir flask
WORKDIR /home/volgactf/dist
COPY . ./
RUN chown -R volgactf:volgactf /home/volgactf/dist
USER volgactf
CMD python app.py

View file

@ -0,0 +1,51 @@
from flask import Flask, send_from_directory, current_app, request, jsonify
from werkzeug.utils import secure_filename
import os
import glob
app = Flask(__name__)
@app.route('/health_check', methods=['GET'])
def health_check():
return "OK", 200
@app.route('/<string:path>', methods=['GET'])
def download(path):
filename = secure_filename(request.args.get("filename"))
uploads = os.path.join(current_app.root_path, path) #file_upload ????
return send_from_directory(directory=uploads, path=filename)
@app.route('/file_list/<string:path>', methods=['GET'])
def file_list(path):
file_list = []
for files in glob.glob(current_app.root_path+'/'+path + '/*'):
file_list.append(files.split('/')[-1])
return jsonify(file_list)
@app.route('/upload/<string:path>', methods=['POST'])
def upload(path):
key = request.files
file = request.files.get(next(iter(key)))
filename = secure_filename(file.filename)
uploads = os.path.join(current_app.root_path, path)
if not os.path.exists(uploads):
os.mkdir(uploads)
file.save(uploads+"/"+filename)
return jsonify({"filename": filename})
@app.route('/delete', methods=['GET'])
def delete():
filename = request.args.get("filename")
filename = secure_filename(filename)
path = "secrets"
delete_path = os.path.join(current_app.root_path, path)
if os.path.exists(delete_path+"/"+filename):
os.remove(delete_path+"/"+filename)
return jsonify({"result": "ok"})
else:
return jsonify({"result": "NOT OK"})
if __name__ == '__main__':
app.run(debug=False, host="0.0.0.0", port=13379)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -0,0 +1,80 @@
version: '3.4'
services:
blog_frontend_server:
build: ./frontend
restart: always
container_name: "blog_frontend_server"
ports:
- 3000:3000
networks:
myblog-network:
ipv4_address: 10.50.20.4
blog_api_server:
image: "blog_api_server"
container_name: "blog_api_server"
build: ./api_server
environment:
REDIRECT_SERVER: "10.50.20.7:8080"
CONTENT_SERVER: "10.50.20.6:13379"
SQLALCHEMY_DATABASE_URI: "postgresql://postgres:postgres@10.50.20.8:5432/mydb"
ports:
- 13377:13377
restart: always
networks:
myblog-network:
ipv4_address: 10.50.20.5
depends_on:
- db
blog_content_server:
image: "blog_content_server"
container_name: "blog_content_server"
build: ./content_server
expose:
- 13379
restart: always
networks:
myblog-network:
ipv4_address: 10.50.20.6
blog_redirector_server:
image: "blog_redirector_server"
container_name: "blog_redirector_server"
build: ./redirector
environment:
SQLALCHEMY_DATABASE_URI: "postgresql://postgres:postgres@10.50.20.8:5432/mydb"
restart: always
expose:
- 8080
networks:
myblog-network:
ipv4_address: 10.50.20.7
depends_on:
- db
db:
image: postgres:14.5
container_name: "blog_postgres_server"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=mydb
restart: always
expose:
- 5432
networks:
myblog-network:
ipv4_address: 10.50.20.8
# command: mongod --logpath=/dev/null # --quiet
networks:
myblog-network:
driver: bridge
ipam:
driver: default
config:
- subnet: 10.50.20.0/24
gateway: 10.50.20.1

View file

@ -0,0 +1,12 @@
FROM node:alpine
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package*.json ./
RUN npm install -g npm@8.19.2 && npm config rm proxy && npm config rm https-proxy
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD npm run start

View file

@ -0,0 +1,34 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View file

@ -0,0 +1,10 @@
export interface SignIn {
username: string,
password: string,
}
export interface SignUp {
username: string;
password: string;
}

View file

@ -0,0 +1,12 @@
export interface Blog_int {
url: string,
is_private: string,
}
export interface Post_int {
posts: {
title: string;
body: string;
blog_url:string;
}
}

View file

@ -0,0 +1,10 @@
.container {
display: grid;
grid-template-columns: 1fr auto 1fr;
grid-template-rows: 100px 1fr 100px;
min-height: 100vh;
grid-template-areas:
". . ."
". form .";
}

View file

@ -0,0 +1,5 @@
import {DataHTMLAttributes, DetailedHTMLProps, HTMLAttributes, ReactNode} from "react";
export interface LayoutProps {
children: ReactNode;
}

View file

@ -0,0 +1,21 @@
import {LayoutProps} from "./Layout.props";
import styles from "./Layout.module.css"
import cn from "classnames";
import {Component, FunctionComponent} from "react";
const Layout = ({ children }: LayoutProps): JSX.Element => {
return(
<div className={styles.container} >
{children}
</div>
);
};
export const withLayout = <T extends Record<string, unknown>>(Component: FunctionComponent<T>) => {
return function withLayoutComponent(props: T): JSX.Element {
return(
<Layout>
<Component {...props} />
</Layout>
);
};
};

View file

@ -0,0 +1,84 @@
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-rows: 100px 1fr;
min-height: 100vh;
grid-template-areas:
". . header . utils"
". post . . .";
}
.utils{
display: grid;
grid-template-areas:
"signout "
"create "
"blog_list "
"read_post"
"posts_list";
grid-area: utils;
max-height: 50px;
max-width: 150px;
}
.signout{
grid-area: signout;
}
.create{
grid-area: create;
}
.blog_list{
grid-area: blog_list;
}
.post_read{
grid-area: post_read;
}
.posts_list{
grid-area: posts_list;
}
.mybtn{
margin: 5px;
--bs-btn-color: #fff;
--bs-btn-bg: #6c757d;
--bs-btn-border-color: #6c757d;
--bs-btn-hover-color: #fff;
--bs-btn-hover-bg: #5c636a;
--bs-btn-hover-border-color: #565e64;
--bs-btn-focus-shadow-rgb: 130,138,145;
--bs-btn-active-color: #fff;
--bs-btn-active-bg: #565e64;
--bs-btn-active-border-color: #51585e;
--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
--bs-btn-disabled-color: #fff;
--bs-btn-disabled-bg: #6c757d;
--bs-btn-disabled-border-color: #6c757d;
user-select: none;
border: var(--bs-btn-border-width) solid var(--bs-btn-border-color);
border-radius: var(--bs-btn-border-radius);
background-color: var(--bs-btn-bg);
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
border-radius: 5px;
font-family: var(--bs-btn-font-family);
font-size: var(--bs-btn-font-size);
font-weight: var(--bs-btn-font-weight);
line-height: var(--bs-btn-line-height);
color: var(--bs-btn-color);
text-align: center;
text-decoration: none;
}
.mybtn:hover{
color: var(--bs-btn-hover-color);
background-color: var(--bs-btn-hover-bg);
border-color: var(--bs-btn-hover-border-color);
}
.header{
grid-area: header;
}

View file

@ -0,0 +1,5 @@
import {DataHTMLAttributes, DetailedHTMLProps, HTMLAttributes, ReactNode} from "react";
export interface LayoutProps {
children: ReactNode;
}

View file

@ -0,0 +1,155 @@
import {LayoutProps} from "./Layout.props";
import styles from "./Layout.module.css"
import styles_post from "./Post/Post.module.css"
import {Post} from "./Post/Post";
import cn from "classnames";
import {Component, FunctionComponent} from "react";
import {useContext, useEffect, useState} from "react";
import Cookie from 'js-cookie';
import axios from "axios";
import {Post_int, Blog_int} from "../interfaces/blog_interface"
import blog from "../pages/blog";
import {Button, Form, Input} from "reactstrap";
const Layout = ({ children }: LayoutProps): JSX.Element => {
const [data, setData] = useState(<></>);
const [file, setFile] = useState()
function handleChange(event) {
setFile(event.target.files[0])
}
useEffect(() => {
//get_posts()
get_blog()
}, []);
function get_blog(){
if (localStorage.getItem("blog_url") == null){
axios.get<Blog_int>('http://10.50.20.5:13377/api/blog', {withCredentials: true}).then(response => {
localStorage.setItem('blog_url', response.data.url);
get_posts(response.data.url)
})
} else{
get_posts(localStorage.getItem("blog_url"))
}
}
function get_posts(blog_url: string){
axios.get<Post_int>('http://10.50.20.5:13377/api/blog/'.concat(blog_url), {withCredentials: true}).then(response => {
let jsonDataPosts = JSON.parse(JSON.stringify(response.data.posts))
let mydata: JSX.Element
jsonDataPosts.forEach((post: Post_int) => {
mydata = (
<>
<Post content={post.posts.body} title={post.posts.title}/>
{mydata}
</>)
setData(mydata)
}
)
})
}
function sign_out(){
localStorage.removeItem("blog_url")
Cookie.remove('sessions')
window.location.href = "/auth"
}
function create_post(){
axios.post("http://10.50.20.5:13377/api/blog/".concat(localStorage.getItem("blog_url")).concat("/").concat("create_post"), {"title": "test", "body":"test"}, {withCredentials: true}).then( response => {window.location.reload()})
}
function blog_list(){
axios.get("http://10.50.20.5:13377/api/blogs", {withCredentials: true}).then( response => {
let jsonDataBlogs = JSON.parse(JSON.stringify(response.data))
let mydata: JSX.Element
jsonDataBlogs.forEach((post: Blog_int) => {
mydata = (
<>
<pre><code>post.url</code></pre>
<pre><code>post.is_private</code></pre>
{mydata}
</>
)
setData(mydata)
}
)
})
}
function upload_file(){
}
function handleSubmit() {
event.preventDefault()
const url = 'http://10.50.20.5:13377/file/upload?path=file_storage';
const formData = new FormData();
formData.append('file', file);
const config = {
withCredentials: true,
headers: {
'content-type': 'multipart/form-data',
},
};
axios.post(url, formData, config).then((response) => {
console.log(response.data);
});
}
function read_post(){
let num_post = prompt("Input id your post")
axios.get("http://10.50.20.5:13377/api/blog/".concat(localStorage.getItem("blog_url")).concat("/").concat("post").concat("/").concat(num_post), {withCredentials: true}).then( response => {
let jsonDataBlogs = JSON.parse(JSON.stringify(response.data))
let mydata: JSX.Element
jsonDataBlogs.forEach((post: Blog_int) => {
mydata = (
<>
<pre><code>{mydata}</code></pre>
</>
)
setData(mydata)
}
)
})
}
return(
<div className={styles.container} >
<div className={styles.utils}>
<button className={cn(styles.signout, styles.mybtn)} onClick={function (){sign_out()}}>Sign Out</button>
<button className={cn(styles.create, styles.mybtn)} onClick={function (){create_post()}}>Create Post</button>
<button className={cn(styles.blog_list, styles.mybtn)} onClick={function (){blog_list()}}>Blogs List</button>
<button className={cn(styles.read_post, styles.mybtn)} onClick={function (){read_post()}}>Read Post</button>
<button className={cn(styles.posts_list, styles.mybtn)} onClick={function (){get_posts(localStorage.getItem("blog_url"))}}>Posts List</button>
<Form onSubmit={handleSubmit}>
<h2>Upload</h2>
<Input type="file" onChange={handleChange}></Input>
<button type="submit">Upload</button>
</Form>
</div>
<h1 className={styles.header}>Test Header</h1>
<Post className={styles_post.post} content={"test"} title={"test"}/>
{children}
</div>
);
};
export const withLayout = <T extends Record<string, unknown>>(Component: FunctionComponent<T>) => {
return function withLayoutComponent(props: T): JSX.Element {
return(
<Layout>
<Component {...props} />
</Layout>
);
};
};

View file

@ -0,0 +1,20 @@
.post{
grid-area: post;
display: grid;
grid-template-columns: 0.5fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-template-areas:
"title . ."
". content .";
max-height: 200px;
}
.title{
grid-area: title;
}
.content{
grid-area: content;
}

View file

@ -0,0 +1,7 @@
import {DataHTMLAttributes, DetailedHTMLProps, HTMLAttributes, InputHTMLAttributes, ReactNode} from "react";
export interface PostProps extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
content: string;
title: string;
}

View file

@ -0,0 +1,14 @@
import {PostProps} from "./Post.props";
import styles from "./Post.module.css"
import cn from "classnames";
export const Post = ({className, title="", content="", ...props}: PostProps): JSX.Element => {
return(
<div className={cn(styles.post, className, {
})} {...props}>
<img src={"http://10.50.20.5:13377/image/images?filename=standart_image.png"}/>
<h1 className={styles.title}>{title}</h1>
<p className={styles.content}>{content}</p>
</div>
);
}

View file

@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View file

@ -0,0 +1,10 @@
module.exports = {
webpack(config){
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
return config;
},
reactStrictMode: true,
};

5774
services/myblog/frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,29 @@
{
"name": "top-app",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.2.5",
"react-dom": "18.2.0"
},
"devDependencies": {
"@types/classnames": "^2.3.1",
"@types/node": "^18.7.14",
"@types/react": "^18.0.18",
"@typescript-eslint/eslint-plugin": "^5.36.1",
"@typescript-eslint/parser": "^5.36.1",
"axios": "^0.27.2",
"bootstrap": "^5.2.0",
"eslint": "^8.23.0",
"eslint-config-next": "12.2.5",
"js-cookie": "^3.0.1",
"jwt-decode": "^3.1.2",
"reactstrap": "^9.1.4",
"typescript": "^4.8.2"
}
}

View file

@ -0,0 +1,7 @@
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp

View file

@ -0,0 +1,5 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}

View file

@ -0,0 +1,67 @@
import {withLayout} from "../layout_auth/Layout";
import {useState} from "react";
import axios from 'axios';
import Cookie from 'js-cookie';
import {useRouter} from "next/router";
import jwtDecode from "jwt-decode";
import 'bootstrap/dist/css/bootstrap.min.css';
import {
Container, Row, Col, Form, Input, Button, Navbar, Nav,
NavbarBrand, NavLink, NavItem, UncontrolledDropdown,
DropdownToggle, DropdownMenu, DropdownItem
} from 'reactstrap';
function setUserIDLocalStrorage(token: string): void{
const decoded_token = jwtDecode<{user:{ID:string} }>(token);
localStorage.setItem('user_id', decoded_token.user.ID);
}
function Home() {
const router = useRouter();
const initialFormData = Object.freeze({
username: "",
password: ""
});
const [formData, updateFormData] = useState(initialFormData);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.value.trim()
});
};
const handleSubmit = (e: React.ChangeEvent<HTMLFormElement>) => {
e.preventDefault();
axios.post('http://10.50.20.5:13377/api/auth/sign_in', formData, {withCredentials: true})
.then(function(response){
let cook = response.headers['set-cookie']
//Cookies.set('api_session', cook)
router.push('/blog');
//Perform action based on response
})
.catch(function(error){
console.log(error);
alert("Bad creads")
//Perform action based on error
});
// ... submit to API or something
};
return (
<>
<form style={{gridArea: "form"}} onSubmit={handleSubmit}>
<h1>Sign In</h1>
<Input onChange={handleChange} name={"username"} placeholder={"Username"}/>
<Input onChange={handleChange} name={"password"} placeholder={"Password"}/>
<Button>Sign In</Button>
<NavLink href={"/register"} style={{justifySelf: "center", alignSelf: "center"}}>Sign out</NavLink>
</form>
</>
);
}
export default withLayout(Home);

View file

@ -0,0 +1,23 @@
import {withLayout} from "../layout_blog/Layout";
import {useState} from "react";
import axios from 'axios';
import Cookie from 'js-cookie';
import {useRouter} from "next/router";
import jwtDecode from "jwt-decode";
import 'bootstrap/dist/css/bootstrap.min.css';
import {
Container, Row, Col, Form, Input, Button, Navbar, Nav,
NavbarBrand, NavLink, NavItem, UncontrolledDropdown,
DropdownToggle, DropdownMenu, DropdownItem
} from 'reactstrap';
function Home() {
return (
<>
</>
);
}
export default withLayout(Home);

View file

@ -0,0 +1,56 @@
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import {useRouter} from "next/router";
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>MyBlog</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<div className={styles.grid}>
<a href="/auth" className={styles.card}>
<h2>Sign in MyBlog</h2>
</a>
<a href="/register" className={styles.card}>
<h2>Register in MyBLog</h2>
</a>
<a
href="/blog"
className={styles.card}
>
<h2>Go to blog &rarr;</h2>
</a>
</div>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>
)
}

View file

@ -0,0 +1,59 @@
import {withLayout} from "../layout_auth/Layout";
import {useState} from "react";
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import {useRouter} from "next/router";
import {
Container, Row, Col, Form, Input, Button, Navbar, NavLink
} from 'reactstrap';
function Home() {
const router = useRouter();
const initialFormData = Object.freeze({
username: "",
password: ""
});
const [formData, updateFormData] = useState(initialFormData);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.value.trim()
});
};
const handleSubmit = (e: React.ChangeEvent<HTMLFormElement>) => {
e.preventDefault();
axios.post('http://10.50.20.5:13377/api/auth/sign_up', formData)
.then(function(response){
router.push('/auth');
//Perform action based on response
})
.catch(function(error){
console.log(error);
//Perform action based on error
});
// ... submit to API or something
};
return (
<>
<form style={{gridArea: "form"}} onSubmit={handleSubmit}>
<h1>Sign Out</h1>
<Input onChange={handleChange} name={"username"} placeholder={"Username"}/>
<Input onChange={handleChange} type={"password"} name={"password"} placeholder={"Password"}/>
<Input onChange={handleChange} type={"password"} name={"password_repeat"} placeholder={"Password (repeat)"}/>
<Button>Sign Out</Button>
<NavLink href={"/auth"} style={{justifySelf: "center", alignSelf: "center"}}>Sign In</NavLink>
</form>
</>
);
}
export default withLayout(Home);

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View file

@ -0,0 +1,4 @@
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,116 @@
.container {
padding: 0 2rem;
}
.main {
min-height: 100vh;
padding: 4rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.footer {
display: flex;
flex: 1;
padding: 2rem 0;
border-top: 1px solid #eaeaea;
justify-content: center;
align-items: center;
}
.footer a {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
}
.title a {
color: #0070f3;
text-decoration: none;
}
.title a:hover,
.title a:focus,
.title a:active {
text-decoration: underline;
}
.title {
margin: 0;
line-height: 1.15;
font-size: 4rem;
}
.title,
.description {
text-align: center;
}
.description {
margin: 4rem 0;
line-height: 1.5;
font-size: 1.5rem;
}
.code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
.grid {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 800px;
}
.card {
margin: 1rem;
padding: 1.5rem;
text-align: left;
color: inherit;
text-decoration: none;
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.15s ease, border-color 0.15s ease;
max-width: 300px;
}
.card:hover,
.card:focus,
.card:active {
color: #0070f3;
border-color: #0070f3;
}
.card h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
.card p {
margin: 0;
font-size: 1.25rem;
line-height: 1.5;
}
.logo {
height: 1em;
margin-left: 0.5rem;
}
@media (max-width: 600px) {
.grid {
width: 100%;
flex-direction: column;
}
}

View file

@ -0,0 +1,16 @@
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}

View file

@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"strict": false,
"strictPropertyInitialization": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
FROM python:3-slim
RUN useradd -ms /bin/bash volgactf
RUN python -m pip install --upgrade pip
RUN pip install --no-cache-dir bobo requests sqlalchemy webob psycopg2-binary
WORKDIR /home/volgactf/dist
COPY . ./
RUN chown -R volgactf:volgactf /home/volgactf/dist
USER volgactf
CMD /bin/bash run.sh

View file

@ -0,0 +1,18 @@
import sqlalchemy
import os
db_url = os.getenv("SQLALCHEMY_DATABASE_URI") or 'sqlite:///users.db'
engine = sqlalchemy.create_engine(db_url)
metadata = sqlalchemy.MetaData()
connection = engine.connect()
users_file = sqlalchemy.Table('user_file', metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('username', sqlalchemy.Text),
sqlalchemy.Column('filename', sqlalchemy.Text))
def create_table():
print('created tables')
metadata.create_all(engine)
if __name__ == "__main__":
create_table()

View file

@ -0,0 +1,72 @@
import bobo, webob
import requests
import sqlalchemy
from sqlalchemy import delete
import os
db_url = os.getenv("SQLALCHEMY_DATABASE_URI") or 'sqlite:///users.db'
engine = sqlalchemy.create_engine(db_url)
metadata = sqlalchemy.MetaData()
connection = engine.connect()
users_file = sqlalchemy.Table('user_file', metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('username', sqlalchemy.Text),
sqlalchemy.Column('filename', sqlalchemy.Text))
def create_table():
metadata.create_all(engine)
@bobo.query('/check_access')
def check_access(filename="None", username="None"):
query = sqlalchemy.select([users_file]).where(users_file.columns.username == username and users_file.columns.filename == filename)
result_proxy = connection.execute(query)
result_set = result_proxy.fetchall()
if len(result_set) > 0:
return 'Allowed'
else:
return webob.Response(status=403)
@bobo.query('/:part1/:part2?', method=['GET'])
def redirect_get(part1="None", part2="None", filename=""):
if not filename:
return 'file param is not exist'
else:
result = requests.get(f"http://{part2}/{part1}?filename={filename}")
return webob.Response(result.content, content_type=result.headers.get('Content-Type'), status=result.status_code)
@bobo.query('/health_check', method=['GET'])
def health_check():
return webob.Response("OK", status=200)
@bobo.query('/delete/:username/:part2', method=['GET'])
def delete_file(username="None", part2="None"):
if not username:
return 'file param is not exist'
else:
query = sqlalchemy.select([users_file]).where(
users_file.columns.username == username)
result_proxy = connection.execute(query)
result_set = result_proxy.fetchall()
query2 = delete(users_file).where(users_file.columns.username == username)
connection.execute(query2)
for result_line in result_set:
result = requests.get(f"http://{part2}/delete?filename={result_line.filename}")
return webob.Response(result.content, content_type=result.headers.get('Content-Type'), status=result.status_code)
@bobo.query('/file_list/:part1/:part2?', method=['GET'])
def file_list_get(part1="None", part2="None"):
result = requests.get(f"http://{part2}/file_list/{part1}")
return webob.Response(result.content, content_type=result.headers.get('Content-Type'), status=result.status_code)
@bobo.query('/:part1/:part2?', method=['POST'])
def redirect_post(file, filename="None", username="None", part1="None", part2="None"):
insert_query = users_file.insert().values([{"username": username, "filename": filename}])
connection.execute(insert_query)
result = requests.post(f"http://{part2}/upload/{part1}", files={filename:file.file}, stream=True)
return webob.Response(result.content, content_type=result.headers.get('Content-Type'), status=result.status_code)

View file

@ -0,0 +1,5 @@
#!/bin/bash
set -e
python3 /home/volgactf/dist/init_db.py & bobo -f redirector.py