first commit
This commit is contained in:
0
server/__init__.py
Normal file
0
server/__init__.py
Normal file
0
server/backend/__init__.py
Normal file
0
server/backend/__init__.py
Normal file
66
server/backend/endpoints.py
Normal file
66
server/backend/endpoints.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from . import pydentic
|
||||
from server.database import db
|
||||
import asyncio
|
||||
|
||||
api = FastAPI()
|
||||
|
||||
api.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # "*" — разрешить всем; можно указать список конкретных доменов
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"], # GET, POST, PUT, DELETE и т.д.
|
||||
allow_headers=["*"], # Разрешить любые заголовки
|
||||
)
|
||||
|
||||
@api.get("/", response_model=pydentic.IdofPersons)
|
||||
async def get_all_rows():
|
||||
for row in await db.get_all_rows():
|
||||
if row:
|
||||
return row
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="The user isn't found")
|
||||
@api.get("/get_user/{id}", response_model=pydentic.IdofPersons)
|
||||
async def get_user(id:int):
|
||||
user = await db.GetUser(id)
|
||||
if user:
|
||||
return user
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="The user isn't found")
|
||||
@api.post("/user_create", response_model=pydentic.IdofPersons)
|
||||
async def create_user(row:pydentic.CreateUser):
|
||||
new_user_id = max(item.id for item in await db.get_all_rows())
|
||||
new_row = pydentic.IdofPersons(id = new_user_id, email=row.email, description=row.description, activated = row.activated, password = row.password)
|
||||
await db.CreateUser(new_row)
|
||||
return new_row
|
||||
@api.delete("/user_delete/{id}", response_model=pydentic.IdofPersons)
|
||||
async def delete_user(id: int):
|
||||
user = await db.GetUser(id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="The user isn't found")
|
||||
await db.DeleteUser(id)
|
||||
return user
|
||||
@api.put("/user_update/{id}", response_model=pydentic.IdofPersons)
|
||||
async def update_user(id: int, updated_row: pydentic.UserUpdate):
|
||||
user = await db.GetUser(id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="The user isn't found")
|
||||
changed = False
|
||||
if updated_row.email is not None and updated_row.email != user.email:
|
||||
user.email = updated_row.email
|
||||
changed = True
|
||||
if updated_row.description is not None and updated_row.description != user.description:
|
||||
user.description = updated_row.description
|
||||
changed = True
|
||||
if updated_row.activated is not None and updated_row.activated != user.activated:
|
||||
user.activated = updated_row.activated
|
||||
changed = True
|
||||
if updated_row.password is not None and updated_row.password != user.password:
|
||||
user.password = updated_row.password
|
||||
changed = True
|
||||
if changed:
|
||||
await db.UpdateUser(user)
|
||||
else:
|
||||
pass
|
||||
return user
|
||||
37
server/backend/pydentic.py
Normal file
37
server/backend/pydentic.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from pydantic import BaseModel, Field, EmailStr, constr,validator
|
||||
from typing import List, Optional
|
||||
from enum import IntEnum
|
||||
#Валидация пароля
|
||||
import re
|
||||
def check_password_complexity(cls, password):
|
||||
if password is None:
|
||||
return password
|
||||
if not re.search(r'[A-Za-z]', password):
|
||||
raise ValueError('Password must contain at least one letter')
|
||||
if not re.search(r'\d', password):
|
||||
raise ValueError('Password must contain at least one digit')
|
||||
if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
|
||||
raise ValueError('Password must contain at least one special symbol')
|
||||
return password
|
||||
|
||||
#Валидация полей с пользователями
|
||||
class UsersInfo(BaseModel):
|
||||
email:EmailStr = Field(..., min_length=6, max_length=254, description="email of the user")
|
||||
description: str = Field(..., description="description of the user")
|
||||
activated:bool = Field(..., description="Has the user activated their account")
|
||||
password:constr(min_length=8) = Field(..., description="Password with min 8 chars, letters and digits")
|
||||
@validator('password')
|
||||
def password_validator(cls, password):
|
||||
return check_password_complexity(cls, password)
|
||||
class IdofPersons(UsersInfo):
|
||||
id:int = Field(..., description="Unique identifier of the user")
|
||||
class CreateUser(UsersInfo):
|
||||
pass
|
||||
class UserUpdate(BaseModel):
|
||||
email:Optional[EmailStr] = Field(None, min_length=6, max_length=254, description="users' email")
|
||||
description:Optional[str] = Field(None, description="description of the user")
|
||||
activated:Optional[bool] = Field(None, description="Has the user activated their account")
|
||||
password:Optional[constr(min_length=8)] = Field(None, description="Password with min 8 chars, letters and digits")
|
||||
@validator('password')
|
||||
def password_validator(cls, password):
|
||||
return check_password_complexity(cls, password)
|
||||
BIN
server/database/DB/example.db
Normal file
BIN
server/database/DB/example.db
Normal file
Binary file not shown.
0
server/database/__init__.py
Normal file
0
server/database/__init__.py
Normal file
82
server/database/db.py
Normal file
82
server/database/db.py
Normal file
@@ -0,0 +1,82 @@
|
||||
|
||||
import asyncio
|
||||
#from sqlalchemy import create_engine #Не async
|
||||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy import Column, Integer, String, Boolean, select
|
||||
|
||||
from pathlib import Path
|
||||
db_folder = Path(__file__).parent / "DB"
|
||||
db_folder.mkdir(parents=True, exist_ok=True)
|
||||
db_path = db_folder / "example.db"
|
||||
async_engine = create_async_engine(f"sqlite+aiosqlite:///{db_path}", echo=True)
|
||||
#sqlite+aiosqlite — тип БД + async-драйвер ///example.db — путь к файлу (три слэша, если путь относительный; четыре, если абсолютный
|
||||
|
||||
from passlib.context import CryptContext
|
||||
#Hash password
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
AsyncSessionLocal = sessionmaker(async_engine,class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String(254), unique=True, nullable=False)
|
||||
description = Column(String, nullable=False)
|
||||
activated = Column(Boolean, default=False)
|
||||
password = Column(String, nullable=False)
|
||||
|
||||
async def init_db():
|
||||
async with async_engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
async def CreateUser(user_info):
|
||||
async with AsyncSessionLocal() as session:
|
||||
new_user = User(email=user_info.email, description=user_info.description, activated=user_info.activated, password=hash_password(user_info.password))
|
||||
session.add(new_user)
|
||||
await session.commit()
|
||||
await session.refresh(new_user)
|
||||
print(new_user.id)
|
||||
async def GetUser(id):
|
||||
async with AsyncSessionLocal() as session:
|
||||
result = await session.execute(select(User).where(User.id==id))
|
||||
user = result.scalar_one_or_none()
|
||||
return user
|
||||
async def get_all_rows():
|
||||
async with AsyncSessionLocal() as session:
|
||||
result = await session.execute(select(User))
|
||||
users = result.scalars().all()
|
||||
return users
|
||||
async def UpdateUser(user_info):
|
||||
async with AsyncSessionLocal() as session:
|
||||
result = await session.execute(select(User).where(User.id==user_info.id))
|
||||
user = result.scalar_one_or_none()
|
||||
if user:
|
||||
user.email = user_info.email
|
||||
user.description = user_info.description
|
||||
user.activated = user_info.activated
|
||||
user.password = hash_password(user_info.password)
|
||||
await session.commit()
|
||||
async def DeleteUser(id):
|
||||
async with AsyncSessionLocal() as session:
|
||||
result = await session.execute(select(User).where(User.id==id))
|
||||
user = result.scalar_one_or_none()
|
||||
if user:
|
||||
await session.delete(user)
|
||||
await session.commit()
|
||||
async def main():
|
||||
await init_db()
|
||||
await CreateUser()
|
||||
await get_all_rows()
|
||||
# await UpdateUser(1)
|
||||
# await GetUser(1)
|
||||
# await DeleteUser(1)
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
BIN
server/front/login/background-image.jpeg
Normal file
BIN
server/front/login/background-image.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 158 KiB |
27
server/front/login/index.html
Normal file
27
server/front/login/index.html
Normal file
@@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login</title>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="glass-container">
|
||||
<div class="login-box">
|
||||
<h2>Login</h2>
|
||||
<form action="#" method="POST">
|
||||
<input type="text" id="username" name="username" required placeholder="Username">
|
||||
<input type="password" id="password" name="password" required placeholder="Password">
|
||||
<div class="options">
|
||||
<input type="checkbox" id="remember" name="remember">
|
||||
<label for="remember"> Remember me</label>
|
||||
<a href="#">Forgot Password?</a>
|
||||
</div>
|
||||
<button type="submit">Login</button>
|
||||
<p>Don't have an account? <a href="./../register/index.html" id="register">Register</a></p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
121
server/front/login/style.css
Normal file
121
server/front/login/style.css
Normal file
@@ -0,0 +1,121 @@
|
||||
* {
|
||||
margin: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Poppins', sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
background-image: url('background-image.jpeg');
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.glass-container {
|
||||
width: 300px;
|
||||
height: 350px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
border-radius: 10px;
|
||||
border: 1px solid #fff;
|
||||
}
|
||||
|
||||
.glass-container::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 10px;
|
||||
backdrop-filter: blur(5px);
|
||||
-webkit-backdrop-filter: blur(5px);
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.login-box {
|
||||
max-width: 250px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #fff;
|
||||
margin-top: 30px;
|
||||
margin-bottom: -20px;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
input {
|
||||
padding: 10px;
|
||||
margin-top: 25px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: transparent;
|
||||
border: 1px solid #fff;
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.options {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 15px;
|
||||
font-size: 12px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.options input {
|
||||
margin-right: 5px;
|
||||
margin-top: 0px;
|
||||
}
|
||||
|
||||
.options a {
|
||||
text-decoration: none;
|
||||
color: white;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
button {
|
||||
background: #fff;
|
||||
color: black;
|
||||
padding: 10px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: transparent;
|
||||
color: white;
|
||||
outline: 1px solid #fff;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 12px;
|
||||
color: #fff;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
#register {
|
||||
text-decoration: none;
|
||||
color: #fff;
|
||||
font-weight: bold;
|
||||
}
|
||||
19
server/front/main/index.html
Normal file
19
server/front/main/index.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Main</title>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="glass-container">
|
||||
<div class="data-box">
|
||||
<h2>data</h2>
|
||||
<form action="#" method="POST">
|
||||
<p>Data</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
60
server/front/main/style.css
Normal file
60
server/front/main/style.css
Normal file
@@ -0,0 +1,60 @@
|
||||
* {
|
||||
margin: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Poppins', sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
background-image: url('./../login/background-image.jpeg');
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.glass-container {
|
||||
width: 600px;
|
||||
height: 700px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
border-radius: 10px;
|
||||
border: 1px solid #fff;
|
||||
}
|
||||
|
||||
.glass-container::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 10px;
|
||||
backdrop-filter: blur(5px);
|
||||
-webkit-backdrop-filter: blur(5px);
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.data-box {
|
||||
max-width: 250px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #fff;
|
||||
margin-top: 30px;
|
||||
margin-bottom: -20px;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: 20px;
|
||||
}
|
||||
p {
|
||||
font-size: 12px;
|
||||
color: #fff;
|
||||
margin-top: 15px;
|
||||
}
|
||||
24
server/front/register/index.html
Normal file
24
server/front/register/index.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Register</title>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="glass-container" id="glass-container">
|
||||
<div class="register-box">
|
||||
<h2>Register</h2>
|
||||
<form id="registerForm">
|
||||
<input type="text" id="email" name="email" required placeholder="Email">
|
||||
<input type="password" id="password" name="password" required placeholder="Password">
|
||||
<input type="password" id="confirm_password" name="confirm_password" required placeholder="Repeat the password">
|
||||
<button type="submit">Register</button>
|
||||
<p>Do you have an account? <a href="./../login/index.html" id="Login">Login</a></p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<script src="js.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
70
server/front/register/js.js
Normal file
70
server/front/register/js.js
Normal file
@@ -0,0 +1,70 @@
|
||||
document.getElementById('registerForm').addEventListener('submit', async function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = document.getElementById('email').value;
|
||||
const password = document.getElementById('password').value;
|
||||
const confirmPassword = document.getElementById('confirm_password').value;
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
showError(['Passwords are different!']);
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = {
|
||||
email,
|
||||
description: "string",
|
||||
activated: true,
|
||||
password
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:8000/user_create', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(userData)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.location.href = './../login/index.html';
|
||||
} else {
|
||||
const err = await response.json();
|
||||
if (Array.isArray(err.detail)) {
|
||||
const messages = err.detail.map(e => {
|
||||
const field = e.loc.filter(locPart => locPart !== 'body').join(' -> ');
|
||||
return `${field}: ${e.msg}`;
|
||||
});
|
||||
showError(messages);
|
||||
} else if (typeof err.detail === 'string') {
|
||||
showError([err.detail]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
showError(['Connection timeout']);
|
||||
}
|
||||
});
|
||||
|
||||
function showError(messages) {
|
||||
let errorElem = document.getElementById('formError');
|
||||
let container = document.getElementById('glass-container');
|
||||
if (!errorElem) {
|
||||
errorElem = document.createElement('div');
|
||||
errorElem.style.transition = "3s";
|
||||
errorElem.id = 'formError';
|
||||
errorElem.style.color = 'red';
|
||||
errorElem.style.marginTop = '20px';
|
||||
errorElem.style.fontSize = "14px";
|
||||
errorElem.style.fontWeight="100";
|
||||
errorElem.style.marginBottom='20px';
|
||||
errorElem.style.lineHeight = "120%";
|
||||
container.style.height = "auto";
|
||||
const form = document.getElementById('registerForm');
|
||||
form.insertAdjacentElement('afterend', errorElem);
|
||||
}
|
||||
errorElem.innerHTML = '';
|
||||
messages.forEach(msg => {
|
||||
const li = document.createElement('li');
|
||||
li.style.listStyleType="none";
|
||||
li.textContent = msg;
|
||||
errorElem.appendChild(li);
|
||||
});
|
||||
}
|
||||
102
server/front/register/style.css
Normal file
102
server/front/register/style.css
Normal file
@@ -0,0 +1,102 @@
|
||||
* {
|
||||
margin: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Poppins', sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
background-image: url('./../login/background-image.jpeg');
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.glass-container {
|
||||
width: 300px;
|
||||
height: 350px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
border-radius: 10px;
|
||||
border: 1px solid #fff;
|
||||
}
|
||||
|
||||
.glass-container::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 10px;
|
||||
backdrop-filter: blur(5px);
|
||||
-webkit-backdrop-filter: blur(5px);
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.register-box {
|
||||
max-width: 250px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #fff;
|
||||
margin-top: 30px;
|
||||
margin-bottom: -20px;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
input {
|
||||
padding: 10px;
|
||||
margin-top: 25px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: transparent;
|
||||
border: 1px solid #fff;
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
button {
|
||||
background: #fff;
|
||||
color: black;
|
||||
padding: 10px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: transparent;
|
||||
color: white;
|
||||
outline: 1px solid #fff;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 12px;
|
||||
color: #fff;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
#Login {
|
||||
text-decoration: none;
|
||||
color: #fff;
|
||||
font-weight: bold;
|
||||
}
|
||||
Reference in New Issue
Block a user