-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructure_and_content.txt
2196 lines (1812 loc) · 80 KB
/
structure_and_content.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet
backend
|---app
|---config
|---db_config.py
|---controllers
|---auth_controller.py
|---category_controller.py
|---query_controller.py
|---snippet_controller.py
|---subcategory_controller.py
|---tag_controller.py
|---user_controller.py
|---database
|---init_db.py
|---models
|---category.py
|---models.py
|---notification.py
|---snippet.py
|---subcategory.py
|---tag.py
|---user.py
|---__init__.py
|---routes
|---routes.py
|---error_handlers.py
|---__init__.py
|---migrations
|---versions
|---55569e580c1b_manual_initial_migration.py
|---bf1e42552369_add_username_column_to_users_table.py
|---alembic.ini
|---env.py
|---README
|---script.py.mako
|---.gitignore
|---directory_structure.txt
|---Dockerfile
|---entrypoint.sh
|---list_directory_structure_to_file.ps1
|---migrate.py
|---package.json
|---README.md
|---requirements - Copy.txt
|---requirements.txt
|---server.py
|---swagger.yaml
.gitignore
directory_structure.txt
docker-compose - Copy.yml
docker-compose.yml
LICENSE
list_directory_structure_to_file.ps1
package-lock.json
package.json
Postman.json
README.md
SnipSet API.postman_collection.json
structure_and_content.ps1
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\docker-compose - Copy.yml
services:
db:
image: postgres:13
environment:
POSTGRES_DB: snipset_db
POSTGRES_USER: snipset_user
POSTGRES_PASSWORD: snipset_your_password
volumes:
- ./db_data:/var/lib/postgresql/data
ports:
- "5432:5432"
backend:
build:
context: ./backend
volumes:
- ./backend:/app
ports:
- "5000:5000"
depends_on:
- db
environment:
FLASK_DEBUG: 1
FLASK_APP: app
DATABASE_URL: postgresql://snipset_user:snipset_your_password@db:5432/snipset_db
DEFAULT_ADMIN_EMAIL: [email protected]
DEFAULT_ADMIN_PASSWORD: admin_password
RECAPTCHA_SITE_KEY: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
RECAPTCHA_SECRET_KEY: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
pgadmin:
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: [email protected]
PGADMIN_DEFAULT_PASSWORD: admin_password
ports:
- "8080:80"
volumes:
- ./pgadmin:/var/lib/pgadmin
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\docker-compose.yml
services:
db:
image: postgres:13
environment:
POSTGRES_DB: snipset_db
POSTGRES_USER: snipset_user
POSTGRES_PASSWORD: snipset_your_password
volumes:
- ./db_data:/var/lib/postgresql/data
ports:
- "5432:5432"
backend:
build:
context: ./backend
volumes:
- ./backend:/app
ports:
- "5000:5000"
depends_on:
- db
environment:
FLASK_DEBUG: 1
FLASK_APP: app
DATABASE_URL: postgresql://snipset_user:snipset_your_password@db:5432/snipset_db
DEFAULT_ADMIN_EMAIL: [email protected]
DEFAULT_ADMIN_PASSWORD: admin_password
RECAPTCHA_SITE_KEY: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
RECAPTCHA_SECRET_KEY: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\README.md
# SnipSet
Build a self-hosted snippet manager with user authentication, advanced search, and role-based access control. Manage Snippets and Business Rules with detailed categorization. Features include email/password and Azure SSO authentication. Utilize Docker for containerization, GitHub for version control, and VSCode for development.
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.9
# Install netcat-openbsd for the entrypoint script
RUN apt-get update && apt-get install -y netcat-openbsd
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Copy the entrypoint script
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# Expose port 5000
EXPOSE 5000
# Define environment variable
ENV FLASK_APP=app
# Add this line to set PYTHONPATH
ENV PYTHONPATH=/app
# Use the entrypoint script to start the application
ENTRYPOINT ["/app/entrypoint.sh"]
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\entrypoint.sh
#!/bin/sh
# Wait for the database to be ready
echo "Waiting for PostgreSQL to be available..."
while ! nc -z db 5432; do
sleep 1
done
echo "Applying database migrations..."
flask db upgrade
echo "Initializing the database..."
python app/database/init_db.py
echo "Starting Flask application..."
exec flask run --host=0.0.0.0
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\migrate.py
from flask import Flask
from flask_migrate import Migrate
from app import create_app, db
app = create_app()
migrate = Migrate(app, db)
if __name__ == "__main__":
app.run(host='0.0.0.0')
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\README.md
# SnipSet Backend
## Setup
1. Build and run the Docker containers:
```sh
docker-compose up --build
```
2. Initialize the database:
```sh
docker-compose exec backend flask db init
docker-compose exec backend flask db migrate
docker-compose exec backend flask db upgrade
```
3. Access the application at `http://localhost:5000`
## Folder Structure
### backend
The root directory for the backend of the application.
- **app/**: Contains the main application code.
- **config/**: Configuration files for the application.
- `config.py`: Contains configuration settings such as database URI and secret keys.
- **models/**: Database models.
- `models.py`: Defines the SQLAlchemy models for the database schema.
- **controllers/**: Business logic and controller code (not yet included but should be added here).
- **routes/**: Contains the route definitions for the application.
- `routes.py`: Defines the API endpoints and links them to controller functions.
- `__init__.py`: Application factory to create and configure the Flask app.
- **.gitignore**: Specifies files and directories to be ignored by Git.
- **directory_structure.txt**: A file listing the structure of the directory.
- **docker-compose/**: Docker compose configuration files (optional).
- **Dockerfile**: Instructions to build the Docker image for the backend service.
- **list_directory_structure_to_file.ps1**: PowerShell script to list the directory structure.
- **README.md**: Instructions and documentation for setting up and running the backend.
- **requirements.txt**: Lists the Python dependencies needed to run the application.
- **swagger.yaml**: API documentation file (if using Swagger for API documentation).
- **migrate.py**: Manages the database migrations using Flask-Migrate.
- **init_db.py**: Script to initialize the database and create tables with initial data.
## Environment Variables
- `DATABASE_URL`: Database connection string
- `SECRET_KEY`: Secret key for session management
- `SECURITY_PASSWORD_SALT`: Salt for password hashing
- `RECAPTCHA_SITE_KEY`: Recaptcha site key
- `RECAPTCHA_SECRET_KEY`: Recaptcha secret key
## Running the Application
### Docker Setup
1. Build and run the Docker containers:
```sh
docker-compose up --build
```
2. Initialize the database:
```sh
docker-compose exec backend flask db init
docker-compose exec backend flask db migrate
docker-compose exec backend flask db upgrade
```
3. Access the application at `http://localhost:5000`
### Manual Setup (Without Docker)
1. Create a virtual environment and install dependencies:
```sh
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install -r requirements.txt
```
2. Set up environment variables in a `.env` file:
```plaintext
DATABASE_URL=postgresql://snipset_user:snipset_your_password@localhost:5432/snipset_db
SECRET_KEY=your_secret_key
SECURITY_PASSWORD_SALT=your_password_salt
RECAPTCHA_SITE_KEY=your_recaptcha_site_key
RECAPTCHA_SECRET_KEY=your_recaptcha_secret_key
```
3. Initialize the database:
```sh
flask db init
flask db migrate
flask db upgrade
```
4. Run the application:
```sh
flask run
```
This README file provides a comprehensive guide to setting up and running the backend, as well as an explanation of the purpose of each folder and file in the backend directory structure.
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\server.py
from app import create_app
import logging
import os
import app.error_handlers # Ensure this import is here to register the error handlers
# Configure logging
logging.basicConfig(level=logging.DEBUG if os.getenv('FLASK_ENV') == 'development' else logging.INFO)
app = create_app()
if __name__ == '__main__':
app.run(host='0.0.0.0')
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\error_handlers.py
from flask import jsonify
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.exceptions import HTTPException
from . import db
def register_error_handlers(app):
@app.errorhandler(404)
def resource_not_found(e):
return jsonify({"error": "Resource not found"}), 404
@app.errorhandler(400)
def bad_request(e):
return jsonify({"error": "Bad request"}), 400
@app.errorhandler(SQLAlchemyError)
def handle_sqlalchemy_error(e):
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
@app.errorhandler(Exception)
def handle_exception(e):
if isinstance(e, HTTPException):
return jsonify({"error": e.description}), e.code
return jsonify({"error": "Internal server error"}), 500
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from flask_babel import Babel
from .config.db_config import Config # Updated import to use db_config
db = SQLAlchemy()
migrate = Migrate()
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
# Initialize extensions
db.init_app(app)
migrate.init_app(app, db)
# Import and register models to ensure they are part of SQLAlchemy
from .models.models import (
User, Role, Category, Subcategory, Snippet, Tag,
SnippetTag, Comment, AuditLog, OAuthToken, FailedLogin,
Backup, AITrainingExport
)
CORS(app)
Babel(app)
# Register blueprints
from .routes.routes import api
app.register_blueprint(api, url_prefix='/api')
return app
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\config\db_config.py
import os
class Config:
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY', 'supersecretkey')
SECURITY_PASSWORD_SALT = os.getenv('SECURITY_PASSWORD_SALT', 'salty')
RECAPTCHA_PUBLIC_KEY = os.getenv('RECAPTCHA_SITE_KEY')
RECAPTCHA_PRIVATE_KEY = os.getenv('RECAPTCHA_SECRET_KEY')
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\auth_controller.py
from flask import Blueprint, request, jsonify, session
from flask_restx import Api, Resource, fields
from werkzeug.security import generate_password_hash, check_password_hash
from app.models.user import User, Role
from app import db
from flask_security import SQLAlchemyUserDatastore
from sqlalchemy.exc import SQLAlchemyError
auth_bp = Blueprint('auth', __name__)
auth_api = Api(auth_bp, version='1.0', title='Auth API', description='Authentication API', doc='/swagger/auth')
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
signup_model = auth_api.model('Signup', {
'username': fields.String(required=True, description='The username'),
'email': fields.String(required=True, description='The email'),
'password': fields.String(required=True, description='The password'),
'name': fields.String(required=True, description='The name'),
'firstname': fields.String(required=True, description='The firstname')
})
login_model = auth_api.model('Login', {
'email': fields.String(required=True, description='The email'),
'password': fields.String(required=True, description='The password')
})
@auth_api.route('/signup')
class Signup(Resource):
@auth_api.expect(signup_model)
def post(self):
data = request.get_json()
username = data['username']
email = data['email']
password = data['password'] # No need to hash here; the model handles it
name = data['name']
firstname = data['firstname']
role_name = 'End User'
role = user_datastore.find_role(role_name)
if not role:
role = user_datastore.create_role(name=role_name)
if User.query.filter_by(username=username).first():
return {"message": "Username already exists"}, 409
if User.query.filter_by(email=email).first():
return {"message": "Email already exists"}, 409
try:
new_user = user_datastore.create_user(
username=username,
email=email,
password=password,
name=name,
firstname=firstname,
roles=[role],
role=role.name
)
db.session.add(new_user) # Add the user to the session
db.session.commit()
return {"message": "User created"}, 201
except SQLAlchemyError as e:
db.session.rollback()
return {"message": "Error creating user", "error": str(e)}, 500
except Exception as e:
return {"message": "An unexpected error occurred", "error": str(e)}, 500
@auth_api.route('/login')
class Login(Resource):
@auth_api.expect(login_model)
def post(self):
data = request.get_json()
try:
user = User.query.filter_by(email=data['email']).first()
if user and check_password_hash(user.password, data['password']):
session['user_id'] = user.id
return {"message": "Login succeeded"}, 200
else:
return {"message": "Invalid credentials"}, 401
except SQLAlchemyError as e:
return {"message": "Database error", "error": str(e)}, 500
except Exception as e:
return {"message": "An unexpected error occurred", "error": str(e)}, 500
@auth_api.route('/logout')
class Logout(Resource):
def get(self):
try:
if 'user_id' not in session:
return jsonify(message="User not logged in"), 400
session.clear()
return jsonify(message="Logout succeeded")
except KeyError:
return jsonify(message="User not logged in"), 400
except Exception as e:
return {"message": "An unexpected error occurred", "error": str(e)}, 500
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\category_controller.py
from flask import request, jsonify
from app import db
from app.models.category import Category
from sqlalchemy.exc import SQLAlchemyError
def create_category():
data = request.get_json()
name = data.get('name')
description = data.get('description')
if not name:
return jsonify({"error": "Name is required"}), 400
try:
new_category = Category(name=name, description=description)
db.session.add(new_category)
db.session.commit()
return jsonify(new_category.to_dict()), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def get_categories():
try:
categories = Category.query.all()
return jsonify([category.to_dict_with_subcategories() for category in categories])
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": "Internal server error"}), 500
except Exception as e:
return jsonify({"error": "Internal server error"}), 500
def delete_category(category_id):
try:
category = Category.query.get_or_404(category_id)
db.session.delete(category)
db.session.commit()
return jsonify({"message": f"Category '{category.name}' deleted successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 400
def update_category(category_id):
data = request.get_json()
name = data.get('name')
description = data.get('description')
try:
category = Category.query.get_or_404(category_id)
if name:
category.name = name
if description:
category.description = description
db.session.commit()
return jsonify(category.to_dict()), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 400
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\query_controller.py
# app/controllers/query_controller.py
from flask import request, jsonify, Blueprint
from app import db
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import text
query_bp = Blueprint('query_bp', __name__)
@query_bp.route('/', methods=['POST'])
def execute_query():
data = request.get_json()
table_name = data.get('table_name')
sql_query = data.get('sql_query')
if not table_name or not sql_query:
return jsonify({"error": "Table name and SQL query are required"}), 400
try:
# Safely format the query
sql_query = text(sql_query.format(table_name=table_name))
result = db.session.execute(sql_query)
records = [dict(row) for row in result.mappings()] # Correctly convert rows to dictionaries
return jsonify(records), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\snippet_controller.py
from flask import request, jsonify
from app import db
from app.models.snippet import Snippet
from app.models.tag import Tag
from sqlalchemy.exc import SQLAlchemyError
def create_snippet():
data = request.get_json()
title = data.get('title')
description = data.get('description')
content = data.get('content')
category_id = data.get('category_id')
subcategory_id = data.get('subcategory_id')
public = data.get('public', False)
user_id = data.get('user_id')
language = data.get('language')
tag_names = data.get('tags', [])
# Validate required fields
if not all([title, description, content, category_id, user_id, language]):
return jsonify({"error": "All required fields must be provided"}), 400
try:
# Create the snippet object
new_snippet = Snippet(
title=title,
description=description,
content=content,
category_id=category_id,
subcategory_id=subcategory_id,
public=public,
user_id=user_id,
language=language
)
# Process tags
tags = []
for tag_name in tag_names:
# Retrieve or create the Tag object
tag = Tag.query.filter_by(name=tag_name).first()
if not tag:
tag = Tag(name=tag_name)
db.session.add(tag)
db.session.flush() # Flush to get the tag's ID before using it
tags.append(tag)
# Add tags to the snippet
new_snippet.tags = tags
# Save the snippet
db.session.add(new_snippet)
db.session.commit()
return jsonify(new_snippet.to_dict()), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig) if e.orig else str(e)}), 500
def get_snippets():
try:
snippets = Snippet.query.all()
return jsonify([snippet.to_dict() for snippet in snippets])
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def get_snippet(snippet_id):
try:
snippet = Snippet.query.get_or_404(snippet_id)
return jsonify(snippet.to_dict())
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def update_snippet(snippet_id):
data = request.get_json()
try:
snippet = Snippet.query.get_or_404(snippet_id)
snippet.title = data.get('title', snippet.title)
snippet.description = data.get('description', snippet.description)
snippet.content = data.get('content', snippet.content)
snippet.type = data.get('type', snippet.type)
snippet.subtype = data.get('subtype', snippet.subtype)
snippet.category_id = data.get('category_id', snippet.category_id)
snippet.subcategory_id = data.get('subcategory_id', snippet.subcategory_id)
snippet.public = data.get('public', snippet.public)
snippet.language = data.get('language', snippet.language)
db.session.commit()
return jsonify(snippet.to_dict()), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def delete_snippet(snippet_id):
try:
snippet = Snippet.query.get_or_404(snippet_id)
db.session.delete(snippet)
db.session.commit()
return '', 204
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def associate_tags(snippet_id):
data = request.get_json()
tags = data.get('tags', [])
try:
snippet = Snippet.query.get_or_404(snippet_id)
snippet.tags = []
for tag_name in tags:
tag = Tag.query.filter_by(name=tag_name).first()
if not tag:
tag = Tag(name=tag_name)
db.session.add(tag)
snippet.tags.append(tag)
db.session.commit()
return jsonify({"message": "Tags associated successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def get_snippets_by_tag(tag_id):
try:
tag = Tag.query.get_or_404(tag_id)
snippets = [snippet.to_dict() for snippet in tag.snippets]
return jsonify(snippets), 200
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\subcategory_controller.py
from flask import request, jsonify
from app import db
from app.models.subcategory import Subcategory
from sqlalchemy.exc import SQLAlchemyError
def create_subcategory():
data = request.get_json()
category_id = data.get('category_id')
name = data.get('name')
description = data.get('description')
if not category_id or not name:
return jsonify({"error": "Category ID and Name are required"}), 400
try:
new_subcategory = Subcategory(category_id=category_id, name=name, description=description)
db.session.add(new_subcategory)
db.session.commit()
return jsonify(new_subcategory.to_dict()), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
def get_subcategories():
try:
subcategories = Subcategory.query.all()
return jsonify([subcategory.to_dict() for subcategory in subcategories])
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def delete_subcategory(subcategory_id):
try:
subcategory = Subcategory.query.get_or_404(subcategory_id)
db.session.delete(subcategory)
db.session.commit()
return jsonify({"message": f"Subcategory '{subcategory.name}' deleted successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 400
def get_subcategories_by_category(category_id):
try:
subcategories = Subcategory.query.filter_by(category_id=category_id).all()
return jsonify([subcategory.to_dict() for subcategory in subcategories])
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
def update_subcategory(subcategory_id):
data = request.get_json()
name = data.get('name')
description = data.get('description')
try:
subcategory = Subcategory.query.get_or_404(subcategory_id)
if name:
subcategory.name = name
if description:
subcategory.description = description
db.session.commit()
return jsonify(subcategory.to_dict()), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 400
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\tag_controller.py
from flask import request, jsonify
from app import db
from app.models.tag import Tag
from sqlalchemy.exc import SQLAlchemyError
def create_tag():
data = request.get_json()
name = data.get('name')
if not name:
return jsonify({"error": "Tag name is required"}), 400
try:
new_tag = Tag(name=name)
db.session.add(new_tag)
db.session.commit()
return jsonify(new_tag.to_dict()), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def get_tags():
try:
tags = Tag.query.all()
return jsonify([tag.to_dict() for tag in tags])
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def update_tag(tag_id):
data = request.get_json()
name = data.get('name')
if not name:
return jsonify({"error": "Tag name is required"}), 400
try:
tag = Tag.query.get_or_404(tag_id)
tag.name = name
db.session.commit()
return jsonify(tag.to_dict()), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def delete_tag(tag_id):
try:
tag = Tag.query.get_or_404(tag_id)
db.session.delete(tag)
db.session.commit()
return jsonify({"message": f"Tag '{tag.name}' deleted successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
**** Here is the content of the file in the path C:\Users\NicolasArgenteAIQOS\OneDrive - AIQOS B.V\Documents\GitHub\SnipSet\backend\app\controllers\user_controller.py
from flask import request, jsonify
from app import db
from app.models.user import User, Profile
from sqlalchemy.exc import SQLAlchemyError
def create_user():
data = request.get_json()
username = data.get('username')
email = data.get('email')
password = data.get('password')
name = data.get('name')
firstname = data.get('firstname')
role = data.get('role')
if not all([username, email, password, name, firstname, role]):
return jsonify({"error": "All fields are required"}), 400
try:
new_user = User(
username=username,
email=email,
password=password,
name=name,
firstname=firstname,
role=role
)
db.session.add(new_user)
db.session.commit()
# Create a profile for the new user
new_profile = Profile(user_id=new_user.id)
db.session.add(new_profile)
db.session.commit()
return jsonify(new_user.to_dict()), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
def get_users():
try:
users = User.query.all()
return jsonify([user.to_dict() for user in users])
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def get_user(user_id):
try:
user = User.query.get_or_404(user_id)
return jsonify(user.to_dict())
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def update_user(user_id):
data = request.get_json()
try:
user = User.query.get_or_404(user_id)
if 'username' in data:
user.username = data['username']
if 'email' in data:
user.email = data['email']
if 'password' in data:
user.password = data['password']
if 'name' in data:
user.name = data['name']
if 'firstname' in data:
user.firstname = data['firstname']
if 'role' in data:
user.role = data['role']
db.session.commit()
return jsonify(user.to_dict()), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 400
def delete_user(user_id):
try:
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return jsonify({"message": f"User '{user.username}' deleted successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e.orig)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 400
def get_user_profile(user_id):
try:
profile = Profile.query.filter_by(user_id=user_id).first()
if profile:
return jsonify(profile.to_dict())
else:
return jsonify({"error": "Profile not found"}), 404
except SQLAlchemyError as e:
return jsonify({"error": str(e.orig)}), 500
def update_user_profile(user_id):
data = request.get_json()
try:
profile = Profile.query.filter_by(user_id=user_id).first()
if not profile:
return jsonify({"error": "Profile not found"}), 404
if 'bio' in data:
profile.bio = data['bio']
if 'avatar_url' in data:
profile.avatar_url = data['avatar_url']
if 'website_url' in data: