Skip to content

Commit

Permalink
Add ticket data from bot and read data using /ticket?id=<id>
Browse files Browse the repository at this point in the history
Basic Create/Modify/View Routes
fixed socket connection issue
  • Loading branch information
HaythmKenway committed Oct 12, 2024
1 parent 48224df commit f93edcf
Show file tree
Hide file tree
Showing 15 changed files with 505 additions and 202 deletions.
8 changes: 5 additions & 3 deletions app/Backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from modules.log import *
import base64
import shutil
import modules.db.db_models as db_models


# Flask configurations
Expand Down Expand Up @@ -46,12 +47,13 @@ def test():
# Socket IO event handling
@socketio.on('connect')
@jwt_required
def connect():
def connect(payload):
sid = request.sid
print(f"User connected: {sid}")
token = request.cookies.get('session')
if token not in sockets:
sockets[token] = {"sid": sid, "connected": True, "history": {}}
socket_connection[token] = ChatbotHandler(token, socketio)
socket_connection[token] = ChatbotHandler(token, socketio,payload)
sockets[token]["sid"] = sid
sockets[token]["connected"] = True

Expand Down Expand Up @@ -112,4 +114,4 @@ def disconnect():


if __name__ == '__main__':
socketio.run(app, debug=True, host="0.0.0.0", port=5000)
socketio.run(app, debug=True, host="0.0.0.0", port=5000)
17 changes: 14 additions & 3 deletions app/Backend/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@

