Commit 9d7bba8b031c4f9e77d02f03d7291901ce66a3d1

Authored by Василь Свідрик
1 parent 70f939b38b
Exists in master

add_menu_with_permissions_db function

Showing 26 changed files with 131 additions and 333 deletions Side-by-side Diff

__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
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
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
components/adm/adm/views.py
1   -import hashlib
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
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
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
... ... @@ -41,8 +41,11 @@
41 41 'title': f"{gettext('title_menu_items')}",
42 42 'icon': {'icon': 'mdi-chart-timeline-variant'},
43 43 'children': [
44   - {'title': 'Тест 3', 'to': 'k2test-new3'},
45   - {'title': 'Тест 3', 'to': 'k2test-new4'},
  44 + {'title': 'Test 3', 'to': 'k2test-new3'},
  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  
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
  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)
... ... @@ -13,7 +13,12 @@
13 13 from functools import wraps
14 14 import os
15 15 import sys
  16 +from .k2admmenu import K2admin_menus, K2admin_Menus_Prava
  17 +from sqlalchemy import text
16 18  
  19 +
  20 +
  21 +
17 22 # initialize db
18 23 # migrate = Migrate(app, db)
19 24  
... ... @@ -32,7 +37,6 @@
32 37  
33 38 return decorated_view
34 39  
35   -
36 40 # def append_to_yaml_file(file_path, data):
37 41 # with open(file_path, 'r') as f:
38 42 # existing_data = yaml.safe_load(f) or []
... ... @@ -49,7 +53,6 @@
49 53 # with open(file_path, 'w') as f:
50 54 # yaml.dump(existing_data, f, default_flow_style=False)
51 55  
52   -
53 56 def remove_from_yaml_file(file_path, component_name):
54 57 with open(file_path, 'r') as f:
55 58 existing_data = yaml.safe_load(f) or []
56 59  
... ... @@ -105,8 +108,8 @@
105 108 @first_login_required
106 109 def dashboard():
107 110 # Компоненти доступні для встановлення
108   - try:
109 111 # GET-запит до API
  112 + try:
110 113 response = requests.get(f'{k2.update_domain}api/components')
111 114 json_data = response.json()
112 115 # Перетворення JSON-об'єкту на масив
... ... @@ -284,6 +287,7 @@
284 287 db.session.commit()
285 288  
286 289 # add language folders
  290 +
287 291 k2.search_babel_translation_directories()
288 292 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories},
289 293 \n \n please wait installing requirments...
... ... @@ -298,6 +302,7 @@
298 302 # menu items
299 303 get_admin_menu()
300 304  
  305 +
301 306 # install requirements
302 307 requirements_file = os.path.join('components', selected_component_name, "requirements.txt")
303 308 if os.path.isfile(requirements_file):
... ... @@ -399,8 +404,6 @@
399 404 return 'Error removing component: ' + str(e)
400 405  
401 406  
402   -
403   -
404 407 @components_bp.route('/component/add')
405 408 def component_add():
406 409 # components for install
407 410  
408 411  
409 412  
... ... @@ -433,19 +436,30 @@
433 436 component_list.append(component_dict)
434 437 return jsonify(component_list)
435 438  
  439 +
436 440 # menu
437 441 @components_bp.route('/api/add-to-menu', methods=['GET'])
438 442 def add_to_menu():
439 443 data = []
440 444 response = requests.get(f"{k2.domain}/menu-admin-items")
441 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 451 components = Component.query.all()
443 452 components_names = [component.name for component in components]
444 453 for components_names in components_names:
445 454 response = requests.get(f"{k2.domain}{components_names}/menu-admin-items")
446   - print(response)
447 455 if response.status_code == 200:
448 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 463 else:
450 464 data
451 465 # add component_name key for menu items
... ... @@ -459,6 +473,43 @@
459 473 def get_admin_menu():
460 474 requests.get(f"{k2.domain}api/add-to-menu")
461 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 515 @components_bp.route('/menu-admin-items')
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