Commit 9d7bba8b031c4f9e77d02f03d7291901ce66a3d1
1 parent
70f939b38b
Exists in
master
add_menu_with_permissions_db function
Showing 26 changed files with 131 additions and 333 deletions Inline Diff
- __pycache__/main.cpython-310.pyc
- __pycache__/routes.cpython-310.pyc
- components/__pycache__/__init__.cpython-310.pyc
- components/adm/README.md
- components/adm/__pycache__/__init__.cpython-310.pyc
- components/adm/adm/__pycache__/__init__.cpython-310.pyc
- components/adm/adm/__pycache__/models.cpython-310.pyc
- components/adm/adm/__pycache__/views.cpython-310.pyc
- components/adm/adm/models.py
- components/adm/adm/views.py
- components/adm/requirements.txt
- components/adm/setup.py
- components/k2test/__pycache__/__init__.cpython-310.pyc
- components/k2test/k2test/__pycache__/__init__.cpython-310.pyc
- components/k2test/k2test/__pycache__/views.cpython-310.pyc
- components/k2test/k2test/views.py
- db/database.db
- k2/__pycache__/__init__.cpython-310.pyc
- k2/__pycache__/k2admmenu.cpython-310.pyc
- k2/__pycache__/k2cfg.cpython-310.pyc
- k2/__pycache__/k2comp.cpython-310.pyc
- k2/__pycache__/k2obj.cpython-310.pyc
- k2/__pycache__/k2rout.cpython-310.pyc
- k2/k2admmenu.py
- k2/k2rout.py
- languages/babel_translation_directories.yml
__pycache__/main.cpython-310.pyc
No preview for this file type
__pycache__/routes.cpython-310.pyc
No preview for this file type
components/__pycache__/__init__.cpython-310.pyc
No preview for this file type
components/adm/README.md
| 1 | # main.py | File was deleted | |
| 2 | |||
| 3 | from components.adm.adm.views import adm | ||
| 4 | from components.test.test.views import test | ||
| 5 | |||
| 6 | app.register_blueprint(adm, url_prefix='/adm') | ||
| 7 | |||
| 8 | cd components/adm | ||
| 9 | pip install -r requirements.txt | ||
| 10 | |||
| 11 | |||
| 12 | endpoint "http://127.0.0.1:5000/adm/register" | ||
| 13 | dictionary to register in such way | ||
| 14 | { | ||
| 15 | "login": "xxx", | ||
| 16 | "password": "xxx", | ||
| 17 | "name": "xxx", | ||
| 18 | "email": "xxx" | ||
| 19 | } | ||
| 20 | |||
| 21 | |||
| 22 | endpoint "http://127.0.0.1:5000/adm/login" | ||
| 23 | dictionary to login in such way | ||
| 24 | { | ||
| 25 | "login":"xxx", | ||
| 26 | "password":"xxx" | ||
| 27 | } | ||
| 28 | |||
| 29 | endpoint http://127.0.0.1:5000/adm/changePassword | ||
| 30 | dictionary to changePassword in such way | ||
| 31 | { | ||
| 32 | "old_password":"xxx", | ||
| 33 | "new_password": "xxx", | ||
| 34 | "re_new_password": "xxx" | ||
| 35 | } | ||
| 36 | endpoint http://127.0.0.1:5000/adm/newUser | ||
| 37 | { | ||
| 38 | "login": "xxx", | ||
| 39 | "password": "xxx", | ||
| 40 | "name": "xxx", | ||
| 41 | "email": "xxx", | ||
| 42 | "phone": "xxx", | ||
| 43 | "repassword": "xxx" | ||
| 44 | |||
| 45 | } |
components/adm/__pycache__/__init__.cpython-310.pyc
No preview for this file type
components/adm/adm/__pycache__/__init__.cpython-310.pyc
No preview for this file type
components/adm/adm/__pycache__/models.cpython-310.pyc
No preview for this file type
components/adm/adm/__pycache__/views.cpython-310.pyc
No preview for this file type
components/adm/adm/models.py
| 1 | import uuid | File was deleted | |
| 2 | from sqlalchemy import Column, Integer, String | ||
| 3 | from sqlalchemy.ext.declarative import declarative_base | ||
| 4 | from flask_jwt_extended import create_access_token, decode_token | ||
| 5 | from datetime import timedelta | ||
| 6 | import hashlib | ||
| 7 | from flask import current_app as k2 | ||
| 8 | |||
| 9 | |||
| 10 | Base = declarative_base() | ||
| 11 | |||
| 12 | class k2users(Base): | ||
| 13 | __tablename__ = 'k2users' | ||
| 14 | user_id = Column(Integer, primary_key=True) | ||
| 15 | login = Column(String(50), unique=True) | ||
| 16 | name = Column(String(50)) | ||
| 17 | email = Column(String(150)) | ||
| 18 | password = Column(String(50)) | ||
| 19 | phone = Column(String(20)) | ||
| 20 | firstname = Column(String(50)) | ||
| 21 | roleid = Column(String(50)) | ||
| 22 | |||
| 23 | def __init__(self, **kwargs): | ||
| 24 | self.user_id = hashlib.md5(str(uuid.uuid4()).encode()).hexdigest() | ||
| 25 | self.login = kwargs.get('login') | ||
| 26 | self.password = hashlib.md5(kwargs.get('password').encode()).hexdigest() | ||
| 27 | self.name = kwargs.get('name') | ||
| 28 | self.email = kwargs.get('email') | ||
| 29 | self.phone = kwargs.get('phone') | ||
| 30 | self.firstname = kwargs.get('firstname') | ||
| 31 | self.roleid = kwargs.get('roleid') | ||
| 32 | |||
| 33 | |||
| 34 | def get_token(self, expire_time=24): | ||
| 35 | expires_delta = timedelta(expire_time) | ||
| 36 | token = create_access_token(identity=self.user_id, expires_delta=expires_delta) | ||
| 37 | if self.roleid == '1': | ||
| 38 | role = 'admin' | ||
| 39 | else: | ||
| 40 | role = "client" | ||
| 41 | |||
| 42 | userData = { | ||
| 43 | "avatar": "/src/assets/images/avatars/avatar-4.png", | ||
| 44 | "email": self.email, | ||
| 45 | "fullName": self.name, | ||
| 46 | "id": self.user_id, | ||
| 47 | "role": role, | ||
| 48 | "username": self.login | ||
| 49 | |||
| 50 | } | ||
| 51 | if self.roleid != '1': | ||
| 52 | userAbilities = [ | ||
| 53 | { | ||
| 54 | "action": "read", | ||
| 55 | "subject": "Auth"}, | ||
| 56 | |||
| 57 | { | ||
| 58 | "action": "read", | ||
| 59 | "subject": "AclDemo"} | ||
| 60 | ] | ||
| 61 | else: | ||
| 62 | userAbilities = [ | ||
| 63 | { | ||
| 64 | "action": "manage", | ||
| 65 | "subject": "all" | ||
| 66 | } | ||
| 67 | ] | ||
| 68 | return (token, userData,userAbilities) | ||
| 69 | |||
| 70 | @classmethod | ||
| 71 | def authenticate(cls, login, password): | ||
| 72 | session = k2.extensions['sqlalchemy'].db.session | ||
| 73 | user = '' | ||
| 74 | try: | ||
| 75 | user = session.query(cls).filter(cls.login == login).filter(cls.password == hashlib.md5(password.encode()).hexdigest()).one() | ||
| 76 | except: | ||
| 77 | user = None | ||
| 78 | return user | ||
| 79 | |||
| 80 | @classmethod | ||
| 81 | def user_by_login(cls, login): | ||
| 82 | session = k2.extensions['sqlalchemy'].db.session | ||
| 83 | user = session.query(cls).filter(cls.login == login).first() | ||
| 84 | return user | ||
| 85 | 1 | import uuid | |
| 86 | 2 | from sqlalchemy import Column, Integer, String | |
| 87 | 3 | from sqlalchemy.ext.declarative import declarative_base | |
| 88 | 4 | from flask_jwt_extended import create_access_token, decode_token | |
| 89 | 5 | from datetime import timedelta | |
| 90 | 6 | import hashlib |
components/adm/adm/views.py
| 1 | import hashlib | File was deleted | |
| 2 | import uuid | ||
| 3 | from flask import Blueprint, request, jsonify | ||
| 4 | from flask import current_app as k2 | ||
| 5 | from flask_jwt_extended import jwt_required, get_jwt_identity | ||
| 6 | |||
| 7 | |||
| 8 | from .models import k2users | ||
| 9 | |||
| 10 | |||
| 11 | adm = Blueprint('adm', __name__, template_folder='templates', static_folder='static', static_url_path='/adm') | ||
| 12 | |||
| 13 | |||
| 14 | @adm.route('/usersclients', methods=["GET"]) | ||
| 15 | @jwt_required() | ||
| 16 | def users_clients(): | ||
| 17 | return jsonify({"data": "roles"}) | ||
| 18 | |||
| 19 | @adm.route('/menuaaccess', methods=["GET"]) | ||
| 20 | @jwt_required() | ||
| 21 | def menu_aaccess(): | ||
| 22 | return jsonify({"data": "roles"}) | ||
| 23 | |||
| 24 | @adm.route('/users', methods=["GET"]) | ||
| 25 | @jwt_required() | ||
| 26 | def grid_users(): | ||
| 27 | return jsonify({"data": "users"}) | ||
| 28 | |||
| 29 | |||
| 30 | @adm.route('/roles', methods=["GET"]) | ||
| 31 | @jwt_required() | ||
| 32 | def grid_roles(): | ||
| 33 | return jsonify({"data": "roles"}) | ||
| 34 | |||
| 35 | |||
| 36 | @adm.route('/register', methods=["POST"]) | ||
| 37 | def register(): | ||
| 38 | params = request.json | ||
| 39 | session = k2.extensions['sqlalchemy'].db.session | ||
| 40 | exist = k2users.user_by_login(request.json['login']) | ||
| 41 | # exist = session.query(k2users).filter_by(login=request.json['login']).first() | ||
| 42 | if not exist: | ||
| 43 | user = k2users(**params) | ||
| 44 | session.add(user) | ||
| 45 | session.commit() | ||
| 46 | token, userData, userAbilities = user.get_token() | ||
| 47 | return {'accessToken': token, "userData": userData, "userAbilities": userAbilities} | ||
| 48 | else: | ||
| 49 | return jsonify({'error': 'User exist'}), 401 | ||
| 50 | |||
| 51 | |||
| 52 | @adm.route('/login', methods=["POST"]) | ||
| 53 | def login(): | ||
| 54 | params = request.json | ||
| 55 | user = k2users.authenticate(**params) | ||
| 56 | if user: | ||
| 57 | token, userData, userAbilities = user.get_token() | ||
| 58 | return {'accessToken': token, "userData": userData, "userAbilities": userAbilities} | ||
| 59 | else: | ||
| 60 | return jsonify({'error': 'Unauthorized'}), 401 | ||
| 61 | |||
| 62 | |||
| 63 | @adm.route('/logout', methods=["GET"]) | ||
| 64 | @jwt_required() | ||
| 65 | def logout(): | ||
| 66 | |||
| 67 | response = { | ||
| 68 | 'message': 'Logged out successfully' | ||
| 69 | } | ||
| 70 | |||
| 71 | return jsonify(response) | ||
| 72 | |||
| 73 | |||
| 74 | @adm.route('/newUser', methods=["GET", "POST"]) | ||
| 75 | @jwt_required() | ||
| 76 | def newUser(): | ||
| 77 | session = k2.extensions['sqlalchemy'].db.session | ||
| 78 | exist = k2users.user_by_login(request.json['login']) | ||
| 79 | if not exist: | ||
| 80 | res = k2users( | ||
| 81 | user_id=hashlib.md5(str(uuid.uuid4()).encode()).hexdigest(), | ||
| 82 | login=request.json['login'], | ||
| 83 | name=request.json['name'], | ||
| 84 | email=request.json['email'], | ||
| 85 | password=hashlib.md5(request.json['password'].encode()).hexdigest(), | ||
| 86 | phone=request.json['phone']) | ||
| 87 | if res: | ||
| 88 | session.add(res) | ||
| 89 | session.commit() | ||
| 90 | return jsonify({'status': 'ok'}) | ||
| 91 | else: | ||
| 92 | return jsonify({'error': 'Such user exist'}), 404 | ||
| 93 | |||
| 94 | |||
| 95 | @adm.route('/changePassword', methods=["POST"]) | ||
| 96 | @jwt_required() | ||
| 97 | def changePassword(): | ||
| 98 | session = k2.extensions['sqlalchemy'].db.session | ||
| 99 | current_user = get_jwt_identity() | ||
| 100 | user = session.query(k2users).filter_by(user_id=current_user).first() | ||
| 101 | if user.password == hashlib.md5(request.json['old_password'].encode()).hexdigest(): | ||
| 102 | if request.json['new_password'] == request.json['re_new_password']: | ||
| 103 | user.password = hashlib.md5(request.json['new_password'].encode()).hexdigest() | ||
| 104 | session.commit() | ||
| 105 | else: | ||
| 106 | return jsonify({'error': 'Пароль не найден в базе'}), 404 | ||
| 107 | else: | ||
| 108 | return jsonify({'error': 'Пароль не совпвдает'}), 404 | ||
| 109 | return jsonify({'status': 'ok'}) | ||
| 110 | |||
| 111 | |||
| 112 | @adm.route('/menu-admin-items') | ||
| 113 | def menu_items(): | ||
| 114 | menu = [ | ||
| 115 | { | ||
| 116 | "title": 'Site administration', | ||
| 117 | "icon": {"icon": 'mdi-account-circle-outline'}, | ||
| 118 | "children": [ | ||
| 119 | {'title': 'Password change', 'to': 'adm-changePassword'}, | ||
| 120 | {'title': 'New user', 'to': 'adm-newUser'}, | ||
| 121 | {'title': 'Users', 'to': 'adm-users'}, | ||
| 122 | {'title': 'Users are clients', 'to': 'adm-usersclients'}, | ||
| 123 | {'title': 'Roles', 'to': 'adm-roles'}, | ||
| 124 | {'title': 'Access to the menu', 'to': 'adm-menuaaccess'}, | ||
| 125 | ], | ||
| 126 | }] | ||
| 127 | |||
| 128 | return menu |
components/adm/requirements.txt
| 1 | alembic==1.11.1 | File was deleted | |
| 2 | Babel==2.12.1 | ||
| 3 | bcrypt==4.0.1 | ||
| 4 | bidict==0.22.1 | ||
| 5 | blinker==1.6.2 | ||
| 6 | certifi==2023.5.7 | ||
| 7 | charset-normalizer==3.1.0 | ||
| 8 | click==8.1.3 | ||
| 9 | colorama==0.4.6 | ||
| 10 | dnspython==2.3.0 | ||
| 11 | email-validator==2.0.0.post2 | ||
| 12 | Flask==2.3.2 | ||
| 13 | flask-babel==3.1.0 | ||
| 14 | Flask-Bcrypt==1.0.1 | ||
| 15 | Flask-Cors==3.0.10 | ||
| 16 | Flask-JWT-Extended==4.5.2 | ||
| 17 | Flask-Login==0.6.2 | ||
| 18 | Flask-Migrate==4.0.4 | ||
| 19 | Flask-MySQLdb==1.0.1 | ||
| 20 | Flask-SQLAlchemy==3.0.3 | ||
| 21 | flask-staticdirs==1.0.1 | ||
| 22 | Flask-WTF==1.1.1 | ||
| 23 | greenlet==2.0.2 | ||
| 24 | idna==3.4 | ||
| 25 | itsdangerous==2.1.2 | ||
| 26 | Jinja2==3.1.2 | ||
| 27 | jsonify==0.5 | ||
| 28 | Mako==1.2.4 | ||
| 29 | MarkupSafe==2.1.2 | ||
| 30 | mysql==0.0.3 | ||
| 31 | mysql-connector==2.2.9 | ||
| 32 | mysql-connector-python==8.0.33 | ||
| 33 | mysqlclient==2.1.1 | ||
| 34 | peppercorn==0.6 | ||
| 35 | protobuf==3.20.3 | ||
| 36 | PyJWT==2.7.0 | ||
| 37 | python-engineio==4.4.1 | ||
| 38 | python-socketio==5.8.0 | ||
| 39 | pytz==2023.3 | ||
| 40 | PyYAML==6.0 | ||
| 41 | requests==2.31.0 | ||
| 42 | six==1.16.0 | ||
| 43 | SQLAlchemy==2.0.15 | ||
| 44 | typing_extensions==4.6.2 | ||
| 45 | urllib3==2.0.2 | ||
| 46 | Werkzeug==2.3.4 | ||
| 47 | WTForms==3.0.1 |
components/adm/setup.py
| 1 | from setuptools import setup | File was deleted | |
| 2 | |||
| 3 | setup( | ||
| 4 | name='adm', | ||
| 5 | version='1.0.0', | ||
| 6 | description='Description of my project', | ||
| 7 | author='Your Name', | ||
| 8 | author_email='yourname@example.com', | ||
| 9 | keywords="adm, k2", | ||
| 10 | python_requires=">=3.7, <=3.11.2", | ||
| 11 | packages=['adm'], | ||
| 12 | package_data={ # Optional | ||
| 13 | }, | ||
| 14 | install_requires=[""], | ||
| 15 | ) |
components/k2test/__pycache__/__init__.cpython-310.pyc
No preview for this file type
components/k2test/k2test/__pycache__/__init__.cpython-310.pyc
No preview for this file type
components/k2test/k2test/__pycache__/views.cpython-310.pyc
No preview for this file type
components/k2test/k2test/views.py
| 1 | from flask import render_template, redirect, request, jsonify | 1 | from flask import render_template, redirect, request, jsonify |
| 2 | from flask_babel import gettext | 2 | from flask_babel import gettext |
| 3 | from flask_login import login_user, current_user, logout_user, login_required | 3 | from flask_login import login_user, current_user, logout_user, login_required |
| 4 | from flask import current_app as k2 | 4 | from flask import current_app as k2 |
| 5 | from flask import Blueprint, json | 5 | from flask import Blueprint, json |
| 6 | from flask_sqlalchemy import SQLAlchemy | 6 | from flask_sqlalchemy import SQLAlchemy |
| 7 | 7 | ||
| 8 | 8 | ||
| 9 | #bliueprint | 9 | #bliueprint |
| 10 | k2test = Blueprint('k2test', __name__, template_folder='templates', static_folder='static') | 10 | k2test = Blueprint('k2test', __name__, template_folder='templates', static_folder='static') |
| 11 | 11 | ||
| 12 | #component routes | 12 | #component routes |
| 13 | @k2test.route('/new') | 13 | @k2test.route('/new') |
| 14 | def new_component(): | 14 | def new_component(): |
| 15 | db = k2.extensions['sqlalchemy'].db | 15 | db = k2.extensions['sqlalchemy'].db |
| 16 | connection = db.engine.connect() | 16 | connection = db.engine.connect() |
| 17 | query = db.text("SELECT email, login FROM k2users") | 17 | query = db.text("SELECT email, login FROM k2users") |
| 18 | result = connection.execute(query).fetchall() | 18 | result = connection.execute(query).fetchall() |
| 19 | rows = [dict(email=row.email, login=row.login) for row in result] | 19 | rows = [dict(email=row.email, login=row.login) for row in result] |
| 20 | # Перетворення результату на JSON | 20 | # Перетворення результату на JSON |
| 21 | json_result = json.dumps(rows) | 21 | json_result = json.dumps(rows) |
| 22 | return json_result | 22 | return json_result |
| 23 | 23 | ||
| 24 | @k2test.route('/new2') | 24 | @k2test.route('/new2') |
| 25 | def new_component2(): | 25 | def new_component2(): |
| 26 | return render_template('new2.html') | 26 | return render_template('new2.html') |
| 27 | 27 | ||
| 28 | @k2test.route('/new3') | 28 | @k2test.route('/new3') |
| 29 | def new_component3(): | 29 | def new_component3(): |
| 30 | return jsonify({'data': 'page new3'}) | 30 | return jsonify({'data': 'page new3'}) |
| 31 | 31 | ||
| 32 | @k2test.route('/new4') | 32 | @k2test.route('/new4') |
| 33 | def new_component4(): | 33 | def new_component4(): |
| 34 | return jsonify({'data': 'page new4'}) | 34 | return jsonify({'data': 'page new4'}) |
| 35 | 35 | ||
| 36 | # menu items for admin | 36 | # menu items for admin |
| 37 | @k2test.route('/menu-admin-items') | 37 | @k2test.route('/menu-admin-items') |
| 38 | def menu_items(): | 38 | def menu_items(): |
| 39 | data = [ | 39 | data = [ |
| 40 | { | 40 | { |
| 41 | 'title': f"{gettext('title_menu_items')}", | 41 | 'title': f"{gettext('title_menu_items')}", |
| 42 | 'icon': {'icon': 'mdi-chart-timeline-variant'}, | 42 | 'icon': {'icon': 'mdi-chart-timeline-variant'}, |
| 43 | 'children': [ | 43 | 'children': [ |
| 44 | {'title': 'Тест 3', 'to': 'k2test-new3'}, | 44 | {'title': 'Test 3', 'to': 'k2test-new3'}, |
| 45 | {'title': 'Тест 3', 'to': 'k2test-new4'}, | 45 | {'title': 'Test 4', 'to': 'k2test-new4'}, |
| 46 | {'title': 'Test 5', 'to': 'k2test-new5'}, | ||
| 47 | {'title': 'Test 6', 'to': 'k2test-new6'}, | ||
| 48 | {'title': 'Test 7', 'to': 'k2test-new7'} | ||
| 46 | ], | 49 | ], |
| 47 | } | 50 | } |
| 48 | 51 | ||
| 49 | ] | 52 | ] |
| 50 | return data | 53 | return data |
| 51 | 54 | ||
| 52 | 55 |
db/database.db
No preview for this file type
k2/__pycache__/__init__.cpython-310.pyc
No preview for this file type
k2/__pycache__/k2admmenu.cpython-310.pyc
No preview for this file type
k2/__pycache__/k2cfg.cpython-310.pyc
No preview for this file type
k2/__pycache__/k2comp.cpython-310.pyc
No preview for this file type
k2/__pycache__/k2obj.cpython-310.pyc
No preview for this file type
k2/__pycache__/k2rout.cpython-310.pyc
No preview for this file type
k2/k2admmenu.py
| File was created | 1 | import hashlib | |
| 2 | import uuid | ||
| 3 | from .k2cfg import k2 | ||
| 4 | |||
| 5 | db = k2.db | ||
| 6 | |||
| 7 | class K2admin_menus(db.Model): | ||
| 8 | __tablename__ = 'k2admin_menus' | ||
| 9 | menuid = db.Column(db.String(75), primary_key=True) | ||
| 10 | namemenu = db.Column(db.String(150), index=True) | ||
| 11 | prevmenu = db.Column(db.String(150), index=True) | ||
| 12 | ccount = db.Column(db.Integer) | ||
| 13 | scriptrun = db.Column(db.Text) | ||
| 14 | prevmenu_text = db.Column(db.String(150)) | ||
| 15 | module_name = db.Column(db.String(150), index=True) | ||
| 16 | magazinsid = db.Column(db.String(75), index=True) | ||
| 17 | active = db.Column(db.Integer, index=True) | ||
| 18 | createuser = db.Column(db.String(75), index=True) | ||
| 19 | createdate = db.Column(db.DateTime, index=True) | ||
| 20 | updateuser = db.Column(db.String(75), index=True) | ||
| 21 | updatedate = db.Column(db.DateTime, index=True) | ||
| 22 | order_ins = db.Column(db.String(150), index=True) | ||
| 23 | caption = db.Column(db.String(1024)) | ||
| 24 | url = db.Column(db.String(2048)) | ||
| 25 | |||
| 26 | def __init__(self, **kwargs): | ||
| 27 | self.menuid = hashlib.md5(str(uuid.uuid4()).encode()).hexdigest() | ||
| 28 | super(K2admin_menus, self).__init__(**kwargs) | ||
| 29 | def __repr__(self): | ||
| 30 | return f"{self.namemenu}')" | ||
| 31 | |||
| 32 | |||
| 33 | |||
| 34 | class K2admin_Menus_Prava(db.Model): | ||
| 35 | __tablename__ = 'k2admin_menus_prava' | ||
| 36 | pravrepid = db.Column(db.String(75), primary_key=True) | ||
| 37 | menuid = db.Column(db.String(75), db.ForeignKey('k2admin_menus.menuid')) | ||
| 38 | username = db.Column(db.String(150)) | ||
| 39 | r = db.Column(db.Integer) | ||
| 40 | w = db.Column(db.Integer) | ||
| 41 | i = db.Column(db.Integer) | ||
| 42 | d = db.Column(db.Integer) | ||
| 43 | c = db.Column(db.Integer) | ||
| 44 | exp = db.Column(db.Integer) | ||
| 45 | imp = db.Column(db.Integer) | ||
| 46 | settable = db.Column(db.Integer) | ||
| 47 | cutpast = db.Column(db.Integer) | ||
| 48 | enable = db.Column(db.Integer) | ||
| 49 | magazinsid = db.Column(db.String(75)) | ||
| 50 | active = db.Column(db.Integer) | ||
| 51 | createuser = db.Column(db.String(75)) | ||
| 52 | createdate = db.Column(db.DateTime) | ||
| 53 | updateuser = db.Column(db.String(75)) | ||
| 54 | updatedate = db.Column(db.DateTime) | ||
| 55 | order_ins = db.Column(db.Integer) | ||
| 56 | roleid = db.Column(db.String(150)) | ||
| 57 | |||
| 58 | menu = db.relationship('K2admin_menus', backref='prava') | ||
| 59 | |||
| 60 | def __init__(self, **kwargs): | ||
| 61 | self.pravrepid = hashlib.md5(str(uuid.uuid4()).encode()).hexdigest() | ||
| 62 | super(K2admin_Menus_Prava, self).__init__(**kwargs) |
k2/k2rout.py
| 1 | import zipfile | 1 | import zipfile |
| 2 | from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, jsonify | 2 | from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, jsonify |
| 3 | import os | 3 | import os |
| 4 | import shutil | 4 | import shutil |
| 5 | from flask import request | 5 | from flask import request |
| 6 | from .k2cfg import k2 | 6 | from .k2cfg import k2 |
| 7 | from .k2comp import Component | 7 | from .k2comp import Component |
| 8 | from flask_migrate import Migrate | 8 | from flask_migrate import Migrate |
| 9 | import requests | 9 | import requests |
| 10 | import subprocess | 10 | import subprocess |
| 11 | from flask import current_app | 11 | from flask import current_app |
| 12 | import yaml | 12 | import yaml |
| 13 | from functools import wraps | 13 | from functools import wraps |
| 14 | import os | 14 | import os |
| 15 | import sys | 15 | import sys |
| 16 | from .k2admmenu import K2admin_menus, K2admin_Menus_Prava | ||
| 17 | from sqlalchemy import text | ||
| 16 | 18 | ||
| 19 | |||
| 20 | |||
| 21 | |||
| 17 | # initialize db | 22 | # initialize db |
| 18 | # migrate = Migrate(app, db) | 23 | # migrate = Migrate(app, db) |
| 19 | 24 | ||
| 20 | components_bp = Blueprint('components', __name__, template_folder='templates') | 25 | components_bp = Blueprint('components', __name__, template_folder='templates') |
| 21 | config = yaml.safe_load(open("db/first-login.yml")) | 26 | config = yaml.safe_load(open("db/first-login.yml")) |
| 22 | 27 | ||
| 23 | db = k2.db | 28 | db = k2.db |
| 24 | 29 | ||
| 25 | 30 | ||
| 26 | def first_login_required(view_func): | 31 | def first_login_required(view_func): |
| 27 | @wraps(view_func) | 32 | @wraps(view_func) |
| 28 | def decorated_view(*args, **kwargs): | 33 | def decorated_view(*args, **kwargs): |
| 29 | if 'username' not in session: | 34 | if 'username' not in session: |
| 30 | return redirect(url_for('components.first_login')) | 35 | return redirect(url_for('components.first_login')) |
| 31 | return view_func(*args, **kwargs) | 36 | return view_func(*args, **kwargs) |
| 32 | 37 | ||
| 33 | return decorated_view | 38 | return decorated_view |
| 34 | 39 | ||
| 35 | |||
| 36 | # def append_to_yaml_file(file_path, data): | 40 | # def append_to_yaml_file(file_path, data): |
| 37 | # with open(file_path, 'r') as f: | 41 | # with open(file_path, 'r') as f: |
| 38 | # existing_data = yaml.safe_load(f) or [] | 42 | # existing_data = yaml.safe_load(f) or [] |
| 39 | # | 43 | # |
| 40 | # if not existing_data: | 44 | # if not existing_data: |
| 41 | # start_id = 1 | 45 | # start_id = 1 |
| 42 | # else: | 46 | # else: |
| 43 | # start_id = max(item.get('id', 0) for item in existing_data) + 1 | 47 | # start_id = max(item.get('id', 0) for item in existing_data) + 1 |
| 44 | # | 48 | # |
| 45 | # for i, item in enumerate(data, start=start_id): | 49 | # for i, item in enumerate(data, start=start_id): |
| 46 | # item['id'] = i | 50 | # item['id'] = i |
| 47 | # existing_data.append(item) | 51 | # existing_data.append(item) |
| 48 | # | 52 | # |
| 49 | # with open(file_path, 'w') as f: | 53 | # with open(file_path, 'w') as f: |
| 50 | # yaml.dump(existing_data, f, default_flow_style=False) | 54 | # yaml.dump(existing_data, f, default_flow_style=False) |
| 51 | 55 | ||
| 52 | |||
| 53 | def remove_from_yaml_file(file_path, component_name): | 56 | def remove_from_yaml_file(file_path, component_name): |
| 54 | with open(file_path, 'r') as f: | 57 | with open(file_path, 'r') as f: |
| 55 | existing_data = yaml.safe_load(f) or [] | 58 | existing_data = yaml.safe_load(f) or [] |
| 56 | 59 | ||
| 57 | updated_data = [item for item in existing_data if item.get('component_name') != component_name] | 60 | updated_data = [item for item in existing_data if item.get('component_name') != component_name] |
| 58 | 61 | ||
| 59 | with open(file_path, 'w') as f: | 62 | with open(file_path, 'w') as f: |
| 60 | yaml.dump(updated_data, f, default_flow_style=False) | 63 | yaml.dump(updated_data, f, default_flow_style=False) |
| 61 | 64 | ||
| 62 | 65 | ||
| 63 | @components_bp.route('/api/languages', methods=['GET']) | 66 | @components_bp.route('/api/languages', methods=['GET']) |
| 64 | def find_language(): | 67 | def find_language(): |
| 65 | components = Component.query.all() | 68 | components = Component.query.all() |
| 66 | languages_paths = [] | 69 | languages_paths = [] |
| 67 | # Додаємо головну директорію languages | 70 | # Додаємо головну директорію languages |
| 68 | languages_paths.append('languages') | 71 | languages_paths.append('languages') |
| 69 | # Знаходимо шляхи до директорій languages всередині папки components | 72 | # Знаходимо шляхи до директорій languages всередині папки components |
| 70 | for component in components: | 73 | for component in components: |
| 71 | component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages' | 74 | component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages' |
| 72 | languages_paths.append(component_languages_directory) | 75 | languages_paths.append(component_languages_directory) |
| 73 | result = ';'.join(languages_paths) | 76 | result = ';'.join(languages_paths) |
| 74 | print(result) | 77 | print(result) |
| 75 | return result | 78 | return result |
| 76 | 79 | ||
| 77 | 80 | ||
| 78 | @components_bp.route('/home', methods=['GET', 'POST']) | 81 | @components_bp.route('/home', methods=['GET', 'POST']) |
| 79 | @first_login_required | 82 | @first_login_required |
| 80 | def home(): | 83 | def home(): |
| 81 | return redirect('/dashboard') | 84 | return redirect('/dashboard') |
| 82 | 85 | ||
| 83 | 86 | ||
| 84 | @components_bp.route('/first-login', methods=['GET', 'POST']) | 87 | @components_bp.route('/first-login', methods=['GET', 'POST']) |
| 85 | def first_login(): | 88 | def first_login(): |
| 86 | if request.method == "POST": | 89 | if request.method == "POST": |
| 87 | username = request.form.get("username") | 90 | username = request.form.get("username") |
| 88 | password = request.form.get("password") | 91 | password = request.form.get("password") |
| 89 | for user in config["users"]: | 92 | for user in config["users"]: |
| 90 | if user["username"] == username and user["password"] == password: | 93 | if user["username"] == username and user["password"] == password: |
| 91 | session['username'] = username # Збереження ім'я користувача в сесії | 94 | session['username'] = username # Збереження ім'я користувача в сесії |
| 92 | return redirect(url_for('components.dashboard')) | 95 | return redirect(url_for('components.dashboard')) |
| 93 | return "Невірне ім'я користувача або пароль." | 96 | return "Невірне ім'я користувача або пароль." |
| 94 | return render_template('first-login.html') | 97 | return render_template('first-login.html') |
| 95 | 98 | ||
| 96 | 99 | ||
| 97 | @components_bp.route('/change_language/<lang>') | 100 | @components_bp.route('/change_language/<lang>') |
| 98 | def change_language(lang): | 101 | def change_language(lang): |
| 99 | session['lang'] = lang | 102 | session['lang'] = lang |
| 100 | k2.current_language = lang | 103 | k2.current_language = lang |
| 101 | return redirect(url_for('components.dashboard')) | 104 | return redirect(url_for('components.dashboard')) |
| 102 | 105 | ||
| 103 | 106 | ||
| 104 | @components_bp.route('/dashboard') | 107 | @components_bp.route('/dashboard') |
| 105 | @first_login_required | 108 | @first_login_required |
| 106 | def dashboard(): | 109 | def dashboard(): |
| 107 | # Компоненти доступні для встановлення | 110 | # Компоненти доступні для встановлення |
| 108 | try: | ||
| 109 | # GET-запит до API | 111 | # GET-запит до API |
| 112 | try: | ||
| 110 | response = requests.get(f'{k2.update_domain}api/components') | 113 | response = requests.get(f'{k2.update_domain}api/components') |
| 111 | json_data = response.json() | 114 | json_data = response.json() |
| 112 | # Перетворення JSON-об'єкту на масив | 115 | # Перетворення JSON-об'єкту на масив |
| 113 | component_server = [item for item in json_data] | 116 | component_server = [item for item in json_data] |
| 114 | except: | 117 | except: |
| 115 | component_server = None | 118 | component_server = None |
| 116 | 119 | ||
| 117 | # Встановлені компоненти | 120 | # Встановлені компоненти |
| 118 | components = Component.query.all() | 121 | components = Component.query.all() |
| 119 | components_names = [component.name for component in components] | 122 | components_names = [component.name for component in components] |
| 120 | # Отримання значення пошукового запиту з параметрів URL | 123 | # Отримання значення пошукового запиту з параметрів URL |
| 121 | search_query = request.args.get('search_query') | 124 | search_query = request.args.get('search_query') |
| 122 | # print(search_query) | 125 | # print(search_query) |
| 123 | filtered_components = [] | 126 | filtered_components = [] |
| 124 | if search_query: | 127 | if search_query: |
| 125 | filtered_components = [component for component in component_server if | 128 | filtered_components = [component for component in component_server if |
| 126 | (search_query.lower() in component['name'].lower() if component['name'] else False) or | 129 | (search_query.lower() in component['name'].lower() if component['name'] else False) or |
| 127 | (search_query.lower() in component['description'].lower() if component[ | 130 | (search_query.lower() in component['description'].lower() if component[ |
| 128 | 'description'] else False)] | 131 | 'description'] else False)] |
| 129 | else: | 132 | else: |
| 130 | filtered_components = component_server | 133 | filtered_components = component_server |
| 131 | current_language = k2.current_language | 134 | current_language = k2.current_language |
| 132 | 135 | ||
| 133 | return render_template('dashboard.html', components=components, | 136 | return render_template('dashboard.html', components=components, |
| 134 | components_names=components_names, component_server=filtered_components, | 137 | components_names=components_names, component_server=filtered_components, |
| 135 | search_query=search_query, language=k2.menu) | 138 | search_query=search_query, language=k2.menu) |
| 136 | 139 | ||
| 137 | 140 | ||
| 138 | @components_bp.route('/show_components/<string:component_id>') | 141 | @components_bp.route('/show_components/<string:component_id>') |
| 139 | def show_components(component_id): | 142 | def show_components(component_id): |
| 140 | response = requests.get(f'{k2.update_domain}api/components') | 143 | response = requests.get(f'{k2.update_domain}api/components') |
| 141 | json_data = response.json() | 144 | json_data = response.json() |
| 142 | selected_component = next((component for component in json_data if component['id'] == component_id), None) | 145 | selected_component = next((component for component in json_data if component['id'] == component_id), None) |
| 143 | return render_template('component-info.html', selected_component=selected_component) | 146 | return render_template('component-info.html', selected_component=selected_component) |
| 144 | 147 | ||
| 145 | 148 | ||
| 146 | @components_bp.route('/install_components_git/<string:component_id>') | 149 | @components_bp.route('/install_components_git/<string:component_id>') |
| 147 | def install_components_git(component_id): | 150 | def install_components_git(component_id): |
| 148 | # Шлях до головної папки проекту | 151 | # Шлях до головної папки проекту |
| 149 | project_folder = 'components' | 152 | project_folder = 'components' |
| 150 | # component = Component.get_repository_by_id(component_id) | 153 | # component = Component.get_repository_by_id(component_id) |
| 151 | response = requests.get(f'{k2.update_domain}api/components') | 154 | response = requests.get(f'{k2.update_domain}api/components') |
| 152 | json_data = response.json() | 155 | json_data = response.json() |
| 153 | selected_component = next((component for component in json_data if component['id'] == component_id), None) | 156 | selected_component = next((component for component in json_data if component['id'] == component_id), None) |
| 154 | # Назва репозиторія | 157 | # Назва репозиторія |
| 155 | repository_name = selected_component['name'] | 158 | repository_name = selected_component['name'] |
| 156 | # Шлях до папки репозиторія в межах проекту | 159 | # Шлях до папки репозиторія в межах проекту |
| 157 | repository_folder = os.path.join(project_folder, repository_name) | 160 | repository_folder = os.path.join(project_folder, repository_name) |
| 158 | # URL репозиторія | 161 | # URL репозиторія |
| 159 | 162 | ||
| 160 | git_repo_url = selected_component['git_link'] | 163 | git_repo_url = selected_component['git_link'] |
| 161 | try: | 164 | try: |
| 162 | # Перевірка наявності папки репозиторія | 165 | # Перевірка наявності папки репозиторія |
| 163 | if not os.path.exists(repository_folder): | 166 | if not os.path.exists(repository_folder): |
| 164 | # Створення папки репозиторія | 167 | # Створення папки репозиторія |
| 165 | os.makedirs(repository_folder) | 168 | os.makedirs(repository_folder) |
| 166 | # Шлях до файлу __init__.py | 169 | # Шлях до файлу __init__.py |
| 167 | init_file = os.path.join(repository_folder, '__init__.py') | 170 | init_file = os.path.join(repository_folder, '__init__.py') |
| 168 | # Перевірка наявності файлу __init__.py | 171 | # Перевірка наявності файлу __init__.py |
| 169 | if not os.path.exists(init_file): | 172 | if not os.path.exists(init_file): |
| 170 | # Створення пустого файлу __init__.py | 173 | # Створення пустого файлу __init__.py |
| 171 | open(init_file, 'a').close() | 174 | open(init_file, 'a').close() |
| 172 | # підключення до приватного репозиторію | 175 | # підключення до приватного репозиторію |
| 173 | # os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW' | 176 | # os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW' |
| 174 | # git_repo_url_with_token = git_repo_url.replace('https://', | 177 | # git_repo_url_with_token = git_repo_url.replace('https://', |
| 175 | # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@') | 178 | # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@') |
| 176 | 179 | ||
| 177 | # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія | 180 | # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія |
| 178 | command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, | 181 | command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, |
| 179 | '--target=' + repository_folder] | 182 | '--target=' + repository_folder] |
| 180 | # Виконуємо команду встановлення | 183 | # Виконуємо команду встановлення |
| 181 | subprocess.check_call(command) | 184 | subprocess.check_call(command) |
| 182 | 185 | ||
| 183 | # Шлях до файлу, до якого потрібно додати код | 186 | # Шлях до файлу, до якого потрібно додати код |
| 184 | file_path = 'routes.py' | 187 | file_path = 'routes.py' |
| 185 | # Код, який потрібно додати | 188 | # Код, який потрібно додати |
| 186 | code = selected_component['dependencies'] | 189 | code = selected_component['dependencies'] |
| 187 | # Відкриття файлу у режимі дозапису | 190 | # Відкриття файлу у режимі дозапису |
| 188 | with open(file_path, 'a') as file: | 191 | with open(file_path, 'a') as file: |
| 189 | # Запис нового коду у файл | 192 | # Запис нового коду у файл |
| 190 | file.write('\n') | 193 | file.write('\n') |
| 191 | file.write(code) | 194 | file.write(code) |
| 192 | file.write('\n') | 195 | file.write('\n') |
| 193 | component = Component.query.filter_by(name=selected_component['name']).first() | 196 | component = Component.query.filter_by(name=selected_component['name']).first() |
| 194 | if not component: | 197 | if not component: |
| 195 | new_component = Component( | 198 | new_component = Component( |
| 196 | name=selected_component['name'], | 199 | name=selected_component['name'], |
| 197 | description=selected_component['description'], | 200 | description=selected_component['description'], |
| 198 | version=selected_component['version'], | 201 | version=selected_component['version'], |
| 199 | git_link=selected_component['git_link'], | 202 | git_link=selected_component['git_link'], |
| 200 | dependencies=selected_component['dependencies'], | 203 | dependencies=selected_component['dependencies'], |
| 201 | installed=True | 204 | installed=True |
| 202 | ) | 205 | ) |
| 203 | # Add the new component to the database | 206 | # Add the new component to the database |
| 204 | db.session.add(new_component) | 207 | db.session.add(new_component) |
| 205 | db.session.commit() | 208 | db.session.commit() |
| 206 | 209 | ||
| 207 | # Повертаємо повідомлення про успішне встановлення | 210 | # Повертаємо повідомлення про успішне встановлення |
| 208 | return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' | 211 | return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 209 | except subprocess.CalledProcessError as e: | 212 | except subprocess.CalledProcessError as e: |
| 210 | return 'Error installing : ' + str(e) | 213 | return 'Error installing : ' + str(e) |
| 211 | 214 | ||
| 212 | 215 | ||
| 213 | @components_bp.route('/install_components/<string:component_id>') | 216 | @components_bp.route('/install_components/<string:component_id>') |
| 214 | def install_component_from_archive(component_id): | 217 | def install_component_from_archive(component_id): |
| 215 | # Шлях до головної папки проекту | 218 | # Шлях до головної папки проекту |
| 216 | project_folder = 'components' | 219 | project_folder = 'components' |
| 217 | # Отримати відповідну компоненту зі списку компонент | 220 | # Отримати відповідну компоненту зі списку компонент |
| 218 | response = requests.get(f'{k2.update_domain}api/components') | 221 | response = requests.get(f'{k2.update_domain}api/components') |
| 219 | json_data = response.json() | 222 | json_data = response.json() |
| 220 | selected_component = next((component for component in json_data if component['id'] == component_id), None) | 223 | selected_component = next((component for component in json_data if component['id'] == component_id), None) |
| 221 | if selected_component is None: | 224 | if selected_component is None: |
| 222 | return 'Component not found' | 225 | return 'Component not found' |
| 223 | # Отримати посилання на архів компоненти та версію | 226 | # Отримати посилання на архів компоненти та версію |
| 224 | archive_url = selected_component['latest_component_data'] | 227 | archive_url = selected_component['latest_component_data'] |
| 225 | version = selected_component['latest_version'] | 228 | version = selected_component['latest_version'] |
| 226 | try: | 229 | try: |
| 227 | # Створити шлях до папки компоненти згідно назви та версії | 230 | # Створити шлях до папки компоненти згідно назви та версії |
| 228 | component_folder = os.path.join(project_folder) | 231 | component_folder = os.path.join(project_folder) |
| 229 | os.makedirs(component_folder, exist_ok=True) | 232 | os.makedirs(component_folder, exist_ok=True) |
| 230 | # Завантажити архів компоненти | 233 | # Завантажити архів компоненти |
| 231 | response = requests.get(archive_url, stream=True) | 234 | response = requests.get(archive_url, stream=True) |
| 232 | response.raise_for_status() | 235 | response.raise_for_status() |
| 233 | # Шлях до завантаженого архіву | 236 | # Шлях до завантаженого архіву |
| 234 | archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip") | 237 | archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip") |
| 235 | # Зберегти архів на диск | 238 | # Зберегти архів на диск |
| 236 | with open(archive_path, "wb") as file: | 239 | with open(archive_path, "wb") as file: |
| 237 | for chunk in response.iter_content(chunk_size=8192): | 240 | for chunk in response.iter_content(chunk_size=8192): |
| 238 | file.write(chunk) | 241 | file.write(chunk) |
| 239 | # Розпакувати архів | 242 | # Розпакувати архів |
| 240 | with zipfile.ZipFile(archive_path, "r") as zip_ref: | 243 | with zipfile.ZipFile(archive_path, "r") as zip_ref: |
| 241 | zip_ref.extractall(component_folder) | 244 | zip_ref.extractall(component_folder) |
| 242 | # Видалити архів | 245 | # Видалити архів |
| 243 | os.remove(archive_path) | 246 | os.remove(archive_path) |
| 244 | #перейменувати якщо git | 247 | #перейменувати якщо git |
| 245 | component_name = selected_component['name'] | 248 | component_name = selected_component['name'] |
| 246 | old_folder_path = os.path.join(component_folder, component_name + ".git") | 249 | old_folder_path = os.path.join(component_folder, component_name + ".git") |
| 247 | new_folder_path = os.path.join(component_folder, component_name) | 250 | new_folder_path = os.path.join(component_folder, component_name) |
| 248 | # Перевірка наявності папки зі старою назвою | 251 | # Перевірка наявності папки зі старою назвою |
| 249 | if os.path.exists(old_folder_path) and os.path.isdir(old_folder_path): | 252 | if os.path.exists(old_folder_path) and os.path.isdir(old_folder_path): |
| 250 | # Перейменування папки зі старою назвою на нову назву | 253 | # Перейменування папки зі старою назвою на нову назву |
| 251 | os.rename(old_folder_path, new_folder_path) | 254 | os.rename(old_folder_path, new_folder_path) |
| 252 | 255 | ||
| 253 | # Шлях до файлу, до якого потрібно додати роути | 256 | # Шлях до файлу, до якого потрібно додати роути |
| 254 | file_path = 'routes.py' | 257 | file_path = 'routes.py' |
| 255 | # Код, який потрібно додати | 258 | # Код, який потрібно додати |
| 256 | code = f'''from components.{selected_component['name']}.{selected_component['name']}.views import {selected_component['name']}\napp.register_blueprint({selected_component['name']}, url_prefix='/{selected_component['name']}')''' | 259 | code = f'''from components.{selected_component['name']}.{selected_component['name']}.views import {selected_component['name']}\napp.register_blueprint({selected_component['name']}, url_prefix='/{selected_component['name']}')''' |
| 257 | # selected_component['dependencies'] | 260 | # selected_component['dependencies'] |
| 258 | 261 | ||
| 259 | # Відкриття файлу у режимі дозапису | 262 | # Відкриття файлу у режимі дозапису |
| 260 | with open(file_path, 'a') as file: | 263 | with open(file_path, 'a') as file: |
| 261 | # Запис нового коду у файл | 264 | # Запис нового коду у файл |
| 262 | file.write('\n') | 265 | file.write('\n') |
| 263 | file.write(code) | 266 | file.write(code) |
| 264 | file.write('\n') | 267 | file.write('\n') |
| 265 | 268 | ||
| 266 | # Update database with the installed component | 269 | # Update database with the installed component |
| 267 | component = Component.query.filter_by(name=selected_component['name']).first() | 270 | component = Component.query.filter_by(name=selected_component['name']).first() |
| 268 | if not component: | 271 | if not component: |
| 269 | component = Component( | 272 | component = Component( |
| 270 | name=selected_component['name'], | 273 | name=selected_component['name'], |
| 271 | description=selected_component['description'], | 274 | description=selected_component['description'], |
| 272 | version=version, | 275 | version=version, |
| 273 | git_link=selected_component['git_link'], | 276 | git_link=selected_component['git_link'], |
| 274 | dependencies=code, | 277 | dependencies=code, |
| 275 | installed=True | 278 | installed=True |
| 276 | ) | 279 | ) |
| 277 | db.session.add(component) | 280 | db.session.add(component) |
| 278 | else: | 281 | else: |
| 279 | component.version = version | 282 | component.version = version |
| 280 | component.git_link = selected_component['git_link'] | 283 | component.git_link = selected_component['git_link'] |
| 281 | component.dependencies = code | 284 | component.dependencies = code |
| 282 | component.installed = True | 285 | component.installed = True |
| 283 | 286 | ||
| 284 | db.session.commit() | 287 | db.session.commit() |
| 285 | 288 | ||
| 286 | # add language folders | 289 | # add language folders |
| 290 | |||
| 287 | k2.search_babel_translation_directories() | 291 | k2.search_babel_translation_directories() |
| 288 | return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories}, | 292 | return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories}, |
| 289 | \n \n please wait installing requirments... | 293 | \n \n please wait installing requirments... |
| 290 | <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />''' | 294 | <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />''' |
| 291 | 295 | ||
| 292 | except Exception as e: | 296 | except Exception as e: |
| 293 | return f'Error installing component: {str(e)}' | 297 | return f'Error installing component: {str(e)}' |
| 294 | 298 | ||
| 295 | 299 | ||
| 296 | @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET']) | 300 | @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET']) |
| 297 | def install_requirments(selected_component_name): | 301 | def install_requirments(selected_component_name): |
| 298 | # menu items | 302 | # menu items |
| 299 | get_admin_menu() | 303 | get_admin_menu() |
| 300 | 304 | ||
| 305 | |||
| 301 | # install requirements | 306 | # install requirements |
| 302 | requirements_file = os.path.join('components', selected_component_name, "requirements.txt") | 307 | requirements_file = os.path.join('components', selected_component_name, "requirements.txt") |
| 303 | if os.path.isfile(requirements_file): | 308 | if os.path.isfile(requirements_file): |
| 304 | pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}" | 309 | pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}" |
| 305 | subprocess.run(pip_command, shell=True, check=True) | 310 | subprocess.run(pip_command, shell=True, check=True) |
| 306 | return f'''Requirements installed successfully | 311 | return f'''Requirements installed successfully |
| 307 | \n \n please wait installing requirments components... | 312 | \n \n please wait installing requirments components... |
| 308 | <meta http-equiv="refresh" content="1;url=/install-requirments-components" />''' | 313 | <meta http-equiv="refresh" content="1;url=/install-requirments-components" />''' |
| 309 | 314 | ||
| 310 | 315 | ||
| 311 | @components_bp.route('/install-requirments-components') | 316 | @components_bp.route('/install-requirments-components') |
| 312 | def install_requirements_components(): | 317 | def install_requirements_components(): |
| 313 | # Откриття файлу requirements_components.txt | 318 | # Откриття файлу requirements_components.txt |
| 314 | requirements_file = 'requirements_components.txt' | 319 | requirements_file = 'requirements_components.txt' |
| 315 | component_ids = None | 320 | component_ids = None |
| 316 | if os.path.isfile(requirements_file): | 321 | if os.path.isfile(requirements_file): |
| 317 | with open('requirements_components.txt', 'r') as file: | 322 | with open('requirements_components.txt', 'r') as file: |
| 318 | component_ids = file.read().splitlines() | 323 | component_ids = file.read().splitlines() |
| 319 | if component_ids: | 324 | if component_ids: |
| 320 | for component_id in component_ids: | 325 | for component_id in component_ids: |
| 321 | # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти | 326 | # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти |
| 322 | response = requests.get( | 327 | response = requests.get( |
| 323 | f'/install_components/{component_id}') | 328 | f'/install_components/{component_id}') |
| 324 | return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' | 329 | return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 325 | else: | 330 | else: |
| 326 | return f'<meta http-equiv="refresh" content="1;url=/dashboard" />' | 331 | return f'<meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 327 | # Опрацювання відповіді (за потреби) | 332 | # Опрацювання відповіді (за потреби) |
| 328 | 333 | ||
| 329 | 334 | ||
| 330 | @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET']) | 335 | @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET']) |
| 331 | def remove_dependencies(component_id): | 336 | def remove_dependencies(component_id): |
| 332 | # Знаходимо компоненту за її ID | 337 | # Знаходимо компоненту за її ID |
| 333 | component = Component.query.get(component_id) | 338 | component = Component.query.get(component_id) |
| 334 | if not component: | 339 | if not component: |
| 335 | return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' | 340 | return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 336 | # remove menu items | 341 | # remove menu items |
| 337 | component_name = component.name | 342 | component_name = component.name |
| 338 | # file_path = "components/menu.yml" | 343 | # file_path = "components/menu.yml" |
| 339 | # remove_from_yaml_file(file_path, component_name) | 344 | # remove_from_yaml_file(file_path, component_name) |
| 340 | requests.get(f"{k2.domain}api/add-to-menu") | 345 | requests.get(f"{k2.domain}api/add-to-menu") |
| 341 | # remove routes | 346 | # remove routes |
| 342 | file_path = 'routes.py' | 347 | file_path = 'routes.py' |
| 343 | with open(file_path, 'r') as file: | 348 | with open(file_path, 'r') as file: |
| 344 | lines = file.readlines() | 349 | lines = file.readlines() |
| 345 | 350 | ||
| 346 | updated_lines = [line for line in lines if line.strip() not in component.dependencies] | 351 | updated_lines = [line for line in lines if line.strip() not in component.dependencies] |
| 347 | with open(file_path, 'w') as file: | 352 | with open(file_path, 'w') as file: |
| 348 | file.writelines(updated_lines) | 353 | file.writelines(updated_lines) |
| 349 | 354 | ||
| 350 | component.installed = False | 355 | component.installed = False |
| 351 | db.session.commit() | 356 | db.session.commit() |
| 352 | 357 | ||
| 353 | return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />' | 358 | return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 354 | 359 | ||
| 355 | 360 | ||
| 356 | @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET']) | 361 | @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET']) |
| 357 | def add_dependencies(component_id): | 362 | def add_dependencies(component_id): |
| 358 | # Знаходимо компоненту за її ID | 363 | # Знаходимо компоненту за її ID |
| 359 | component = Component.query.get(component_id) | 364 | component = Component.query.get(component_id) |
| 360 | if not component: | 365 | if not component: |
| 361 | return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' | 366 | return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 362 | 367 | ||
| 363 | file_path = 'routes.py' | 368 | file_path = 'routes.py' |
| 364 | code = component.dependencies | 369 | code = component.dependencies |
| 365 | # Відкриття файлу у режимі дозапису | 370 | # Відкриття файлу у режимі дозапису |
| 366 | with open(file_path, 'a') as file: | 371 | with open(file_path, 'a') as file: |
| 367 | # Запис нового коду у файл | 372 | # Запис нового коду у файл |
| 368 | file.write(code) | 373 | file.write(code) |
| 369 | 374 | ||
| 370 | # Оновлюємо статус компоненти | 375 | # Оновлюємо статус компоненти |
| 371 | component.installed = True | 376 | component.installed = True |
| 372 | db.session.commit() | 377 | db.session.commit() |
| 373 | return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' | 378 | return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 374 | 379 | ||
| 375 | 380 | ||
| 376 | @components_bp.route('/remove-component/<string:component_id>') | 381 | @components_bp.route('/remove-component/<string:component_id>') |
| 377 | def remove_component(component_id): | 382 | def remove_component(component_id): |
| 378 | # Шлях до головної папки проекту | 383 | # Шлях до головної папки проекту |
| 379 | project_folder = 'components' | 384 | project_folder = 'components' |
| 380 | component = Component.query.get(component_id) | 385 | component = Component.query.get(component_id) |
| 381 | # Назва репозиторія | 386 | # Назва репозиторія |
| 382 | repository_name = component.name | 387 | repository_name = component.name |
| 383 | # Шлях до папки репозиторія в межах проекту | 388 | # Шлях до папки репозиторія в межах проекту |
| 384 | repository_folder = os.path.join(project_folder, repository_name) | 389 | repository_folder = os.path.join(project_folder, repository_name) |
| 385 | try: | 390 | try: |
| 386 | # Перевірка наявності папки репозиторія | 391 | # Перевірка наявності папки репозиторія |
| 387 | if os.path.exists(repository_folder): | 392 | if os.path.exists(repository_folder): |
| 388 | # Видалення папки репозиторія | 393 | # Видалення папки репозиторія |
| 389 | shutil.rmtree(repository_folder) | 394 | shutil.rmtree(repository_folder) |
| 390 | # Видаляємо компоненту з бази | 395 | # Видаляємо компоненту з бази |
| 391 | if component: | 396 | if component: |
| 392 | db.session.delete(component) | 397 | db.session.delete(component) |
| 393 | db.session.commit() | 398 | db.session.commit() |
| 394 | 399 | ||
| 395 | # Повертаємо повідомлення про успішне видалення | 400 | # Повертаємо повідомлення про успішне видалення |
| 396 | return 'Component removed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' | 401 | return 'Component removed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' |
| 397 | except Exception as e: | 402 | except Exception as e: |
| 398 | # Повертаємо повідомлення про помилку видалення | 403 | # Повертаємо повідомлення про помилку видалення |
| 399 | return 'Error removing component: ' + str(e) | 404 | return 'Error removing component: ' + str(e) |
| 400 | 405 | ||
| 401 | 406 | ||
| 402 | |||
| 403 | |||
| 404 | @components_bp.route('/component/add') | 407 | @components_bp.route('/component/add') |
| 405 | def component_add(): | 408 | def component_add(): |
| 406 | # components for install | 409 | # components for install |
| 407 | try: | 410 | try: |
| 408 | # GET-requests to API | 411 | # GET-requests to API |
| 409 | response = requests.get(f'{k2.update_domain}api/components') | 412 | response = requests.get(f'{k2.update_domain}api/components') |
| 410 | json_data = response.json() | 413 | json_data = response.json() |
| 411 | for item in json_data: | 414 | for item in json_data: |
| 412 | item['button'] = f"{k2.domain}/install_components/{item['id']}" | 415 | item['button'] = f"{k2.domain}/install_components/{item['id']}" |
| 413 | 416 | ||
| 414 | except: | 417 | except: |
| 415 | json_data = None | 418 | json_data = None |
| 416 | return jsonify(json_data) | 419 | return jsonify(json_data) |
| 417 | 420 | ||
| 418 | 421 | ||
| 419 | @components_bp.route('/component/list') | 422 | @components_bp.route('/component/list') |
| 420 | def component_list(): | 423 | def component_list(): |
| 421 | # Встановлені компоненти | 424 | # Встановлені компоненти |
| 422 | component_list = [] | 425 | component_list = [] |
| 423 | components = Component.query.all() | 426 | components = Component.query.all() |
| 424 | for component in components: | 427 | for component in components: |
| 425 | component_dict = {} | 428 | component_dict = {} |
| 426 | component_dict['name'] = component.name | 429 | component_dict['name'] = component.name |
| 427 | component_dict['id'] = component.id | 430 | component_dict['id'] = component.id |
| 428 | component_dict['description'] = component.description | 431 | component_dict['description'] = component.description |
| 429 | component_dict['version'] = component.version | 432 | component_dict['version'] = component.version |
| 430 | component_dict['button_off'] =f"{k2.domain}/remove_dependencies/{component.id}" | 433 | component_dict['button_off'] =f"{k2.domain}/remove_dependencies/{component.id}" |
| 431 | component_dict['button_on'] = f"{k2.domain}/add_dependencies/{component.id}" | 434 | component_dict['button_on'] = f"{k2.domain}/add_dependencies/{component.id}" |
| 432 | component_dict['button_del'] = f"{k2.domain}/remove-component/{component.id}" | 435 | component_dict['button_del'] = f"{k2.domain}/remove-component/{component.id}" |
| 433 | component_list.append(component_dict) | 436 | component_list.append(component_dict) |
| 434 | return jsonify(component_list) | 437 | return jsonify(component_list) |
| 435 | 438 | ||
| 439 | |||
| 436 | # menu | 440 | # menu |
| 437 | @components_bp.route('/api/add-to-menu', methods=['GET']) | 441 | @components_bp.route('/api/add-to-menu', methods=['GET']) |
| 438 | def add_to_menu(): | 442 | def add_to_menu(): |
| 439 | data = [] | 443 | data = [] |
| 440 | response = requests.get(f"{k2.domain}/menu-admin-items") | 444 | response = requests.get(f"{k2.domain}/menu-admin-items") |
| 441 | data.append(response.json()[0]) | 445 | data.append(response.json()[0]) |
| 446 | prev_menu = response.json()[0]['title'] | ||
| 447 | for item in response.json()[0]['children']: | ||
| 448 | name_menu = item['to'] | ||
| 449 | caption_menu = item['title'] | ||
| 450 | add_menu_with_permissions_db(name_menu, prev_menu, caption_menu) | ||
| 442 | components = Component.query.all() | 451 | components = Component.query.all() |
| 443 | components_names = [component.name for component in components] | 452 | components_names = [component.name for component in components] |
| 444 | for components_names in components_names: | 453 | for components_names in components_names: |
| 445 | response = requests.get(f"{k2.domain}{components_names}/menu-admin-items") | 454 | response = requests.get(f"{k2.domain}{components_names}/menu-admin-items") |
| 446 | print(response) | ||
| 447 | if response.status_code == 200: | 455 | if response.status_code == 200: |
| 448 | data.append(response.json()[0]) | 456 | data.append(response.json()[0]) |
| 457 | #prev_menu = | ||
| 458 | prev_menu = response.json()[0]['title'] | ||
| 459 | for item in response.json()[0]['children']: | ||
| 460 | name_menu = item['to'] | ||
| 461 | caption_menu = item['title'] | ||
| 462 | add_menu_with_permissions_db(name_menu, prev_menu, caption_menu) | ||
| 449 | else: | 463 | else: |
| 450 | data | 464 | data |
| 451 | # add component_name key for menu items | 465 | # add component_name key for menu items |
| 452 | for item in data: | 466 | for item in data: |
| 453 | item['component_name'] = components_names | 467 | item['component_name'] = components_names |
| 454 | k2.menu = data | 468 | k2.menu = data |
| 455 | return k2.menu | 469 | return k2.menu |
| 456 | 470 | ||
| 457 | 471 | ||
| 458 | @components_bp.route('/api/main-menu/') | 472 | @components_bp.route('/api/main-menu/') |
| 459 | def get_admin_menu(): | 473 | def get_admin_menu(): |
| 460 | requests.get(f"{k2.domain}api/add-to-menu") | 474 | requests.get(f"{k2.domain}api/add-to-menu") |
| 461 | return k2.menu | 475 | return k2.menu |
| 476 | |||
| 477 | |||
| 478 | def add_menu_with_permissions_db(name_menu, prev_menu, caption_menu): | ||
| 479 | |||
| 480 | # Створення об'єкта k2admin_menus | ||
| 481 | menu = text('SELECT COUNT(*) FROM k2admin_menus WHERE namemenu = :name_menu') | ||
| 482 | result = db.session.execute(menu, {'name_menu': name_menu}).fetchone() | ||
| 483 | count = result[0] | ||
| 484 | if count == 0: | ||
| 485 | new_menu_element = K2admin_menus( | ||
| 486 | namemenu=name_menu, | ||
| 487 | prevmenu=prev_menu, | ||
| 488 | caption=caption_menu, | ||
| 489 | module_name=name_menu | ||
| 490 | ) | ||
| 491 | # Додавання об'єкта k2admin_menus до сесії | ||
| 492 | db.session.add(new_menu_element) | ||
| 493 | db.session.commit() | ||
| 494 | # Створення об'єкта k2admin_menus_prava | ||
| 495 | new_prava = K2admin_Menus_Prava( | ||
| 496 | menuid=new_menu_element.menuid, # Зв'язуємо зовнішній ключ з menuid нового меню | ||
| 497 | username=None, | ||
| 498 | r=0, | ||
| 499 | w=0, | ||
| 500 | i=0, | ||
| 501 | d=0, | ||
| 502 | c=0, | ||
| 503 | exp=0, | ||
| 504 | imp=0, | ||
| 505 | settable=0, | ||
| 506 | cutpast=0, | ||
| 507 | enable=0, | ||
| 508 | roleid=1 | ||
| 509 | ) | ||
| 510 | # Додавання об'єкта k2admin_menus_prava до сесії | ||
| 511 | db.session.add(new_prava) | ||
| 512 | db.session.commit() | ||
| 462 | 513 | ||
| 463 | 514 | ||
| 464 | @components_bp.route('/menu-admin-items') | 515 | @components_bp.route('/menu-admin-items') |
| 465 | def menu_items(): | 516 | def menu_items(): |
| 466 | menu = [ | 517 | menu = [ |
| 467 | { | 518 | { |
| 468 | "title": 'Add components', | 519 | "title": 'Add components', |
| 469 | "icon": {"icon": 'mdi-account-circle-outline'}, | 520 | "icon": {"icon": 'mdi-account-circle-outline'}, |
| 470 | "children": [ | 521 | "children": [ |
| 471 | {'title': 'Install components', 'to': 'component-add'}, | 522 | {'title': 'Install components', 'to': 'component-add'}, |
| 472 | {'title': 'Installed components', 'to': 'component-list'}, | 523 | {'title': 'Installed components', 'to': 'component-list'}, |
| 473 | 524 | ||
| 474 | ], | 525 | ], |
| 475 | }] | 526 | }] |
| 476 | return menu | 527 | return menu |
| 477 | 528 | ||
| 478 | 529 |
languages/babel_translation_directories.yml
| 1 | babel_translation_directories: languages;components/k2test/k2test/languages;components/grid/grid/languages;components/adm/adm/languages | 1 | babel_translation_directories: languages;components/k2test/k2test/languages;components/grid/grid/languages;components/adm/adm/languages;components/k2auth/k2auth/languages |
| 2 | 2 |