from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
from werkzeug.security import generate_password_hash, check_password_hash
import psycopg2
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key_here'
jwt = JWTManager(app)
conn = psycopg2.connect(database="flask_db", user="postgres",
password="admin", host="localhost", port="5432")
cur = conn.cursor()
cur.execute(
'''
CREATE TABLE IF NOT EXISTS users (
Id smallserial PRIMARY KEY,
Username varchar(100) NOT NULL,
email varchar(100) NOT NULL,
Password text NOT NULL,
Chack BOOLEAN,
CheckTok text
);
CREATE TABLE IF NOT EXISTS students (
Students_id smallserial PRIMARY KEY,
Name varchar(100) NOT NULL,
Surname varchar(100) NOT NULL,
Email varchar(100) ,
Password text NOT NULL,
UNIQUE(Email)
);
CREATE TABLE IF NOT EXISTS portfolio (
Portfolio_id smallserial PRIMARY KEY,
Autor_id smallserial,
FOREIGN KEY (Autor_id ) REFERENCES students (Students_id) ON DELETE CASCADE,
Title varchar(300),
Description text,
Create_date date
);
CREATE TABLE IF NOT EXISTS employer (
Employer_id smallserial PRIMARY KEY,
Company_name VARCHAR(255) NOT NULL,
Address VARCHAR(255),
Phone VARCHAR(20),
Email VARCHAR(255),
industry VARCHAR(50)
);
CREATE TABLE IF NOT EXISTS vacancy (
Vacancy_id smallserial PRIMARY KEY,
job_title VARCHAR(255) NOT NULL,
Company_id smallserial,
FOREIGN KEY (Company_id ) REFERENCES employer (Employer_id) ON DELETE CASCADE,
Description TEXT,
Salary DECIMAL(10, 2),
Posted_date DATE
);
CREATE TABLE IF NOT EXISTS respToVacancy (
Response_id smallserial PRIMARY KEY,
Port_id smallserial,
Vac_id smallserial,
FOREIGN KEY (Port_id ) REFERENCES portfolio (Portfolio_id) ON DELETE CASCADE,
FOREIGN KEY (Vac_id ) REFERENCES vacancy (Vacancy_id) ON DELETE CASCADE,
Letter TEXT,
Resp_date DATE
);
CREATE TABLE IF NOT EXISTS respToPort (
Response_id smallserial PRIMARY KEY,
Port_id smallserial,
Vac_id smallserial,
FOREIGN KEY (Port_id ) REFERENCES portfolio (Portfolio_id) ON DELETE CASCADE,
FOREIGN KEY (Vac_id ) REFERENCES vacancy (Vacancy_id) ON DELETE CASCADE,
Letter TEXT,
Resp_date DATE
);
''')
conn.commit()
cur.close()
conn.close()
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 't2948701@gmail.com'
app.config['MAIL_PASSWORD'] = 'xhlynsgbhwknahpn'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get('username')
email = data.get('email')
password = data.get('password')
hashed_password = generate_password_hash(password)
conn = psycopg2.connect(database="flask_db", user="postgres",
password="admin", host="localhost", port="5432")
cur = conn.cursor()
cur.execute('''
SELECT EXISTS (SELECT * FROM users WHERE Username = %s OR Email = %s)
''',
(username,email))
if not(cur.fetchone()[0]):
access_token = create_access_token(identity=username)
msg = Message('Hello', sender = 't2948701@gmail.com', recipients = [email])
msg.body = f"Hi! Follow the link to end registration: http://127.0.0.1:5000//authenticate/{username}/{access_token}"
mail.send(msg)
cur.execute('''
INSERT INTO users (Username,Email, Password, Chack, CheckTok) VALUES(%s, %s, %s, %s, %s) RETURNING Id;
''',
(username,email, hashed_password, False, access_token ))
id = cur.fetchone()[0]
conn.commit()
cur.close()
conn.close()
return jsonify({'message': 'User registered successfully',
"status": 200,
"id": id,
})
else:
conn.commit()
cur.close()
conn.close()
return jsonify({'message': 'User registered faild',
"status": 400,})
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
email = data.get('email')
password = data.get('password')
conn = psycopg2.connect(database="flask_db", user="postgres",
password="admin", host="localhost", port="5432")
cur = conn.cursor()
cur.execute('''
SELECT Password, Username, Chack FROM users WHERE Email = %s
''',
(email,))
inf = cur.fetchone()
if inf:
if check_password_hash(inf[0], password) and inf[2]: #Тута костыль
access_token = create_access_token(identity=inf[1])
conn.commit()
cur.close()
conn.close()
return jsonify({'access_token': access_token,
"status": 200,})
conn.commit()
cur.close()
conn.close()
return jsonify({'message': 'Invalid credentials',
"status": 400,})
@app.route('/authenticate/<string:username>/<string:token>', methods=['GET'])
def authenticate(username, token):
conn = psycopg2.connect(database="flask_db", user="postgres",
password="admin", host="localhost", port="5432")
cur = conn.cursor()
cur.execute('''
SELECT CheckTok FROM users WHERE Username = %s
''',
(username,))
inf = cur.fetchone()[0]
if inf == token:
cur.execute('''
UPDATE users SET Chack = TRUE WHERE Username = %s
''', (username,))
conn.commit()
cur.close()
conn.close()
return jsonify({'message': 'User authentication ok',
"username": username,
"status": 200})
else:
conn.commit()
cur.close()
conn.close()
return({'message': 'User authentication faild',
"status": 400,})
# @app.route('/protected', methods=['GET'])
# @jwt_required()
# def protected():
# current_user = request.identity
# return jsonify({'message': f'Protected resource for user: {current_user}'})
if __name__ == '__main__':
app.run(debug=True)