diff --git a/service/src/auth.py b/service/src/auth.py index 894e531..e4c7cee 100644 --- a/service/src/auth.py +++ b/service/src/auth.py @@ -72,8 +72,14 @@ async def sign_up(): final_text = "" for j in text: final_text += j + + private_key_text = private_key.split('\n') + text = private_key_text[1:-2] + final_private_key_text = "" + for j in text: + final_private_key_text += j - new_user = User(email=email, first_name=first_name, private_key=private_key, public_key=public_key, public_key_name = final_text, password= password1, time = datetime.datetime.now()) + new_user = User(email=email, first_name=first_name, private_key=private_key, public_key=public_key, public_key_name = final_text, private_key_name = final_private_key_text ,password= password1, time = datetime.datetime.now()) db.session.add(new_user) db.session.commit() login_user(new_user, remember=True) # missing await? diff --git a/service/src/models.py b/service/src/models.py index ffa70d4..4115c71 100644 --- a/service/src/models.py +++ b/service/src/models.py @@ -8,6 +8,11 @@ db.Column('group_id', db.Integer, db.ForeignKey('NoteGroup.id')) ) +user_friends_association = db.Table('user_friends_association', + db.Column('user_id', db.Integer, db.ForeignKey('User.id')), + db.Column('friend_id', db.Integer, db.ForeignKey('User.id')) +) + class NoteGroup(db.Model): __tablename__ = 'NoteGroup' id = db.Column(db.Integer, primary_key=True) @@ -51,6 +56,7 @@ class User(db.Model, UserMixin): private_key = db.Column(db.String(255), unique=True) public_key = db.Column(db.String(255), unique=True) public_key_name = db.Column(db.String(255), unique=True) + private_key_name = db.Column(db.String(255), unique=True) status = db.Column(db.String(255)) time = db.Column(db.DateTime(timezone=True), default=func.now()) diff --git a/service/src/views.py b/service/src/views.py index f660e1d..0bd516b 100644 --- a/service/src/views.py +++ b/service/src/views.py @@ -5,6 +5,7 @@ from .models import User from .models import user_group_association from .models import NoteOfGroup +from .models import user_friends_association from . import db import json import datetime as dt @@ -230,4 +231,42 @@ async def profil(): current_user.status = status db.session.commit() flash('Profile updated!', category='success') - return render_template("profil.html", user=current_user, groups=Note_groups) \ No newline at end of file + return render_template("profil.html", user=current_user, groups=Note_groups) + + +# @views.route('/add_friend', methods=['GET', 'POST']) +# @login_required +# async def add_friend_headfunction(): +# if request.method == 'POST': +# if 'accept_friend' in request.form: +# user_email = request.form.get('user.email') +# print(user_email) + +# elif 'reject_friend' in request.form: +# user_email = request.form.get('user.email') +# print(user_email) + +# elif 'add_friend' in request.form: +# friend_email = request.form.get('friend_email') +# print(friend_email) +# add_friend(friend_email) +# #return add_friend(friend_email) +# else: +# users = User.query.all() +# user_list = [] +# for user in users: +# if user.email != current_user.email: +# user_list.append(user) +# return render_template("add_friend.html", users=user_list) + +# # def accept_friend(): + +# # def reject_friend(): + +# def add_friend(friend_email): +# if len(friend_email) < 1: +# flash('Friend email is too short!', category='error') +# elif db.session.query(User).filter_by(email=friend_email).first(): + + + diff --git a/service/src_old/__init__.py b/service/src_old/__init__.py deleted file mode 100644 index 371b855..0000000 --- a/service/src_old/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -from flask import Flask -from flask_sqlalchemy import SQLAlchemy -from os import path -from flask_login import LoginManager -import logging -import os -import random -import base64 - -log_directory = os.path.join("..", "instance") -if not os.path.exists(log_directory): - os.makedirs(log_directory) - -fh = logging.FileHandler(os.path.join(log_directory, "service.log")) -logger = logging.getLogger("ENOWARS_LOGER") -logger.setLevel(logging.DEBUG) -fh = logging.FileHandler("../instance/service.log") -fh.setLevel(logging.DEBUG) -formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") -fh.setFormatter(formatter) -logger.addHandler(fh) - -db = SQLAlchemy() -DB_NAME = "database.db" -def generate_secret_key(): - return base64.b64encode(random.SystemRandom().getrandbits(256).to_bytes(32, 'little')).decode('utf-8') - - -def create_app(): - app = Flask(__name__) - app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', generate_secret_key()) - app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}' - db.init_app(app) - - from .views import views - from .auth import auth - - app.register_blueprint(views, url_prefix='/') - app.register_blueprint(auth, url_prefix='/') - - from .models import User, Note - - with app.app_context(): - db.create_all() - - login_manager = LoginManager() - login_manager.login_view = 'auth.login' - login_manager.init_app(app) - - @login_manager.user_loader - def load_user(id): - return User.query.get(int(id)) - - return app - - -def create_database(app): - if not path.exists('website/' + DB_NAME): - db.create_all(app=app) - logger.info('Created Database!') diff --git a/service/src_old/aes_encryption.py b/service/src_old/aes_encryption.py deleted file mode 100644 index 2e95dc5..0000000 --- a/service/src_old/aes_encryption.py +++ /dev/null @@ -1,42 +0,0 @@ -from Crypto.Cipher import AES -from Crypto.Random import get_random_bytes -from Crypto.Util.Padding import pad, unpad -import random -import time -import datetime -import base64 - -def random_number(): - random_number = random.randint(0, 2**128 - 1) - return random_number.to_bytes(16, byteorder='big') - -def aes_encrypt(plaintext): - current_time = datetime.datetime.now().time() - time_str = str(current_time) - time = time_str.split(':') - seed = time[0] + time[1] - random.seed(seed) - - key = random_number() - nonce = random_number() - - cipher = AES.new(key, AES.MODE_GCM, nonce=nonce) - plaintext_bytes = plaintext.encode() - padded_plaintext = pad(plaintext_bytes, AES.block_size) - ciphertext = cipher.encrypt(padded_plaintext) - return base64.b64encode(ciphertext).decode(), key, nonce - - - - - - - - - - - - - - - diff --git a/service/src_old/auth.py b/service/src_old/auth.py deleted file mode 100644 index e4c7cee..0000000 --- a/service/src_old/auth.py +++ /dev/null @@ -1,98 +0,0 @@ -from flask import Blueprint, render_template, request, flash, redirect, url_for -from .models import User -from werkzeug.security import generate_password_hash, check_password_hash -from . import db, logger ##means from __init__.py import db -from flask_login import login_user, login_required, logout_user, current_user -from . import rsa_encryption -import datetime - - -auth = Blueprint('auth', __name__) - - -@auth.route('/login', methods=['GET', 'POST']) -async def login(): - if request.method == 'POST': - email = request.form.get('email') - password = request.form.get('password') - user = User.query.filter_by(email=email).first() - if user: - if(user.password == password): - flash('Logged in successfully!', category='success') - login_user(user, remember=True) - return redirect(url_for('views.home')) - else: - flash('Incorrect password, try again.', category='error') - else: - flash('Email does not exist.', category='error') - return render_template("login.html", user=current_user) - - -@auth.route('/logout') -@login_required -async def logout(): - logout_user() - return redirect(url_for('auth.login')) - - -@auth.route('/sign-up', methods=['GET', 'POST']) -async def sign_up(): - if request.method == 'POST': - email = request.form.get('email') - first_name = request.form.get('firstName') - password1 = request.form.get('password1') - password2 = request.form.get('password2') - #to be changed - public_key = request.form.get('public_key') - - - user = User.query.filter_by(email=email).first() - if user: - flash('Email already exists.', category='error') - elif len(email) < 4: - flash('Email must be greater than 3 characters.', category='error') - elif len(first_name) < 2: - flash('First name must be greater than 1 character.', category='error') - elif password1 != password2: - flash('Passwords don\'t match.', category='error') - elif len(password1) < 7: - flash('Password must be at least 7 characters.', category='error') - else: - if public_key == "on": - #check if public key is already in use - while True: - private_key, public_key = rsa_encryption.get_keys() - all_public_keys = [user_public.public_key for user_public in User.query.all()] - if public_key not in all_public_keys: - break - - #saving the public key in a format that can be used as later - text = public_key.split('\n') - text = text[1:-2] - final_text = "" - for j in text: - final_text += j - - private_key_text = private_key.split('\n') - text = private_key_text[1:-2] - final_private_key_text = "" - for j in text: - final_private_key_text += j - - new_user = User(email=email, first_name=first_name, private_key=private_key, public_key=public_key, public_key_name = final_text, private_key_name = final_private_key_text ,password= password1, time = datetime.datetime.now()) - db.session.add(new_user) - db.session.commit() - login_user(new_user, remember=True) # missing await? - flash('Account created!', category='success') - return redirect(url_for('views.home')) - else: - private_key = None - public_key = None - new_user = User(email=email, first_name=first_name, private_key=private_key, public_key=public_key, password= password1, time = datetime.datetime.now()) - db.session.add(new_user) - db.session.commit() #await? - login_user(new_user, remember=True) # missing await? - flash('Account created!', category='success') - return redirect(url_for('views.home')) - - return render_template("sign_up.html", user=current_user) diff --git a/service/src_old/cleanup.py b/service/src_old/cleanup.py deleted file mode 100644 index d74a4ab..0000000 --- a/service/src_old/cleanup.py +++ /dev/null @@ -1,58 +0,0 @@ -import os -import sqlite3 -import datetime -import time - -Interval_for_cleanup = datetime.timedelta(minutes=15) - -db_path = os.path.dirname(__file__) -db_path = os.path.dirname(db_path) -db_path = os.path.join(db_path, 'instance') -db_path = os.path.join(db_path, 'database.db') - -def cleanup_header(): - time.sleep(120) - time_to_sleep = 60 - while True: - cleanup_Note() - cleanup_User() - cleanup_NoteGroup() - cleanup_NoteOfGroup() - time.sleep(time_to_sleep) - - -def cleanup_Note(): - db = sqlite3.connect(db_path) - cursor = db.cursor() - cursor.execute('DELETE FROM Note WHERE time < ?', (datetime.datetime.now() - Interval_for_cleanup,)) - db.commit() - db.close() - -def cleanup_User(): - db = sqlite3.connect(db_path) - cursor = db.cursor() - cursor.execute('SELECT id FROM User WHERE time < ?', (datetime.datetime.now() - Interval_for_cleanup,)) - users_to_delete = cursor.fetchall() - users_to_delete = [user[0] for user in users_to_delete] - cursor.execute('DELETE FROM user_group_association WHERE user_id IN ({})'.format(','.join('?' * len(users_to_delete))), users_to_delete) - cursor.execute('DELETE FROM User WHERE time < ?', (datetime.datetime.now() - Interval_for_cleanup,)) - db.commit() - db.close() - -def cleanup_NoteGroup(): - db = sqlite3.connect(db_path) - cursor = db.cursor() - cursor.execute('DELETE FROM NoteGroup WHERE time < ?', (datetime.datetime.now() - Interval_for_cleanup,)) - db.commit() - db.close() - -def cleanup_NoteOfGroup(): - db = sqlite3.connect(db_path) - cursor = db.cursor() - cursor.execute('DELETE FROM NoteOfGroup WHERE time < ?', (datetime.datetime.now() - Interval_for_cleanup,)) - db.commit() - db.close() - - -if __name__ == '__main__': - cleanup_header() \ No newline at end of file diff --git a/service/src_old/models.py b/service/src_old/models.py deleted file mode 100644 index 4115c71..0000000 --- a/service/src_old/models.py +++ /dev/null @@ -1,64 +0,0 @@ -from . import db -from flask_login import UserMixin -from sqlalchemy.sql import func - -# Association table for the many-to-many relationship between users and groups -user_group_association = db.Table('user_group_association', - db.Column('user_id', db.Integer, db.ForeignKey('User.id')), - db.Column('group_id', db.Integer, db.ForeignKey('NoteGroup.id')) -) - -user_friends_association = db.Table('user_friends_association', - db.Column('user_id', db.Integer, db.ForeignKey('User.id')), - db.Column('friend_id', db.Integer, db.ForeignKey('User.id')) -) - -class NoteGroup(db.Model): - __tablename__ = 'NoteGroup' - id = db.Column(db.Integer, primary_key=True) - name = db.Column(db.String(150)) - group_key = db.Column(db.String(255)) - time = db.Column(db.DateTime(timezone=True), default=func.now()) - # Define the relationship with User using the association table - users = db.relationship('User', secondary=user_group_association, backref=db.backref('groups', lazy='dynamic')) - notes = db.relationship('NoteOfGroup', backref='group', lazy=True) - -class NoteOfGroup(db.Model): - __tablename__ = 'NoteOfGroup' - id = db.Column(db.Integer, primary_key=True) - name = db.Column(db.String(255)) - data = db.Column(db.String(10000)) - encrypted_data = db.Column(db.String(10000)) - time = db.Column(db.DateTime(timezone=True), default=func.now()) - description = db.Column(db.Text) - group_id = db.Column(db.Integer, db.ForeignKey('NoteGroup.id')) - key = db.Column(db.String(255)) - nonce = db.Column(db.String(255)) - -class Note(db.Model): - __tablename__ = 'Note' - id = db.Column(db.Integer, primary_key=True) - name = db.Column(db.String(255)) - data = db.Column(db.String(10000)) - encrypted_data = db.Column(db.String(10000)) - description = db.Column(db.Text) - owner_id = db.Column(db.Integer, db.ForeignKey('User.id')) - destination_id = db.Column(db.Integer) - time = db.Column(db.DateTime(timezone=True), default=func.now()) - -class User(db.Model, UserMixin): - __tablename__ = 'User' - id = db.Column(db.Integer, primary_key=True) - email = db.Column(db.String(150), unique=True) - password = db.Column(db.String(150)) - first_name = db.Column(db.String(150)) - notes = db.relationship('Note', backref='owner', lazy=True) - private_key = db.Column(db.String(255), unique=True) - public_key = db.Column(db.String(255), unique=True) - public_key_name = db.Column(db.String(255), unique=True) - private_key_name = db.Column(db.String(255), unique=True) - status = db.Column(db.String(255)) - time = db.Column(db.DateTime(timezone=True), default=func.now()) - - - diff --git a/service/src_old/requirements.txt b/service/src_old/requirements.txt deleted file mode 100644 index 4a2b19e..0000000 Binary files a/service/src_old/requirements.txt and /dev/null differ diff --git a/service/src_old/rsa_encryption.py b/service/src_old/rsa_encryption.py deleted file mode 100644 index 1f4f14b..0000000 --- a/service/src_old/rsa_encryption.py +++ /dev/null @@ -1,98 +0,0 @@ -import rsa -from cryptography.hazmat.primitives.asymmetric import rsa as crsa -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import padding -from cryptography.hazmat.primitives import hashes -import random -import sympy -import time -import pickle -import base64 - -from gmpy2 import is_prime - -# the prime calculation is based on https://www.geeksforgeeks.org/how-to-generate-large-prime-numbers-for-rsa-algorithm/ -# First 10000 prime numbers - - -first_primes_list = list(sympy.primerange(2, 10000)) - -# Generate RSA key pair -def generate_key_pair(p,q): - n = p * q - e = 65537 # Commonly used public exponent - d = rsa.common.inverse(e, (p-1)*(q-1)) - # Generate RSA key object - private_key = rsa.PrivateKey(n, e, d, p, q) - public_key = rsa.PublicKey(n, e) - return private_key, public_key - -# Generate a random n-bit number -def nBitRandom(n): - random.seed(random.SystemRandom().random()) - return random.randrange(2**(n-1)+1, 2**n - 1) - - -def getLowLevelPrime(n): - while True: - # Obtain a random number - randomnumber = nBitRandom(n) - randomnumber2 = randomnumber + 4 - - # test if number is prime - for divisor in first_primes_list: - if randomnumber % divisor == 0 and divisor**2 <= randomnumber or randomnumber2 % divisor == 0 and divisor**2 <= randomnumber2: - break - else: - return randomnumber, randomnumber2 - - -def random_prime(): - def test(p,q): - for _ in first_primes_list: - if p % _ == 0 or q % _ == 0: return False - return True - while True: - p = nBitRandom(256) - p |= 1 - q = p + 6 - if test(p,q): - if is_prime(p) and is_prime(q): return p,q - - -def get_keys(): - p,q = random_prime() - private_key, public_key = generate_key_pair(p,q) - return private_key.save_pkcs1().decode(), public_key.save_pkcs1().decode() - - -async def encryption_of_message(message, public_key): - #make 52 byte/char long messages and add them together to make bigger - #byte_len = 20 - byte_len = 52 - public_key = rsa.PublicKey.load_pkcs1(public_key.encode()) - message = message.encode('utf-8') - message_chunks = [message[i:i+byte_len] for i in range(0, len(message), byte_len)] - cipher_string = b"" - for i in range(len(message_chunks)): - cipher = rsa.encrypt(message_chunks[i], public_key) - cipher_string += cipher - return base64.b64encode(cipher_string).decode() - -def decryption_of_message(cipher_string, private_key): - #byte_len = 32 #64 - byte_len = 64 - private_key = rsa.PrivateKey.load_pkcs1(private_key.encode()) - cipher_string = base64.b64decode(cipher_string) - cipher_array = [cipher_string[i:i+byte_len] for i in range(0, len(cipher_string), byte_len)] - plaintext = "" - for cipher in cipher_array: - plaintext += rsa.decrypt(cipher, private_key).decode() - return plaintext - -# if __name__ == '__main__': -# message = "ENOABCDEF1234567890+/=ABCDEFGHIJKLM1234567890+/=1234567890+/=" -# private_key, public_key = get_keys() -# cipher_string = encryption_of_message(message, public_key) -# plaintext = decryption_of_message(cipher_string, private_key) -# print("Plaintext: ", plaintext) diff --git a/service/src_old/static/index.js b/service/src_old/static/index.js deleted file mode 100644 index 7039e54..0000000 --- a/service/src_old/static/index.js +++ /dev/null @@ -1,16 +0,0 @@ -function deleteNote(noteId) { - fetch("/delete-note", { - method: "POST", - body: JSON.stringify({ noteId: noteId }), - }).then((_res) => { - window.location.href = "/"; - }); -} -function deleteNoteGroup(noteGroupId) { - fetch("/delete-note-group", { - method: "POST", - body: JSON.stringify({ noteGroupId: noteGroupId }), - }).then((_res) => { - window.location.href = window.location.pathname; - }); -} diff --git a/service/src_old/static/style.css b/service/src_old/static/style.css deleted file mode 100644 index 7d14101..0000000 --- a/service/src_old/static/style.css +++ /dev/null @@ -1,2 +0,0 @@ -/* here will be the css code for the whatsapp scam side */ - \ No newline at end of file diff --git a/service/src_old/templates/add_friend.html b/service/src_old/templates/add_friend.html deleted file mode 100644 index a838093..0000000 --- a/service/src_old/templates/add_friend.html +++ /dev/null @@ -1,21 +0,0 @@ -{% extends "base.html" %} {% block title %}ADD FRIENDS{% endblock %} {% block content - %} -
-
- -
- -
- -
-
-{% endblock %} \ No newline at end of file diff --git a/service/src_old/templates/base.html b/service/src_old/templates/base.html deleted file mode 100644 index 9cfc60c..0000000 --- a/service/src_old/templates/base.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - {% block title %}Home{% endblock %} - - - - - {% with messages = get_flashed_messages(with_categories=true) %} {% if - messages %} {% for category, message in messages %} {% if category == - 'error' %} - - {% else %} - - {% endif %} {% endfor %} {% endif %} {% endwith %} - -
{% block content %} {% endblock %}
- - - - -{% block javascript %} - - - -{% endblock %} - - diff --git a/service/src_old/templates/group_page.html b/service/src_old/templates/group_page.html deleted file mode 100644 index 7ae37f2..0000000 --- a/service/src_old/templates/group_page.html +++ /dev/null @@ -1,24 +0,0 @@ -{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content - %} -

