Skip to content

Commit

Permalink
Added admin login and post adding page
Browse files Browse the repository at this point in the history
  • Loading branch information
Nakama3942 committed Dec 14, 2023
1 parent c9696e7 commit 8d04587
Show file tree
Hide file tree
Showing 8 changed files with 212 additions and 36 deletions.
64 changes: 56 additions & 8 deletions blog/index.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import Flask, render_template, send_from_directory
from flask import Flask, render_template, send_from_directory, request, redirect, url_for, session
import markdown2
import yaml
import os
Expand All @@ -7,21 +7,69 @@
app = Flask(__name__, template_folder='template', static_folder='resources')
app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), 'files')

app.secret_key = 'your_secret_key' # Секретный ключ для подписи сессий
ADMIN_KEY = 'admin_key' # Ваш ключ для доступа к админским функциям

# Проверка, является ли пользователь администратором
def is_admin():
return session.get('admin', False)

# Маршрут для входа в аккаунт (с ключом)
@app.route('/login')
def login():
key = request.args.get('key', '')
if key == ADMIN_KEY:
session['admin'] = True
return redirect(url_for('diary'))

# Маршрут для выхода из аккаунта
@app.route('/logout')
def logout():
session.pop('admin', None)
return redirect(url_for('diary'))

@app.route('/new_post')
def add_post():
if not is_admin():
return 'Access Denied'
return render_template('new_post.html', is_admin=is_admin())

@app.route('/save_post', methods=['POST'])
def save_post_route():
# warning работает не корректно
title = request.form['title']
description = request.form['description']
content = request.form['content']

# Сохраняем файлы на сервер
saved_files = []
for uploaded_file in request.files.getlist('file'):
filename = os.path.join(app.config['UPLOAD_FOLDER'], uploaded_file.filename)
uploaded_file.save(filename)
file_metadata = {'name': uploaded_file.filename, 'type': get_file_type(uploaded_file.filename)}
saved_files.append(file_metadata)

# Формируем метаданные поста
post_metadata = f"name: {title}.md\ntitle: {title}\ndatetime: {datetime.now().strftime('%Y-%m-%d %I:%M %p')}\ndescription: {description}\nfiles: {files}\n\n#{title}\n\n{content}"

# Сохраняем метаданные в файл
post_filename = f"{title}.md"
with open(os.path.join(app.config['UPLOAD_FOLDER'], post_filename), 'w', encoding='utf-8') as post_file:
post_file.write(post_metadata)

return redirect(url_for('diary'))

@app.route('/')
def home():
post_files = get_posts('posts', 5)
post_contents = [load_post_metadata(file) for file in post_files]
return render_template('index.html', post_contents=post_contents)

# @app.route('/contacts')
# def contacts():
# return render_template('contacts.html')
return render_template('index.html', post_contents=post_contents, is_admin=is_admin())

@app.route('/diary')
def diary():
post_files = get_posts('posts', 0)
post_contents = [load_post_metadata(file) for file in post_files]
return render_template('diary.html', post_contents=post_contents)
return render_template('diary.html', post_contents=post_contents, is_admin=is_admin())

def get_posts(posts_directory, num_posts):
post_files = [f for f in os.listdir(posts_directory) if os.path.isfile(os.path.join(posts_directory, f))]
Expand Down Expand Up @@ -56,7 +104,7 @@ def load_post_metadata(post_content):
def post(post_id):
# Ваш код для загрузки и отображения полного содержания поста
post_content = load_post_content(post_id)
return render_template('post.html', post_content=post_content)
return render_template('post.html', post_content=post_content, is_admin=is_admin())

def load_post_content(file_name):
file_name = 'posts/' + str(file_name)
Expand Down
47 changes: 47 additions & 0 deletions blog/resources/scripts/scripts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
function auto_grow(element) {
element.style.height = "5px";
element.style.height = (element.scrollHeight)+"px";
}

window.addEventListener('unload', function () {
const form = document.querySelector('form');
form.reset(); // Очищаем все поля формы
});

// JavaScript для отображения выбранных файлов
function handleFileSelect(event) {
const files = event.target.files;
const fileList = document.getElementById('fileList');

// Обновляем список файлов
for (const file of files) {
const listItem = document.createElement('li');
listItem.classList.add('file-item');

const link = document.createElement('a');
link.href = URL.createObjectURL(file);
link.download = file.name;

const icon = document.createElement('img');
icon.src = 'resources/icons/' + getFileType(file.name) + '.png';
icon.alt = getFileType(file.name) + ' Icon';
icon.width = 128;
icon.height = 128;
icon.classList.add('file-icon');

const fileName = document.createTextNode(file.name);

link.appendChild(icon);
link.appendChild(fileName);
listItem.appendChild(link);

fileList.appendChild(listItem);
}
}

