Compare commits
5 Commits
98175ede85
...
a50a06d371
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a50a06d371 | ||
|
|
5baeee1f97 | ||
|
|
3f074e895d | ||
|
|
92c76d7155 | ||
|
|
923adfc7dc |
@ -1,3 +1,4 @@
|
|||||||
flask==3.0.2
|
flask==3.0.2
|
||||||
mysql-connector-python==9.4.0
|
mysql-connector-python==9.4.0
|
||||||
python_dotenv==1.1.1
|
python_dotenv==1.1.1
|
||||||
|
Flask-CORS==6.0.1
|
||||||
@ -1,93 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
# encoding: utf-8
|
|
||||||
|
|
||||||
'''
|
|
||||||
car.py is a source for all car endpoints.
|
|
||||||
'''
|
|
||||||
|
|
||||||
from flask import request, jsonify
|
|
||||||
|
|
||||||
def registerCarEndpoints(app, database):
|
|
||||||
@app.route('/car', methods=['GET'])
|
|
||||||
def get_car():
|
|
||||||
if not request.is_json:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
data = request.get_json()
|
|
||||||
|
|
||||||
if not data.get('name'):
|
|
||||||
return jsonify({'error': 'Request must contain name field'}), 400
|
|
||||||
|
|
||||||
query = f'SELECT * from car WHERE name = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if not output:
|
|
||||||
return jsonify({"message": "No car by that name exist"}), 404
|
|
||||||
car = output[0]
|
|
||||||
if len(car) != 3:
|
|
||||||
return jsonify({'error': 'Car data is corrupted'}), 500
|
|
||||||
|
|
||||||
response = {
|
|
||||||
"name": car[0],
|
|
||||||
"car": car[1],
|
|
||||||
"freeCarSpaces": car[2]
|
|
||||||
}
|
|
||||||
return jsonify(response), 200
|
|
||||||
|
|
||||||
@app.route('/car', methods=['POST'])
|
|
||||||
def add_car():
|
|
||||||
if not request.is_json:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
data = request.get_json()
|
|
||||||
if not data.get('name') or not data.get('car') or data.get('spaces') is None:
|
|
||||||
return jsonify({'error': 'JSON must contain car and name fields'}), 400
|
|
||||||
|
|
||||||
query = 'SELECT * from car WHERE name = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if output:
|
|
||||||
return jsonify({'error': 'A person has a car already'}), 409
|
|
||||||
|
|
||||||
query = 'INSERT into car (Name, Car, FreeCarSpaces) VALUES (%s, %s, %s)'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],data['car'],data['spaces']))
|
|
||||||
|
|
||||||
database.commit()
|
|
||||||
return jsonify({"message": "car added", "car": data}), 200
|
|
||||||
|
|
||||||
@app.route('/car', methods=['UPDATE'])
|
|
||||||
def update_car():
|
|
||||||
if not request.is_json:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
data = request.get_json()
|
|
||||||
if not data.get('name') or not data.get('car') or data.get('spaces') is None:
|
|
||||||
return jsonify({'error': 'JSON must contain car,name,space fields'}), 400
|
|
||||||
|
|
||||||
query = 'SELECT * from car WHERE name = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if not output:
|
|
||||||
return jsonify({'error': 'Such car does not exist. Add it first'}), 409
|
|
||||||
|
|
||||||
query = 'UPDATE car SET Name = %s, Car = %s, FreeCarSpaces = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],data['car'],data['spaces']))
|
|
||||||
|
|
||||||
database.commit()
|
|
||||||
return jsonify({"message": "car modified", "car": data}), 200
|
|
||||||
|
|
||||||
@app.route('/car', methods=['DELETE'])
|
|
||||||
def delete_car():
|
|
||||||
if not request.is_json:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
data = request.get_json()
|
|
||||||
if not data.get('name'):
|
|
||||||
return jsonify({'error': 'JSON must contain persons name whose car to delete'}), 400
|
|
||||||
|
|
||||||
query = 'SELECT * from car WHERE name = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if not output:
|
|
||||||
return jsonify({'error': 'Such person does not have a car'}), 409
|
|
||||||
|
|
||||||
query = 'DELETE FROM car WHERE Name = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
database.commit()
|
|
||||||
return jsonify({"message": "car deleted"}), 200
|
|
||||||
@ -1,11 +1,3 @@
|
|||||||
|
|
||||||
#!/usr/bin/env python
|
|
||||||
# encoding: utf-8
|
|
||||||
|
|
||||||
'''
|
|
||||||
db_client.py is the module for managing teh Dungeon's database services.
|
|
||||||
'''
|
|
||||||
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
import sys
|
import sys
|
||||||
import mysql.connector
|
import mysql.connector
|
||||||
@ -14,32 +6,20 @@ import os
|
|||||||
STARTUP_TABLE_CREATION_QUERIES = {
|
STARTUP_TABLE_CREATION_QUERIES = {
|
||||||
"users": """CREATE TABLE IF NOT EXISTS users (
|
"users": """CREATE TABLE IF NOT EXISTS users (
|
||||||
Name varchar(255),
|
Name varchar(255),
|
||||||
Attendance varchar(255),
|
Attendance bool,
|
||||||
HasCar bool
|
Password VARCHAR(2048)
|
||||||
);""",
|
);""",
|
||||||
"car": """CREATE TABLE IF NOT EXISTS car (
|
"sessions": """CREATE TABLE IF NOT EXISTS sessions (
|
||||||
Name varchar(255),
|
Token VARCHAR(2048),
|
||||||
Car varchar(255),
|
Name varchar(255)
|
||||||
FreeCarSpaces tinyint(1)
|
|
||||||
);""",
|
|
||||||
"suggestions": """CREATE TABLE IF NOT EXISTS suggestions (
|
|
||||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
|
||||||
Name VARCHAR(255),
|
|
||||||
Suggestion VARCHAR(2048)
|
|
||||||
);""",
|
|
||||||
"passengers": """CREATE TABLE IF NOT EXISTS passengers (
|
|
||||||
Name varchar(255),
|
|
||||||
Car varchar(255)
|
|
||||||
);""",
|
);""",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class Severity(Enum):
|
class Severity(Enum):
|
||||||
INFO = "INFO"
|
INFO = "INFO"
|
||||||
WARNING = "WARNING"
|
WARNING = "WARNING"
|
||||||
ERROR = "ERROR"
|
ERROR = "ERROR"
|
||||||
|
|
||||||
|
|
||||||
class DBClient:
|
class DBClient:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.db_server = os.environ.get('DB_SERVER')
|
self.db_server = os.environ.get('DB_SERVER')
|
||||||
@ -48,16 +28,18 @@ class DBClient:
|
|||||||
self.password = os.environ.get('ROOT_PWD')
|
self.password = os.environ.get('ROOT_PWD')
|
||||||
self.database = os.environ.get('DB_NAME')
|
self.database = os.environ.get('DB_NAME')
|
||||||
|
|
||||||
if not self.db_server:
|
self.validate_env_variables() # Check for required environment variables
|
||||||
self.error("Environment variable 'DB_SERVER' is not set.")
|
self.connection = self.open()
|
||||||
if not self.db_port:
|
self.cursor = self.connection.cursor()
|
||||||
self.error("Environment variable 'DB_PORT' is not set.")
|
|
||||||
if not self.password:
|
self.initialize_database()
|
||||||
self.error("Environment variable 'ROOT_PWD' is not set.")
|
|
||||||
if not self.database:
|
|
||||||
self.error("Environment variable 'DB_NAME' is not set.")
|
|
||||||
|
|
||||||
self.connection = mysql.connector.connect(
|
def validate_env_variables(self):
|
||||||
|
if not self.db_server or not self.db_port or not self.password or not self.database:
|
||||||
|
self.error("Missing one or more environment variables.")
|
||||||
|
|
||||||
|
def open(self):
|
||||||
|
return mysql.connector.connect(
|
||||||
host=self.db_server,
|
host=self.db_server,
|
||||||
port=self.db_port,
|
port=self.db_port,
|
||||||
user=self.user,
|
user=self.user,
|
||||||
@ -65,51 +47,39 @@ class DBClient:
|
|||||||
database=self.database
|
database=self.database
|
||||||
)
|
)
|
||||||
|
|
||||||
self.cursor = self.connection.cursor()
|
|
||||||
self.initialize_database()
|
|
||||||
self.commit()
|
|
||||||
|
|
||||||
def create_database(self, db_name):
|
|
||||||
query = f"CREATE DATABASE IF NOT EXISTS `{db_name}`;"
|
|
||||||
self.cursor.execute(query)
|
|
||||||
|
|
||||||
def switch_database(self, db_name):
|
|
||||||
self.connection.database = db_name
|
|
||||||
|
|
||||||
def initialize_database(self):
|
|
||||||
self.create_database(self.database)
|
|
||||||
self.switch_database(self.database)
|
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['users'])
|
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['car'])
|
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['suggestions'])
|
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['passengers'])
|
|
||||||
|
|
||||||
def query(self, query_str, quiet=False, params=None):
|
|
||||||
self.info(f'Executing query: {query_str}')
|
|
||||||
self.cursor.execute(query_str, params)
|
|
||||||
if quiet:
|
|
||||||
return []
|
|
||||||
return self.cursor.fetchall()
|
|
||||||
|
|
||||||
def commit(self):
|
|
||||||
self.info('Commiting actions to DB')
|
|
||||||
self.connection.commit()
|
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self.cursor.close()
|
self.cursor.close()
|
||||||
self.connection.close()
|
self.connection.close()
|
||||||
|
|
||||||
|
def initialize_database(self):
|
||||||
|
self.query(STARTUP_TABLE_CREATION_QUERIES['users'])
|
||||||
|
self.query(STARTUP_TABLE_CREATION_QUERIES['sessions'])
|
||||||
|
|
||||||
|
def query(self, query_str, params=None):
|
||||||
|
try:
|
||||||
|
self.info(f'Executing query: {query_str}')
|
||||||
|
self.cursor.execute(query_str, params)
|
||||||
|
|
||||||
|
if 'SELECT' in query_str:
|
||||||
|
return self.cursor.fetchall() # Return results for SELECT queries
|
||||||
|
else:
|
||||||
|
self.commit() # Commit if it's a non-SELECT query
|
||||||
|
except Exception as e:
|
||||||
|
self.error(f"Query failed: {str(e)}")
|
||||||
|
|
||||||
|
def commit(self):
|
||||||
|
self.info('Committing actions to DB')
|
||||||
|
self.connection.commit()
|
||||||
|
|
||||||
def info(self, message):
|
def info(self, message):
|
||||||
self.message(severity=Severity.INFO, message=message)
|
self.message(severity=Severity.INFO, message=message)
|
||||||
|
|
||||||
|
|
||||||
def warning(self, message):
|
def warning(self, message):
|
||||||
self.message(severity=Severity.WARNING, message=message)
|
self.message(severity=Severity.WARNING, message=message)
|
||||||
|
|
||||||
def error(self, message):
|
def error(self, message):
|
||||||
self.message(severity=Severity.ERROR, message=message)
|
self.message(severity=Severity.ERROR, message=message)
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
def message(self, severity, message):
|
def message(self, severity, message):
|
||||||
print(f'DBClient [{severity.value}]: {message}')
|
print(f'DBClient [{severity.value}]: {message}')
|
||||||
|
|
||||||
|
|||||||
@ -6,27 +6,21 @@ server.py is the main source file for the Dungeon's backend service.
|
|||||||
'''
|
'''
|
||||||
|
|
||||||
from flask import Flask, request, jsonify
|
from flask import Flask, request, jsonify
|
||||||
|
from flask_cors import CORS
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from db_client import DBClient
|
from db_client import DBClient
|
||||||
from car import registerCarEndpoints
|
|
||||||
from user import registerUserEndpoints
|
from user import registerUserEndpoints
|
||||||
from suggestions import registerSuggestionsEndpoints
|
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
app.config['JSON_AS_ASCII'] = False # Ensures non-ASCII characters are preserved
|
||||||
|
allowed_origins = [
|
||||||
|
"https://nyipyatki.davydovcloud.com",
|
||||||
|
"https://nyipyatki-dev.davydovcloud.com",
|
||||||
|
]
|
||||||
|
CORS(app, resources={r"*": {"origins": allowed_origins}}) # Only allow example.com
|
||||||
database = DBClient()
|
database = DBClient()
|
||||||
registerCarEndpoints(app=app, database=database)
|
|
||||||
registerUserEndpoints(app=app, database=database)
|
registerUserEndpoints(app=app, database=database)
|
||||||
registerSuggestionsEndpoints(app=app, database=database)
|
|
||||||
|
|
||||||
@app.route('/login', methods=['POST'])
|
|
||||||
def login():
|
|
||||||
if request.is_json:
|
|
||||||
return jsonify({"hello": "user"}), 200
|
|
||||||
else:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(debug=True)
|
app.run(debug=True)
|
||||||
@ -6,106 +6,78 @@ user.py is a source for all user endpoints.
|
|||||||
'''
|
'''
|
||||||
|
|
||||||
from flask import request, jsonify
|
from flask import request, jsonify
|
||||||
|
import os
|
||||||
|
|
||||||
def registerUserEndpoints(app, database):
|
def registerUserEndpoints(app, database):
|
||||||
@app.route('/users', methods=['GET'])
|
@app.route('/users/isSet', methods=['GET'])
|
||||||
def get_users():
|
def user_is_set():
|
||||||
query = f'SELECT * from users'
|
user_name = request.args.get('userName')
|
||||||
users = database.query(query_str=query)
|
try:
|
||||||
if not users:
|
query = "SELECT * FROM users WHERE Name=%s"
|
||||||
return jsonify({"message": "No users exist"}), 404
|
result = database.query(query, params=(user_name,))
|
||||||
response = {}
|
return jsonify(bool(result and result[0][2])), 200
|
||||||
for user in users:
|
except mysql.connector.Error as err:
|
||||||
if len(user) != 3:
|
# Log the error or handle it as necessary
|
||||||
return jsonify({'error': 'User data is corrupted'}), 500
|
app.logger.error(f"Error: {err}")
|
||||||
|
return jsonify({"error": "Database error occurred"}), 500
|
||||||
|
except Exception as e:
|
||||||
|
# Handle unexpected errors
|
||||||
|
app.logger.error(f"Unexpected error: {e}")
|
||||||
|
return jsonify({"error": "Internal server error"}), 500 # Check if password exists
|
||||||
|
|
||||||
response.update({
|
@app.route('/users/createPassword', methods=['POST'])
|
||||||
"name": user[0],
|
def create_password():
|
||||||
"attendance": user[1],
|
data = request.json
|
||||||
"has_car": bool(user[2])
|
user_name = data.get('userName')
|
||||||
})
|
password = data.get('password')
|
||||||
return jsonify(response), 200
|
|
||||||
|
|
||||||
@app.route('/user', methods=['GET'])
|
# Check if the user already exists
|
||||||
def get_user():
|
query = "SELECT * FROM users WHERE Name=%s"
|
||||||
if not request.is_json:
|
result = database.query(query, params=(user_name,))
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
if result:
|
||||||
|
return jsonify(success=False, message='Пользователь уже создан'), 400
|
||||||
|
|
||||||
data = request.get_json()
|
query = "INSERT INTO users (Name, Password) VALUES (%s, %s)"
|
||||||
|
|
||||||
|
try:
|
||||||
|
database.query(query, params=(user_name, password))
|
||||||
|
|
||||||
if not data.get('name'):
|
# Generate a session token
|
||||||
return jsonify({'error': 'Request must contain name field'}), 400
|
token = os.urandom(16).hex()
|
||||||
|
session_query = "INSERT INTO sessions (Token, Name) VALUES (%s, %s)"
|
||||||
query = f'SELECT * from users WHERE name = %s'
|
database.query(session_query, params=(token,user_name))
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if not output:
|
return jsonify(success=True, token=token), 201 # Return success with token
|
||||||
return jsonify({"message": "No user by that name exist"}), 404
|
except Exception as e:
|
||||||
user = output[0]
|
return jsonify(success=False, message='Ошибка при создании пароля: ' + str(e)), 500
|
||||||
if len(user) != 3:
|
|
||||||
return jsonify({'error': 'User data is corrupted'}), 500
|
|
||||||
|
|
||||||
response = {
|
|
||||||
"name": user[0],
|
|
||||||
"attendance": user[1],
|
|
||||||
"has_car": bool(user[2])
|
|
||||||
}
|
|
||||||
return jsonify(response), 200
|
|
||||||
|
|
||||||
@app.route('/user', methods=['POST'])
|
|
||||||
def add_user():
|
|
||||||
if not request.is_json:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
data = request.get_json()
|
@app.route('/login', methods=['POST'])
|
||||||
if not data.get('name') or not data.get('attendance') or data.get('has_car') is None:
|
def login():
|
||||||
return jsonify({'error': 'JSON must contain user fields'}), 400
|
data = request.json
|
||||||
|
user_name = data.get('userName')
|
||||||
query = 'SELECT * from users WHERE name = %s'
|
password = data.get('password')
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if output:
|
|
||||||
return jsonify({'error': 'A person already exists'}), 409
|
|
||||||
|
|
||||||
query = 'INSERT into users (Name, Attendance, HasCar) VALUES (%s, %s, %s)'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],data['attendance'],data['has_car']))
|
|
||||||
|
|
||||||
database.commit()
|
query = "SELECT * FROM users WHERE Name=%s AND Password=%s"
|
||||||
return jsonify({"message": "user added", "user": data}), 200
|
result = database.query(query, params=(user_name, password))
|
||||||
|
|
||||||
@app.route('/user', methods=['UPDATE'])
|
|
||||||
def update_user():
|
|
||||||
if not request.is_json:
|
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
|
||||||
|
|
||||||
data = request.get_json()
|
if result:
|
||||||
if not data.get('name') or not data.get('attendance') or data.get('has_car') is None:
|
token = os.urandom(16).hex() # Example token generation
|
||||||
return jsonify({'error': 'JSON must contain user fields'}), 400
|
session_query = "INSERT INTO sessions (Token, Name) VALUES (%s, %s)"
|
||||||
|
database.query(session_query, params=(token, user_name))
|
||||||
query = 'SELECT * from users WHERE name = %s'
|
return jsonify(success=True, token=token), 200
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
if not output:
|
|
||||||
return jsonify({'error': 'Such user does not exist. Add it first'}), 409
|
|
||||||
|
|
||||||
query = 'UPDATE user SET Name = %s, Attendance = %s, HasCar = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],data['attendance'],data['has_car']))
|
|
||||||
|
|
||||||
database.commit()
|
return jsonify(success=False), 401
|
||||||
return jsonify({"message": "user modified", "user": data}), 200
|
|
||||||
|
|
||||||
@app.route('/user', methods=['DELETE'])
|
@app.route('/login/validateToken', methods=['POST'])
|
||||||
def delete_user():
|
def validate_token():
|
||||||
if not request.is_json:
|
data = request.json
|
||||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
token = data.get('token')
|
||||||
|
user_name = data.get('userName')
|
||||||
data = request.get_json()
|
query = "SELECT * FROM sessions WHERE Token=%s AND Name=%s"
|
||||||
if not data.get('name'):
|
try:
|
||||||
return jsonify({'error': 'JSON must contain persons name to delete'}), 400
|
result = database.query(query, params=(token, user_name))
|
||||||
|
return jsonify(tokenValid=bool(result)), 200
|
||||||
query = 'SELECT * from users WHERE name = %s'
|
except Exception as e:
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
return jsonify(success=False, message=str(e)), 500
|
||||||
if not output:
|
|
||||||
return jsonify({'error': 'Such person does not exist'}), 409
|
|
||||||
|
|
||||||
query = 'DELETE FROM users WHERE Name = %s'
|
|
||||||
output = database.query(query_str=query, params=(data['name'],))
|
|
||||||
database.commit()
|
|
||||||
return jsonify({"message": "user deleted"}), 200
|
|
||||||
|
|||||||
@ -5,7 +5,7 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
ports:
|
ports:
|
||||||
- "2027:5000"
|
- "2027:5000"
|
||||||
container_name: "${CONTAINER_NAME:-nyi-backend}"
|
container_name: "${BACKEND_CT_NAME:-nyi-backend}"
|
||||||
depends_on:
|
depends_on:
|
||||||
- db # Ensure backend waits for db to start
|
- db # Ensure backend waits for db to start
|
||||||
db:
|
db:
|
||||||
@ -18,6 +18,14 @@ services:
|
|||||||
- MYSQL_DATABASE=${DB_NAME}
|
- MYSQL_DATABASE=${DB_NAME}
|
||||||
volumes:
|
volumes:
|
||||||
- nyi_db_volume:/var/lib/mysql
|
- nyi_db_volume:/var/lib/mysql
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
ports:
|
||||||
|
- "2028:80"
|
||||||
|
container_name: "${FRONTEND_CT_NAME:-nyi-frontend}"
|
||||||
|
depends_on:
|
||||||
|
- backend # Ensure fronetnd waits for backend to start
|
||||||
volumes:
|
volumes:
|
||||||
nyi_db_volume:
|
nyi_db_volume:
|
||||||
29
frontend/Dockerfile
Normal file
29
frontend/Dockerfile
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
# Use the official Node.js image.
|
||||||
|
FROM node:18 AS build
|
||||||
|
|
||||||
|
# Set the working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package.json and package-lock.json (or yarn.lock) to the working directory
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
# Copy the rest of the application
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Start a new stage to serve the application
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
# Copy the build output to Nginx's public folder
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
# Expose port 80
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
# Start Nginx when the container runs
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
15
frontend/package-lock.json
generated
15
frontend/package-lock.json
generated
@ -8,6 +8,7 @@
|
|||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"crypto-js": "^4.2.0",
|
||||||
"js-cookie": "^3.0.5",
|
"js-cookie": "^3.0.5",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-cookie": "^8.0.1",
|
"react-cookie": "^8.0.1",
|
||||||
@ -15,6 +16,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.33.0",
|
"@eslint/js": "^9.33.0",
|
||||||
|
"@types/crypto-js": "^4.2.2",
|
||||||
"@types/react": "^19.1.10",
|
"@types/react": "^19.1.10",
|
||||||
"@types/react-dom": "^19.1.7",
|
"@types/react-dom": "^19.1.7",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
@ -1408,6 +1410,13 @@
|
|||||||
"@babel/types": "^7.28.2"
|
"@babel/types": "^7.28.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/crypto-js": {
|
||||||
|
"version": "4.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz",
|
||||||
|
"integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/estree": {
|
"node_modules/@types/estree": {
|
||||||
"version": "1.0.8",
|
"version": "1.0.8",
|
||||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
|
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
|
||||||
@ -1978,6 +1987,12 @@
|
|||||||
"node": ">= 8"
|
"node": ">= 8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/crypto-js": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/csstype": {
|
"node_modules/csstype": {
|
||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
||||||
|
|||||||
@ -10,6 +10,7 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"crypto-js": "^4.2.0",
|
||||||
"js-cookie": "^3.0.5",
|
"js-cookie": "^3.0.5",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-cookie": "^8.0.1",
|
"react-cookie": "^8.0.1",
|
||||||
@ -17,6 +18,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.33.0",
|
"@eslint/js": "^9.33.0",
|
||||||
|
"@types/crypto-js": "^4.2.2",
|
||||||
"@types/react": "^19.1.10",
|
"@types/react": "^19.1.10",
|
||||||
"@types/react-dom": "^19.1.7",
|
"@types/react-dom": "^19.1.7",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
|||||||
@ -1,15 +1,9 @@
|
|||||||
#root {
|
#root {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 1280px;
|
max-width: 1280px;
|
||||||
min-width: 375px;
|
|
||||||
margin: 0 auto;
|
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mainText {
|
|
||||||
color: #5f5e5e;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* General table styles */
|
/* General table styles */
|
||||||
table {
|
table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@ -23,13 +17,11 @@ table {
|
|||||||
th {
|
th {
|
||||||
background-color: #4CAF50; /* Green */
|
background-color: #4CAF50; /* Green */
|
||||||
color: white;
|
color: white;
|
||||||
padding: 10px;
|
|
||||||
text-align: left;
|
text-align: left;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Table cell styles */
|
/* Table cell styles */
|
||||||
td {
|
td {
|
||||||
padding: 10px;
|
|
||||||
border: 1px solid #ddd;
|
border: 1px solid #ddd;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,25 +30,6 @@ tr:nth-child(even) {
|
|||||||
background-color: #f2f2f2;
|
background-color: #f2f2f2;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Responsive table styles */
|
|
||||||
@media (max-width: 600px) {
|
|
||||||
table {
|
|
||||||
display: block;
|
|
||||||
overflow-x: auto;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
th, td {
|
|
||||||
padding: 8px;
|
|
||||||
font-size: 0.9em;
|
|
||||||
}
|
|
||||||
|
|
||||||
th {
|
|
||||||
font-weight: bold;
|
|
||||||
background-color: #3C8A3C;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Hover effect for rows */
|
/* Hover effect for rows */
|
||||||
tr:hover {
|
tr:hover {
|
||||||
background-color: #f1f1f1;
|
background-color: #f1f1f1;
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
import './App.css'
|
import './App.css'
|
||||||
import Greeting from './components/Greeting'
|
import Greeting from './components/Greeting'
|
||||||
import Hosting from './components/Hosting'
|
import Hosting from './components/Hosting'
|
||||||
import NameSelector from './components/NameSelector'
|
import InitialSetup from './components/InitialSetup'
|
||||||
import Program from './components/Program'
|
import Program from './components/Program'
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<NameSelector/>
|
<InitialSetup/>
|
||||||
<Greeting/>
|
<Greeting/>
|
||||||
<br/>
|
<br/>
|
||||||
<Hosting/>
|
<Hosting/>
|
||||||
|
|||||||
0
frontend/src/components/Attendance.tsx
Normal file
0
frontend/src/components/Attendance.tsx
Normal file
@ -65,7 +65,7 @@ function Hosting() {
|
|||||||
<tr key={id}>
|
<tr key={id}>
|
||||||
<td>{item.name}</td>
|
<td>{item.name}</td>
|
||||||
<td>{item.capacity}</td>
|
<td>{item.capacity}</td>
|
||||||
<td>{<ReserveButton update={update} reservedBy={item.reservedBy} id={id} />}</td>
|
<td>{<ReserveButton update={update} reservedBy={item.reservedBy} id={Number(id)} />}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
147
frontend/src/components/InitialSetup.tsx
Normal file
147
frontend/src/components/InitialSetup.tsx
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useCookies } from 'react-cookie';
|
||||||
|
import { GUESTS } from '../constants/constants';
|
||||||
|
import useFetchUser from '../utils/fetchUser'; // Import your custom hook
|
||||||
|
import { useNotification } from '../NotificationContext';
|
||||||
|
|
||||||
|
const InitialSetup = () => {
|
||||||
|
const [cookie, setCookie] = useCookies();
|
||||||
|
const [selectedName, setSelectedName] = useState<string | undefined>(cookie.userName);
|
||||||
|
const [token] = useState<string | undefined>(cookie.apiToken)
|
||||||
|
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [isPasswordSet, setIsPasswordSet] = useState(false); // To track if password is set
|
||||||
|
|
||||||
|
const { userSet, passwordCreate, signUser, validToken } = useFetchUser(); // Destructure functions from the hook
|
||||||
|
const notify = useNotification();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const validateToken = async () => {
|
||||||
|
const isTokenValid = await validToken(token, selectedName);
|
||||||
|
setIsSubmitted(isTokenValid);
|
||||||
|
};
|
||||||
|
|
||||||
|
validateToken();
|
||||||
|
if (selectedName) {
|
||||||
|
checkUserPassword(selectedName)
|
||||||
|
}
|
||||||
|
}, [selectedName]);
|
||||||
|
|
||||||
|
const handleSelect = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
|
const name = event.target.value;
|
||||||
|
setCookie('userName', name, { path: '/' });
|
||||||
|
setSelectedName(name);
|
||||||
|
checkUserPassword(name);
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkUserPassword = async (name: string) => {
|
||||||
|
const passwordStatus = await userSet(name);
|
||||||
|
setIsPasswordSet(passwordStatus);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePasswordCreate = async () => {
|
||||||
|
const message= await passwordCreate(selectedName!, password);
|
||||||
|
if (message !== '') {
|
||||||
|
notify(message, 'error')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setIsSubmitted(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSignIn = async () => {
|
||||||
|
const signedIn = await signUser(selectedName!, password); // Implement your sign-in logic here
|
||||||
|
if (!signedIn) {
|
||||||
|
notify('Не удалось войти. Может пароль не тот?', 'error')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setIsSubmitted(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
if (isSubmitted) {
|
||||||
|
console.log('Selected', selectedName);
|
||||||
|
return null; // or you can redirect to another component or page
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={styles.container}>
|
||||||
|
<h2 style={styles.title}>Выбери себя</h2>
|
||||||
|
<select style={styles.dropdown} onChange={handleSelect} value={selectedName || ''}>
|
||||||
|
<option value="" disabled>{(cookie.userName == undefined) ? 'Пятка' : cookie.userName}</option>
|
||||||
|
{GUESTS.map((name) => (
|
||||||
|
<option key={name} value={name}>
|
||||||
|
{name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{(selectedName !== undefined) && (
|
||||||
|
<>
|
||||||
|
<h3>{isPasswordSet ? 'Войдите' : 'Создайте свой пароль'}</h3>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="Ввести пароль"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
style={styles.input}
|
||||||
|
/>
|
||||||
|
{isPasswordSet ? (
|
||||||
|
<>
|
||||||
|
<button onClick={handleSignIn}>
|
||||||
|
Войти
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (<>
|
||||||
|
<button
|
||||||
|
onClick={handlePasswordCreate}
|
||||||
|
disabled={!password} // Disables the button if no password is entered
|
||||||
|
>
|
||||||
|
Создать пароль
|
||||||
|
</button>
|
||||||
|
</>)}
|
||||||
|
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const styles = {
|
||||||
|
container: {
|
||||||
|
position: 'fixed' as 'fixed',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: '100vw',
|
||||||
|
height: '100vh',
|
||||||
|
backgroundColor: 'rgba(0, 0, 0, 1)',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column' as 'column',
|
||||||
|
justifyContent: 'center',
|
||||||
|
alignItems: 'center',
|
||||||
|
color: '#fff',
|
||||||
|
zIndex: 1000,
|
||||||
|
overflow: 'hidden',
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
marginBottom: '20px',
|
||||||
|
},
|
||||||
|
dropdown: {
|
||||||
|
padding: '10px',
|
||||||
|
fontSize: '16px',
|
||||||
|
cursor: 'pointer',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '5px',
|
||||||
|
outline: 'none',
|
||||||
|
marginBottom: '10px',
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
padding: '10px',
|
||||||
|
fontSize: '16px',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '5px',
|
||||||
|
outline: 'none',
|
||||||
|
marginBottom: '10px',
|
||||||
|
width: '200px', // Set a width
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default InitialSetup;
|
||||||
@ -1,64 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { useCookies } from 'react-cookie';
|
|
||||||
import { GUESTS } from '../constants/constants';
|
|
||||||
|
|
||||||
const NameSelector = () => {
|
|
||||||
const [cookie, setCookie] = useCookies(['userName']);
|
|
||||||
const [selectedName, setSelectedName] = useState<string | undefined>(cookie.userName);
|
|
||||||
|
|
||||||
const handleSelect = (name: string) => {
|
|
||||||
if (name)
|
|
||||||
setSelectedName(name);
|
|
||||||
setCookie('userName', name, { path: '/' });
|
|
||||||
};
|
|
||||||
|
|
||||||
if (selectedName !== undefined) {
|
|
||||||
console.log('Selected', selectedName)
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div style={styles.container}>
|
|
||||||
<h2 style={styles.title}>Выбери себя</h2>
|
|
||||||
<div style={styles.namesContainer}>
|
|
||||||
{GUESTS.map((name) => (
|
|
||||||
<button key={name} style={styles.button} onClick={() => handleSelect(name)}>
|
|
||||||
{name}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const styles = {
|
|
||||||
container: {
|
|
||||||
position: 'fixed' as 'fixed',
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
width: '100vw',
|
|
||||||
height: '100vh',
|
|
||||||
backgroundColor: 'rgba(0, 0, 0, 1)',
|
|
||||||
display: 'flex',
|
|
||||||
flexDirection: 'column' as 'column',
|
|
||||||
justifyContent: 'center',
|
|
||||||
alignItems: 'center',
|
|
||||||
color: '#fff',
|
|
||||||
zIndex: 1000,
|
|
||||||
},
|
|
||||||
title: {
|
|
||||||
marginBottom: '20px',
|
|
||||||
},
|
|
||||||
namesContainer: {
|
|
||||||
display: 'flex',
|
|
||||||
flexDirection: 'column' as 'column',
|
|
||||||
},
|
|
||||||
button: {
|
|
||||||
margin: '10px',
|
|
||||||
padding: '10px 20px',
|
|
||||||
fontSize: '16px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export default NameSelector;
|
|
||||||
@ -1,5 +1,5 @@
|
|||||||
|
|
||||||
export const API_URL = 'https://example.backend.com/hosting';
|
export const API_URL = 'https://nyipyatki-backend.davydovcloud.com';
|
||||||
export const GUESTS = [
|
export const GUESTS = [
|
||||||
"Медведь",
|
"Медведь",
|
||||||
"Ксения",
|
"Ксения",
|
||||||
|
|||||||
@ -1,18 +1,3 @@
|
|||||||
:root {
|
|
||||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
|
||||||
line-height: 1.5;
|
|
||||||
font-weight: 400;
|
|
||||||
|
|
||||||
color-scheme: light dark;
|
|
||||||
color: rgba(255, 255, 255, 0.87);
|
|
||||||
background-color: #242424;
|
|
||||||
|
|
||||||
font-synthesis: none;
|
|
||||||
text-rendering: optimizeLegibility;
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
-moz-osx-font-smoothing: grayscale;
|
|
||||||
}
|
|
||||||
|
|
||||||
a {
|
a {
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: #646cff;
|
color: #646cff;
|
||||||
@ -28,41 +13,5 @@ body {
|
|||||||
place-items: center;
|
place-items: center;
|
||||||
min-width: 320px;
|
min-width: 320px;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
}
|
overflow-x: hidden;
|
||||||
|
|
||||||
h1 {
|
|
||||||
font-size: 3.2em;
|
|
||||||
line-height: 1.1;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
border-radius: 8px;
|
|
||||||
border: 1px solid transparent;
|
|
||||||
padding: 0.6em 1.2em;
|
|
||||||
font-size: 1em;
|
|
||||||
font-weight: 500;
|
|
||||||
font-family: inherit;
|
|
||||||
background-color: #1a1a1a;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: border-color 0.25s;
|
|
||||||
}
|
|
||||||
button:hover {
|
|
||||||
border-color: #646cff;
|
|
||||||
}
|
|
||||||
button:focus,
|
|
||||||
button:focus-visible {
|
|
||||||
outline: 4px auto -webkit-focus-ring-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: light) {
|
|
||||||
:root {
|
|
||||||
color: #213547;
|
|
||||||
background-color: #ffffff;
|
|
||||||
}
|
|
||||||
a:hover {
|
|
||||||
color: #747bff;
|
|
||||||
}
|
|
||||||
button {
|
|
||||||
background-color: #f9f9f9;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import type { Hosting } from '../types';
|
import type { Hosting } from '../types';
|
||||||
|
import { API_URL } from '../constants/constants';
|
||||||
|
|
||||||
const mockData: Hosting = {
|
const mockData: Hosting = {
|
||||||
1: {
|
1: {
|
||||||
@ -33,7 +34,7 @@ const useFetchHosting = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/hosting');
|
const response = await fetch(`${API_URL}/hosting`);
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
throw new Error('Network response was not ok');
|
throw new Error('Network response was not ok');
|
||||||
}
|
}
|
||||||
@ -48,7 +49,7 @@ const useFetchHosting = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/hosting/${id}`, {
|
const response = await fetch(`${API_URL}/hosting/${id}`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
|||||||
110
frontend/src/utils/fetchUser.tsx
Normal file
110
frontend/src/utils/fetchUser.tsx
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
import { useCookies } from 'react-cookie';
|
||||||
|
import { API_URL } from '../constants/constants';
|
||||||
|
import { hashPassword } from './hashPassword';
|
||||||
|
|
||||||
|
const useFetchUser = () => {
|
||||||
|
const [, setCookie] = useCookies(['apiToken']);
|
||||||
|
|
||||||
|
const userSet = async (userName: string): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/users/isSet?userName=${encodeURIComponent(userName)}`);
|
||||||
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
const data = await response.json();
|
||||||
|
return data; // Assuming the server returns true/false
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking user password status:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const passwordCreate = async (userName: string, password: string): Promise<string> => {
|
||||||
|
// Simple validation: password should not be empty and should have a minimum length
|
||||||
|
if (!password || password.length < 6) {
|
||||||
|
console.error('Password should be at least 6 characters long.');
|
||||||
|
return 'Пароль должен иметь, как минимум 6 символов';
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const hashedPassword = hashPassword(password)
|
||||||
|
const response = await fetch(`${API_URL}/users/createPassword`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userName,
|
||||||
|
password: hashedPassword,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
setCookie('apiToken', data.token, { path: '/' });
|
||||||
|
console.log(`Password created for ${userName}`);
|
||||||
|
return ''; // Password creation success
|
||||||
|
}
|
||||||
|
return 'Не удалось создать пароль'; // Password creation failure
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating password:', error);
|
||||||
|
return 'Пароль не создан:' + error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const signUser = async (userName: string, password: string): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
const hashedPassword = hashPassword(password); // Implement this function to hash the password
|
||||||
|
const response = await fetch(`${API_URL}/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userName,
|
||||||
|
password: hashedPassword,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.token) {
|
||||||
|
setCookie('apiToken', data.token, { path: '/' });
|
||||||
|
console.log(`User ${userName} signed in.`);
|
||||||
|
return true; // Sign-in success
|
||||||
|
}
|
||||||
|
return false; // Sign-in failed
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error logging in:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const validToken = async (token: string | undefined, userName: string | undefined): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/login/validateToken`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
token,
|
||||||
|
userName
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
return data.tokenValid
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error validating token:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { userSet, passwordCreate, signUser, validToken };
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useFetchUser;
|
||||||
10
frontend/src/utils/hashPassword.tsx
Normal file
10
frontend/src/utils/hashPassword.tsx
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
// src/utils/passwordHasher.ts
|
||||||
|
import SHA256 from 'crypto-js/sha256';
|
||||||
|
/**
|
||||||
|
* Hashes a password using SHA-256.
|
||||||
|
* @param {string} password - The plain text password.
|
||||||
|
* @returns {string} - The hashed password in hex format.
|
||||||
|
*/
|
||||||
|
export const hashPassword = (password: string): string => {
|
||||||
|
return SHA256(password).toString(); // Returns the hash in hex format
|
||||||
|
};
|
||||||
@ -4,4 +4,7 @@ import react from '@vitejs/plugin-react'
|
|||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
allowedHosts: ['nyipyatki-dev.davydovcloud.com'],
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user