Group Messages

-
- -
-
- -
-
- -
-
- {% endblock %} \ No newline at end of file diff --git a/service/src_old/templates/group_page_unauthorized.html b/service/src_old/templates/group_page_unauthorized.html deleted file mode 100644 index 44b33ba..0000000 --- a/service/src_old/templates/group_page_unauthorized.html +++ /dev/null @@ -1,14 +0,0 @@ -{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content - %} -

Group Messages

-
- -
- {% endblock %} \ No newline at end of file diff --git a/service/src_old/templates/groups.html b/service/src_old/templates/groups.html deleted file mode 100644 index 2546561..0000000 --- a/service/src_old/templates/groups.html +++ /dev/null @@ -1,27 +0,0 @@ -{% extends "base.html" %} {% block title %}Group Channels{% endblock %} {% block content - %} -
-
- -
- -
- -
-
- -
-
-{% endblock %} - - - - \ No newline at end of file diff --git a/service/src_old/templates/home.html b/service/src_old/templates/home.html deleted file mode 100644 index c4bf12d..0000000 --- a/service/src_old/templates/home.html +++ /dev/null @@ -1,42 +0,0 @@ -{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content - %} -

Private Messages

- -
- -
- -
-
- -
-
- {% endblock %} diff --git a/service/src_old/templates/login.html b/service/src_old/templates/login.html deleted file mode 100644 index 4f67e1b..0000000 --- a/service/src_old/templates/login.html +++ /dev/null @@ -1,28 +0,0 @@ -{% extends "base.html" %} {% block title %}Login{% endblock %} {% block content -%} -
-