# Admin Creds
ADMIN_CRED = dict({
'username': os.getenv('SVC_ACC', 'admin'),
'password': os.getenv('SVC_ACC_PASS', 'admin')
'username': os.getenv('ADMIN_ACC', 'admin'),
'password': os.getenv('ADMIN_ACC_PASS', 'admin')
})
ADMIN_CRED_2 = dict({
'username': os.getenv('SVC_ACC', 'nig'),
Expand Down Expand Up @@ -53,6 +53,7 @@
instructions_chat="""You are an IT application/expert engineer who has to sort and work on incoming tickets from merchant or clients for worldline\'s products in the payment/fintech industry. start with a greeting and understand the issue, ask specific questions only if required and try to auto fill or get all the details with minimal queries. Have a conversation and when the conversation ends (once the users sends a \'create\' or /create command/text ), provide the json as the last parameter, Do Not provide the json before the conversation ends & keep the conversation natural in a flow. Also give them an option to mention \"create\" to continue creating a ticket (only if the text/description is retrieved from user). Give brief replies. Do not nudge. Upon \"create\" command, STRICTLY give just the json & upon command \"status\", explain what you have understood till now. If any attachment is provided, go through it and analyse it, dont ask the user to explain the logs, understand and retrieve it yourself.
{
\\\"subject\\\" : \\\"\\\", // Generate the title for provided text, string
\\\"description\\\" : \\\"\\\", // Generate the description for provided text, string
\\\"summary\\\": \\\"\\\", // Generate a summary of the text, with all description, string
\\\"attachments\\\": [ {\\\"attachment_name\\\" : \\\"The attachement name \\\", \\\"attachment details\\\" : \\\" analysis, file information about the attachent and issue\\\" } ], // Mention the attachment name and details from it, if it is an image get the error/details or the situation, if it is a log file try to get the error or cause or description from the logs. Do the analysis & try fetching whatever went wrong is is the cause. and give an explanation.
\\\"product_type\\\": \\\"\\\", // retrieve the product type from the text & attachments, string: [ webgui, wlpfo, pass, wlsi, ]
Expand Down Expand Up @@ -95,6 +96,7 @@
"ticket_id": "", // do not modify, use the incoming values
"user": "", // do not modify, use the incoming values
"medium": "", // do not modify, use the incoming values
"description":"",do not modify, use the incoming values
"connection: "", // do not modify, use the incoming values
"text": "", // do not modify, use the incoming values
"subject" : "", // Generate the title for provided text, string
Expand Down Expand Up @@ -137,6 +139,7 @@
"chat_id": "", # 1234567890
"ticket_id": "", # SVC-123456
"user": "", # username
"description":"",#description
"medium": "", # [ "chat (vertex/ollama)", "email", "form" ]
"connection": "live", # [ "live", "offline", "closed" ]
"text": "", # "I am experiencing timeouts with EFTPOS transactions."
Expand All @@ -156,4 +159,12 @@
tmp_folders_cleanup=True
attachment_upload_folder='./bucket/attachments/'
chats_folder='./bucket/chats/'
ticket_folder = "./bucket/tickets"
ticket_folder = "./bucket/tickets"

# Jira Configs

JIRA_CRED = dict({
'username': os.getenv("JIRA_ADMIN",'jiraadmin'),
'password': os.getenv("JIRA_PASS", 'Skibbidi@42069'),
'server': os.getenv("JIRA_SERVER", 'http://localhost:8080')
})
25 changes: 13 additions & 12 deletions app/Backend/database/data/customer_table.csv
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
name ,age ,gender ,email ,phone ,company ,role ,score
Ras Das , 23 ,female ,ras.das@nullbyte.exe ,6969420911 ,ICICI ,Techinal Staff , 3
Alice Johnson , 30 ,Female ,alice.johnson@example.com ,1234567890 ,Tech Corp ,Customer , 85
Bob Smith , 28 ,Male ,bob.smith@example.com ,1234567891 ,Innovate LLC ,Customer , 90
Charlie Brown , 35 ,Male ,charlie.brown@example.com ,1234567892 ,NextGen Inc ,Customer , 78
Daisy White , 22 ,Female ,daisy.white@example.com ,1234567893 ,Future Solutions ,Customer , 88
Ethan Hunt , 40 ,Male ,ethan.hunt@example.com ,1234567894 ,Prime Services ,Customer , 95
Fiona Green , 29 ,Female ,fiona.green@example.com ,1234567895 ,Global Enterprises ,Customer , 80
George Black , 45 ,Male ,george.black@example.com ,1234567896 ,Visionary Tech ,Customer , 70
Hannah Brown , 33 ,Female ,hannah.brown@example.com ,1234567897 ,Smart Solutions ,Customer , 82
Ian Wright , 27 ,Male ,ian.wright@example.com ,1234567898 ,Dynamica Industries ,Customer , 87
Julia Roberts , 31 ,Female ,julia.roberts@example.com ,1234567899 ,Innovation Hub ,Customer , 92
name,age,gender,email,phone,company,role,score
Unassigned,0,Male,unassigned@nullbyte.com,,unassigned,unassigned,0
Ras Das,23,Female,ras.das@nullbyte.exe,6969420911,ICICI,Techinal Staff,3
Alice Johnson,30,Female,alice.johnson@example.com,1234567890,Tech Corp,Customer,85
Bob Smith,28,Male,bob.smith@example.com,1234567891,Innovate LLC,Customer,90
Charlie Brown,35,Male,charlie.brown@example.com,1234567892,NextGen Inc,Customer,78
Daisy White,22,Female,daisy.white@example.com,1234567893,Future Solutions,Customer,88
Ethan Hunt,40,Male,ethan.hunt@example.com,1234567894,Prime Services,Customer,95
Fiona Green,29,Female,fiona.green@example.com,1234567895,Global Enterprises,Customer,80
George Black,45,Male,george.black@example.com,1234567896,Visionary Tech,Customer,70
Hannah Brown,33,Female,hannah.brown@example.com,1234567897,Smart Solutions,Customer,82
Ian Wright,27,Male,ian.wright@example.com,1234567898,Dynamica Industries,Customer,87
Julia Roberts,31,Female,julia.roberts@example.com,1234567899,Innovation Hub,Customer,92
25 changes: 13 additions & 12 deletions app/Backend/database/data/employee_table.csv
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
name ,age ,gender ,email ,phone ,role ,score ,manager ,gcm ,experience
Rajashree ,23 ,female ,Rajashree@nullbyte.exe ,0420420911 ,Associate Consultant ,4 ,69 ,1 ,2
Alice Johnson ,30 ,Female ,alice.johnson.emp@example.com ,1234567890 ,Sales ,85 , ,1 ,5
Bob Smith ,28 ,Male ,bob.smith.emp@example.com ,1234567891 ,Support ,90 ,1 ,2 ,3
Charlie Brown ,35 ,Male ,charlie.brown.emp@example.com ,1234567892 ,Development ,78 ,1 ,3 ,8
Daisy White ,22 ,Female ,daisy.white.emp@example.com ,1234567893 ,HR ,88 , ,4 ,2
Ethan Hunt ,40 ,Male ,ethan.hunt.emp@example.com ,1234567894 ,Management ,95 ,3 ,5 ,10
Fiona Green ,29 ,Female ,fiona.green.emp@example.com ,1234567895 ,Marketing ,80 ,2 ,6 ,4
George Black ,45 ,Male ,george.black.emp@example.com ,1234567896 ,Finance ,70 ,5 ,7 ,12
Hannah Brown ,33 ,Female ,hannah.brown.emp@example.com ,1234567897 ,Development ,82 ,3 ,8 ,7
Ian Wright ,27 ,Male ,ian.wright.emp@example.com ,1234567898 ,Support ,87 ,4 ,9 ,3
Julia Roberts ,31 ,Female ,julia.roberts.emp@example.com ,1234567899 ,Sales ,92 ,5 ,10 ,6
name,age,gender,email,phone,role,score,manager,gcm,experience
Unassigned,0,Male,unassigned@nullbyte.com,,unassigned,0,1,0,1
Rajashree,23,Female,Rajashree@nullbyte.exe,0420420911,Associate Consultant,4,69,1,2
Alice Johnson,30,Female,alice.johnson.emp@example.com,1234567890,Sales,85,,1,5
Bob Smith,28,Male,bob.smith.emp@example.com,1234567891,Support,90,1,2,3
Charlie Brown,35,Male,charlie.brown.emp@example.com,1234567892,Development,78,1,3,8
Daisy White,22,Female,daisy.white.emp@example.com,1234567893,HR,88,,4,2
Ethan Hunt,40,Male,ethan.hunt.emp@example.com,1234567894,Management,95,3,5,10
Fiona Green,29,Female,fiona.green.emp@example.com,1234567895,Marketing,80,2,6,4
George Black,45,Male,george.black.emp@example.com,1234567896,Finance,70,5,7,12
Hannah Brown,33,Female,hannah.brown.emp@example.com,1234567897,Development,82,3,8,7
Ian Wright,27,Male,ian.wright.emp@example.com,1234567898,Support,87,4,9,3
Julia Roberts,31,Female,julia.roberts.emp@example.com,1234567899,Sales,92,5,10,6
6 changes: 4 additions & 2 deletions app/Backend/database/dockerfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
FROM mysql:8.0

ENV MYSQL_ROOT_PASSWORD=root
ENV MYSQL_DATABASE=nullbyte
ENV MYSQL_USER=nullbyteadmin
#ENV MYSQL_DATABASE=nullbyte
#ENV MYSQL_USER=nullbyteadmin
ENV MYSQL_PASSWORD=rootpassword
ENV MYSQL_OPTIONS="--secure-file-priv=false"


RUN mkdir -p /var/lib/mysql-files

Expand Down
21 changes: 14 additions & 7 deletions app/Backend/database/scripts/create_database.sql
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
DROP DATABASE IF EXISTS nullbyte;

CREATE DATABASE IF NOT EXISTS nullbyte;
USE nullbyte;

-- Corrected the GRANT statement for MySQL 8.0 and later
CREATE USER IF NOT EXISTS 'nullbyteadmin'@'%' IDENTIFIED BY 'rootpassword';
GRANT ALL PRIVILEGES ON nullbyte.* TO 'nullbyteadmin'@'%';
FLUSH PRIVILEGES;

CREATE TABLE IF NOT EXISTS customer (
id INT AUTO_INCREMENT PRIMARY KEY,
Id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT,
gender ENUM('Male', 'Female'),
Expand All @@ -29,37 +27,46 @@ CREATE TABLE IF NOT EXISTS employee (
phone VARCHAR(15),
role VARCHAR(100),
score INT,
manager INT DEFAULT NULL, -- Allow manager to be NULL by default
manager INT DEFAULT NULL,
gcm INT,
experience INT,
FOREIGN KEY (manager) REFERENCES employee(id) ON DELETE SET NULL
);

CREATE TABLE IF NOT EXISTS ticket (
Id INT AUTO_INCREMENT PRIMARY KEY,
Ticket_Id INT AUTO_INCREMENT PRIMARY KEY,
Chat_Id VARCHAR(50),
Subject VARCHAR(255) NOT NULL,
Summary VARCHAR(255) NOT NULL,
Analysis TEXT,
Attachments BLOB,
Type VARCHAR(100),
Description TEXT NOT NULL,
Status ENUM('Open', 'In Progress', 'Closed', 'Reopened') NOT NULL,
Priority ENUM('Low', 'Medium', 'High') NOT NULL,
Issue_Type VARCHAR(50),
Channel VARCHAR(100),
Customer_ID INT,
Product_ID INT,
Product_ID VARCHAR(100),
Medium VARCHAR(100),
Team VARCHAR(50),
Assignee_ID INT,
Resolution TEXT,
Issue_Date DATETIME DEFAULT CURRENT_TIMESTAMP,
First_Response_Time DATETIME,
Time_to_Resolution INT,
Reopens INT DEFAULT 0,
Story_Points INT,
Score INT,
FOREIGN KEY (Customer_ID) REFERENCES customer(id) ON DELETE CASCADE,
FOREIGN KEY (Assignee_ID) REFERENCES employee(id) ON DELETE SET NULL
);


CREATE TABLE IF NOT EXISTS comments (
Ticket_id INT NOT NULL,
Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
Comment_user INT,
Comment TEXT,
FOREIGN KEY (Ticket_id) REFERENCES ticket(Id) ON DELETE CASCADE -- Added foreign key for ticket
FOREIGN KEY (Ticket_id) REFERENCES ticket(Ticket_Id) ON DELETE CASCADE -- Added foreign key for ticket
);
62 changes: 39 additions & 23 deletions app/Backend/modules/auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,55 @@
from flask import Blueprint, request, make_response, jsonify
import datetime
from .ldap_wrapper import Lwrapper
from ..log import logger
from modules.log import *
from config import *
# from flask import session

auth_ldap = Blueprint('auth', __name__)
lwrapper=Lwrapper()


@auth_ldap.post('/auth')
def authenticate():
if request.is_json:
body = request.json
else:
body = request.form

username = body.get('email')
password = body.get('password')
payload = {}

if not username or not password:
return make_response(jsonify({'error': 'Email and password are required'}), 400)
return make_response(jsonify({'error': 'email and password are required'}), 400)

logger.info(f"Authenticating user: {username}")

if Lwrapper().Authenticate(username, password):
payload = {
'sub': username,
'iat': datetime.datetime.now(datetime.timezone.utc),
'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)
if username == ADMIN_CRED['username'] and password == ADMIN_CRED['password']:
payload = {'username': 'Administrator', 'ou': [], 'upn': 'administrator@nullbyte.exe'}
elif lwrapper.Authenticate(username, password):
payload = lwrapper.getPayload(username)

payload['iat'] = datetime.datetime.now(datetime.timezone.utc)
payload['exp'] = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=JWT_EXP_DELTA_SECONDS)
logger.info(payload)

token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)

if token:
response = make_response(jsonify({'token': token, 'message': 'Authentication successful'}), 201)
response.set_cookie('session', token, httponly=True, secure=True)
if username in users_token:
del users[users_token[username]]
users_token[username] = token
users[token] = {
'username': username,
'added': payload.get('iat'),
'exp': payload.get('exp'),
}
token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
if token:
response = make_response(jsonify({'token': token, 'message': 'Authentication successful'}), 201)
response.set_cookie('session', token, httponly=True, secure=True)
if username in users_token:
del users[users_token[username]]
users_token[username] = token
users[token] = {
'username': username,
'added': payload.get('iat'),
'exp': payload.get('exp'),
}
logger.info(f"Session user set to: {username} {token}")
return response
logger.info(f"Session user set to: {username} {token}")
return response

return make_response(jsonify({'error': 'Invalid credentials'}), 401)

def cleanup_user(token=None, user_id=None):
Expand All @@ -63,17 +72,24 @@ def decorated(*args, **kwargs):
if 'Authorization' in request.headers:
token = request.headers['Authorization'].split(" ")[1]
elif 'session' in request.cookies:
print("Session Cookie: ", request.cookies['session'])
logging.debug("Session Cookie: %s", request.cookies['session'])
token = request.cookies['session']

if not token:
return jsonify({'message': 'Token is missing!'}), 401
return jsonify({'message': 'Token is missing!'}), 401

try:
data = jwt.decode(token, JWT_SECRET, JWT_ALGORITHM)
logging.debug("Decoded JWT data: %s", data)
except jwt.ExpiredSignatureError:
return jsonify({'message': 'Token has expired!'}), 401
except jwt.InvalidTokenError:
return jsonify({'message': 'Invalid token!'}), 401

# Check if the decorated function accepts 'payload' as a keyword argument
if 'payload' in f.__code__.co_varnames:
kwargs['payload'] = data # Store payload in kwargs if the function accepts it

return f(*args, **kwargs)

return decorated
Expand Down
Loading

0 comments on commit f93edcf

Please sign in to comment.