// Получаем тип файла по расширению
function getFileType(fileName) {
const extension = fileName.split('.').pop().toLowerCase();
// Ваш код определения типа файла по расширению, например, расширения 'pdf' -> 'PDF'
return extension.toUpperCase();
}
87 changes: 62 additions & 25 deletions blog/resources/style/style.css
Original file line number Diff line number Diff line change
@@ -1,53 +1,53 @@
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}

header {
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
}

nav {
background-color: #eee;
padding: 1em;
text-align: center;
background-color: #eee;
padding: 1em;
text-align: center;
}

nav a {
margin: 0 10px;
text-decoration: none;
color: #333;
margin: 0 10px;
text-decoration: none;
color: #333;
}

main {
max-width: 800px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
max-width: 800px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
}

footer {
padding: 1em;
background-color: #333;
color: #fff;
padding: 1em;
background-color: #333;
color: #fff;
}

.footer-container {
display: flex;
justify-content: space-between;
display: flex;
justify-content: space-between;
}
.column-left {
padding-left: 50px;
width: 48%; /* Задайте ширину колонок по вашему усмотрению */
width: 48%; /* Задайте ширину колонок по вашему усмотрению */
}
.column-right {
text-align: center;
width: 48%; /* Задайте ширину колонок по вашему усмотрению */
width: 48%; /* Задайте ширину колонок по вашему усмотрению */
}

.file-list {
Expand All @@ -64,3 +64,40 @@ footer {
width: 100%;
height: auto;
}

form {
max-width: 600px;
margin: 0 auto;
}
input[type="text"],
textarea,
input[type="file"],
input[type="submit"] {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
textarea {
resize: none; /* Запрет изменения размера */
overflow-y: hidden; /* Скрытие вертикального ползунка прокрутки */
min-height: 150px; /* Высота для textarea */
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
/* Дополнительные стили для элемента input[type="file"] */
input[type="file"] {
padding: 0;
}
/* Стили для подсказок (placeholders) */
::placeholder {
color: #999;
}
4 changes: 4 additions & 0 deletions blog/template/diary.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
{% include 'nav.html' %}

<main>
{% if is_admin %}
<a href="/new_post">Додати пост</a>
{% endif %}

{% for metadata in post_contents %}
<article>
<a href="{{ url_for('post', post_id=metadata[0]['name']) }}">
Expand Down
2 changes: 1 addition & 1 deletion blog/template/footer.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<footer>
<div class="footer-container">
<div class="column-left">
<h3>&copy; 2024 Калиновський Валентин</h3>
<h3>&copy; 2023-2024 Калиновський Валентин</h3>
<p>Студент-програміст</p>
<p>23 года, холост</p>
<p>
Expand Down
6 changes: 5 additions & 1 deletion blog/template/header.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
<header>
<h1>Калиновський Валентин<br>Мій Особистий Блог</h1>
<h1>Калиновський Валентин</h1>
<h2>Мій Особистий Блог</h2>
{% if is_admin %}
<p>Привіт, Вальок!</p>
{% endif %}
</header>
1 change: 0 additions & 1 deletion blog/template/nav.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@
<!-- <a href="#">Проекти</a>-->
<!-- <a href="#">Документації</a>-->
<a href="/diary">Щоденник</a>
<!-- <a href="/contacts">Контакти</a>-->
</nav>
37 changes: 37 additions & 0 deletions blog/template/new_post.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Новий пост</title>
<link rel="stylesheet" href="../resources/style/style.css">
</head>
<body>

{% include 'header.html' %}

{% include 'nav.html' %}

<script src="resources/scripts/scripts.js"></script>

<main>
<form action="{{ url_for('save_post_route') }}" method="post" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Заголовок" required>

<input type="text" name="description" placeholder="Опис" required>

<textarea name="content" placeholder="Текст" oninput="auto_grow(this)" required></textarea>

<input type="file" id="fileInput" name="files" onchange="handleFileSelect(event)" multiple>

<!-- Список выбранных файлов -->
<ul id="fileList" class="file-list"></ul>

<input type="submit" value="Зберегти пост">
</form>
</main>

{% include 'footer.html' %}

</body>
</html>

0 comments on commit 8d04587

Please sign in to comment.