Login

-
- - -
-
- - -
-
- -
-{% endblock %} diff --git a/service/src_old/templates/profil.html b/service/src_old/templates/profil.html deleted file mode 100644 index 501ca18..0000000 --- a/service/src_old/templates/profil.html +++ /dev/null @@ -1,59 +0,0 @@ -{% extends "base.html" %} {% block title %}Profil{% endblock %} {% block content - %} -
-

Profil

-
- -
-
-
- {% if groups %} -

Groups you created

-
- -
- {% endif %} - -

Your Keys

- {% if user.public_key%} -
- -
- {% else %} -
- - -
-
- -
- {% endif %} - -

Edit Profil

-
- - -
-
- -
- -
- {% endblock %} \ No newline at end of file diff --git a/service/src_old/templates/sign_up.html b/service/src_old/templates/sign_up.html deleted file mode 100644 index 88f4355..0000000 --- a/service/src_old/templates/sign_up.html +++ /dev/null @@ -1,59 +0,0 @@ -{% extends "base.html" %} {% block title %}Sign Up{% endblock %} {% block -content %} -
-

Sign Up

-
- - -
-
- - -
- -
- - -
- -
- - -
-
- - -
-
- -
-{% endblock %} diff --git a/service/src_old/templates/userlist.html b/service/src_old/templates/userlist.html deleted file mode 100644 index 09f9c2d..0000000 --- a/service/src_old/templates/userlist.html +++ /dev/null @@ -1,16 +0,0 @@ -{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content - %} -
-

User

-
- -
-
- {% endblock %} \ No newline at end of file diff --git a/service/src_old/views.py b/service/src_old/views.py deleted file mode 100644 index 0bd516b..0000000 --- a/service/src_old/views.py +++ /dev/null @@ -1,272 +0,0 @@ -from flask import Blueprint, render_template, request, flash, jsonify, redirect, url_for -from flask_login import login_required, current_user -from .models import Note -from .models import NoteGroup -from .models import User -from .models import user_group_association -from .models import NoteOfGroup -from .models import user_friends_association -from . import db -import json -import datetime as dt - -from sqlalchemy.orm import aliased -from sqlalchemy.sql import exists - -from . import aes_encryption -from . import rsa_encryption - - -views = Blueprint('views', __name__) - -@views.route('/', methods=['GET', 'POST']) -@login_required -async def home(): - if request.method == 'POST': - note = request.form.get('note')#Gets the note from the HTML - public_key = request.form.get('public_key') - - if len(note) < 1: - flash('Note is too short!', category='error') - else: - users = User.query.all() - public_keys = [user.public_key_name for user in users] - - if public_key is None: - new_note = Note(data=note, owner_id=current_user.id, destination_id=None, time = dt.datetime.now()) #providing the schema for the note - elif public_key not in public_keys: - new_note = Note(data=note, owner_id=current_user.id, destination_id=None, time = dt.datetime.now()) #providing the schema for the note - flash('Public key not found, message not encrypted', category='error') - else: - target_user = User.query.filter_by(public_key_name=public_key).first() - target_user_id = target_user.id - encrypted_note = await rsa_encryption.encryption_of_message(note, target_user.public_key) - new_note = Note(data=note, encrypted_data = encrypted_note, owner_id=current_user.id, destination_id=target_user_id, time = dt.datetime.now()) #providing the schema for the note - flash('Message encrypted and sent', category='success') - - db.session.add(new_note) #adding the note to the database - db.session.commit() - n = Note.query - return render_template("home.html", user=current_user, notes=n) - -@views.route('/creategroup', methods=['GET', 'POST']) -@login_required -async def group_headfunction(): - if request.method == 'POST': - if 'join_group' in request.form: - group_id = request.form.get('join_group') - key = request.form.get('group_key_join_' + str(group_id)) - return join_group(group_id, key) - elif 'add_group' in request.form: - group_name = request.form.get('group_name') - group_key = request.form.get('group_key') - return creategroup(group_name, group_key) - - note_groups = db.session.query(NoteGroup).all() - groups = [{column.name: getattr(note_group, column.name) for column in NoteGroup.__table__.columns} for note_group in note_groups] - return render_template("groups.html", user=current_user, groups=groups) - -def creategroup(group_name, group_key): - if request.method == 'POST': - group_name = request.form.get('group_name') - if len(group_name) < 1 or len(group_key) < 1: - flash('Group Name or Key is too short!', category='error') - - elif db.session.query(NoteGroup).filter_by(name=group_name).first(): - flash('Group name already exists.', category='error') - - else: - # Create a new NoteGroup instance - new_group = NoteGroup(name=group_name, group_key=group_key, time= dt.datetime.now()) - - # Add the current user to the group - new_group.users.append(current_user) - - # Add the group to the session and commit - db.session.add(new_group) - db.session.commit() - flash('Group added!', category='success') - return redirect(url_for('views.group_page', group_id=new_group.id)) - - #Show all the groups on the page - # Retrieve all rows from the NoteGroup table - note_groups = db.session.query(NoteGroup).all() - # Prepare a list of dictionaries where each dictionary represents a row with column names as keys and values as values - groups = [{column.name: getattr(note_group, column.name) for column in NoteGroup.__table__.columns} for note_group in note_groups] - return render_template("groups.html", user=current_user, groups=groups) - -def join_group(group_id, key): - group = db.session.query(NoteGroup).filter_by(id=group_id).first() - if group: - if key == group.group_key: - id = group.id - UserId = current_user.id - if db.session.query(user_group_association).filter_by(user_id=UserId, group_id=id).first(): - return redirect(url_for('views.group_page', group_id=group.id)) - else: - # Add the current user to the group - join = user_group_association.insert().values(user_id=UserId, group_id=id) - db.session.execute(join) - db.session.commit() - flash('You have joined the group!', category='success') - group = db.session.query(NoteGroup).filter_by(id=group_id).first() - return redirect(url_for('views.group_page', group_id=group.id)) - else: - flash('Incorrect key. Please try again.', category='error') - else: - flash('Group not found.', category='error') - return redirect(url_for('views.home')) - -@views.route('/creategroup/', methods=['GET', 'POST']) -@login_required -async def group_page(group_id): - #id unique so only one object will be returned - group_allusers = db.session.query(NoteGroup).filter_by(id=group_id).first() - if group_allusers: - if any(one_user == current_user for one_user in group_allusers.users): - if request.method == 'POST': - note_of_group_data = request.form.get('note_of_group')#Gets the note from the HTML - if len(note_of_group_data) < 1: - flash('Note is too short!', category='error') - else: - encrypted_data, key, nonce = aes_encryption.aes_encrypt(note_of_group_data) - new_note_of_group = NoteOfGroup(data=note_of_group_data, group_id=group_allusers.id, encrypted_data=encrypted_data, time= dt.datetime.now(), key=str(key), nonce=str(nonce)) - db.session.add(new_note_of_group) #adding the note to the database - db.session.commit() - flash('Note added!', category='success') - n = NoteOfGroup.query.filter_by(group_id=group_id) - return render_template("group_page.html", user=current_user, notes=n, group=group_allusers) - else: - n = NoteOfGroup.query.filter_by(group_id=group_id) - return render_template("group_page_unauthorized.html", user=current_user, notes=n, group=group_allusers) - else: - flash('Group not found.', category='error') - return redirect(url_for('views.home')) - -@views.route('/userlist', methods=['GET', 'POST']) -@login_required -async def userlist(): - users = User.query.all() - user_list_with_public_keys = [] - for user in users: - if user.public_key_name is not None: - user_list_with_public_keys.append(user) - return render_template("userlist.html", user=current_user, users=user_list_with_public_keys) - -#view js script for information and base.html -@views.route('/delete-note', methods=['POST']) -async def delete_note(): - note = json.loads(request.data) # this function expects a JSON from the INDEX.js file - noteId = note['noteId'] - note = Note.query.get(noteId) - if note: - if note.owner_id == current_user.id: - db.session.delete(note) - db.session.commit() - - return jsonify({}) - -#view js script for information and base.html -@views.route('/delete-note-group', methods=['POST']) -async def delete_note_group(): - note = json.loads(request.data) - noteId = note['noteGroupId'] - note = NoteOfGroup.query.get(noteId) - - if note: - group = NoteGroup.query.filter_by(id=note.group_id).first() - if any(one_user == current_user for one_user in group.users): - db.session.delete(note) - db.session.commit() - - return jsonify({}) - -###### - -@views.route('/profil', methods=['GET', 'POST']) -@login_required -async def profil(): - alias_a = aliased(user_group_association) - group_users = db.session.query(alias_a.c.group_id).filter( - alias_a.c.user_id == current_user.id, - ).all() - group_ids = [group_id for group_id, in group_users] - final_group_ids = [] - for i in group_ids: - a = db.session.query(user_group_association).filter_by(group_id=i).first() - if a[0] == current_user.id: - final_group_ids.append(i) - Note_groups = NoteGroup.query.filter(NoteGroup.id.in_(final_group_ids)).all() - - - if request.method == 'POST': - status = request.form.get('status') - public_key = request.form.get('public_key') - if public_key == "on": - #check if public key is already in use - while True: - private_key, public_key = rsa_encryption.get_keys() - all_public_keys = [user_public.public_key for user_public in User.query.all()] - if public_key not in all_public_keys: - break - - #saving the public key in a format that can be used as later - text = public_key.split('\n') - text = text[1:-2] - final_text = "" - for j in text: - final_text += j - - - current_user.public_key = public_key - current_user.public_key_name = final_text - current_user.private_key = private_key - current_user.status = status - db.session.commit() - return redirect(url_for('views.profil')) - else: - if len(status) < 1: - flash('Status is too short!', category='error') - else: - current_user.status = status - db.session.commit() - flash('Profile updated!', category='success') - return render_template("profil.html", user=current_user, groups=Note_groups) - - -# @views.route('/add_friend', methods=['GET', 'POST']) -# @login_required -# async def add_friend_headfunction(): -# if request.method == 'POST': -# if 'accept_friend' in request.form: -# user_email = request.form.get('user.email') -# print(user_email) - -# elif 'reject_friend' in request.form: -# user_email = request.form.get('user.email') -# print(user_email) - -# elif 'add_friend' in request.form: -# friend_email = request.form.get('friend_email') -# print(friend_email) -# add_friend(friend_email) -# #return add_friend(friend_email) -# else: -# users = User.query.all() -# user_list = [] -# for user in users: -# if user.email != current_user.email: -# user_list.append(user) -# return render_template("add_friend.html", users=user_list) - -# # def accept_friend(): - -# # def reject_friend(): - -# def add_friend(friend_email): -# if len(friend_email) < 1: -# flash('Friend email is too short!', category='error') -# elif db.session.query(User).filter_by(email=friend_email).first(): - - -