Compare commits

..

6 Commits

Author SHA1 Message Date
4d9e136166 Updated bug
All checks were successful
Build / build-windows-binary (push) Successful in 30s
Build / build-linux-binary (push) Successful in 48s
2024-08-26 14:25:47 -05:00
603bc13683 feat(doc strings) #18 Add documentation to all functions in code
All checks were successful
Build / build-windows-binary (push) Successful in 33s
Build / build-linux-binary (push) Successful in 1m52s
2024-08-26 14:21:29 -05:00
394c276131 fix(home directory) #15 home directory not correct 2024-08-26 13:50:35 -05:00
cb96b00e8d feat(config) #10 add config.toml to releases 2024-08-26 13:25:20 -05:00
abd669c3bb Merge pull request 'fix(authentication): BUG #20 - Authentication isnt working with existing logic & updated model' (#21) from fix-first-time-auth-error into main
All checks were successful
Build / build-windows-binary (push) Successful in 34s
Build / build-linux-binary (push) Successful in 1m23s
Reviewed-on: #21
2024-08-22 14:07:43 -05:00
487d883297 fix(authentication): BUG #20 - Authentication isnt working with existing logic & updated model 2024-08-22 14:04:00 -05:00
7 changed files with 55 additions and 12 deletions

View File

@ -38,4 +38,6 @@ jobs:
- run: pyinstaller --noconfirm --onefile --console ${{ gitea.workspace }}/inex.py - run: pyinstaller --noconfirm --onefile --console ${{ gitea.workspace }}/inex.py
- uses: softprops/action-gh-release@v2 - uses: softprops/action-gh-release@v2
with: with:
files: ${{ gitea.workspace }}/dist/inex.exe files: |
${{ gitea.workspace }}/dist/inex.exe
${{ gitea.workspace }}/config.toml.example

12
inex.py
View File

@ -13,7 +13,10 @@ import inexSqlquery
class Inex: class Inex:
def __init__(self): def __init__(self):
"""Initilize config, calls functions from inex-connect.py and inex-logging.py""" """Initilize config, calls functions from inexConnect.py, inexLogging.py
inexDataModel.py, inexDataProcessing.py, inexEncoder.py and inexSqlquery.py
Main logic of the program. Requires a config.toml in the same directory it's
being run from."""
# assign libraries # assign libraries
self.db = pyodbc self.db = pyodbc
self.il = logging self.il = logging
@ -25,6 +28,7 @@ class Inex:
self.e = inexEncoder.Encoder self.e = inexEncoder.Encoder
self.sq = inexSqlquery self.sq = inexSqlquery
# Check if local config file exists.
if self.os.path.exists('./config.toml'): if self.os.path.exists('./config.toml'):
config_file_path = './config.toml' config_file_path = './config.toml'
with open(config_file_path, 'rb') as c: with open(config_file_path, 'rb') as c:
@ -71,18 +75,20 @@ class Inex:
# create the connection to the database # create the connection to the database
self.cursor = self.ic.inexSql.connectDatabase(self, self.db, self.dbDriver, self.dbServer, self.dbDatabase, self.dbUser, self.dbPassword) self.cursor = self.ic.inexSql.connectDatabase(self, self.db, self.dbDriver, self.dbServer, self.dbDatabase, self.dbUser, self.dbPassword)
# Query the database
self.data = self.ic.inexSql.databaseQuery(self, self.cursor, self.sq.sqlQuerymodel.queryData(self.queryOverride,self.dbQuery, self.queryDaystopull)) self.data = self.ic.inexSql.databaseQuery(self, self.cursor, self.sq.sqlQuerymodel.queryData(self.queryOverride,self.dbQuery, self.queryDaystopull))
# Modify the data to meet EFC requirements
self.modifiedData = processData(self.data, dataTemplate, prd_ext_tenant_name=self.prdExttenantname,product_name=self.productName,\ self.modifiedData = processData(self.data, dataTemplate, prd_ext_tenant_name=self.prdExttenantname,product_name=self.productName,\
prd_ext_tenant_id=self.platformConfig["tenant_id"]) prd_ext_tenant_id=self.platformConfig["tenant_id"])
# Push data to EFC. Check for local Auth token -> Authenticate if needed -> push data
if self.pushToplatform: if self.pushToplatform:
inexConnect.fortraEFC.__init__(self) inexConnect.fortraEFC.__init__(self)
# TODO: move this to its own function
if self.useLog: if self.useLog:
self.il.warning(f"Writing to '{self.outputFile}'.") self.il.warning(f"Writing to '{self.outputFile}'.")
# Write data to json
if self.writeJsonfile: if self.writeJsonfile:
with open(self.outputFile, "w") as f: with open(self.outputFile, "w") as f:
self.j.dump(self.modifiedData, f, indent = 2, cls=self.e) self.j.dump(self.modifiedData, f, indent = 2, cls=self.e)

View File

@ -20,6 +20,7 @@ class inexSql:
return cursor return cursor
def databaseQuery(self, cursor, query, args=()): def databaseQuery(self, cursor, query, args=()):
"""Use the database connection to send a query."""
if self.useLog: if self.useLog:
self.il.debug(f"Query:") self.il.debug(f"Query:")
self.il.debug(query) self.il.debug(query)
@ -43,7 +44,10 @@ class inexSql:
return r return r
class fortraEFC: class fortraEFC:
"""Class to connect to fortra EFC. It will authenticate and push rest payloads.
Writes a .token file to the same directory script was run in."""
def __init__(self): def __init__(self):
"""This is the logic for how authentication is handled"""
# Check if .token file is present # Check if .token file is present
if fortraEFC.readToken(self) == 1: if fortraEFC.readToken(self) == 1:
# Get fresh token. First run. # Get fresh token. First run.
@ -57,6 +61,8 @@ class fortraEFC:
fortraEFC.pushPayload(self) fortraEFC.pushPayload(self)
def readToken(self): def readToken(self):
"""Looks locally for a .token file. Returns a numeral code
for logic in the init method."""
if self.os.path.exists(self.tokenFilepath): if self.os.path.exists(self.tokenFilepath):
with open(self.tokenFilepath, 'rb') as t: with open(self.tokenFilepath, 'rb') as t:
self.tokenData = self.j.load(t) self.tokenData = self.j.load(t)
@ -66,6 +72,7 @@ class fortraEFC:
return 1 return 1
def getToken(self): def getToken(self):
"""Gets a token from fortra idp."""
self.tokenData = self.r.post(self.platformConfig["idp"], data={"grant_type":"client_credentials",\ self.tokenData = self.r.post(self.platformConfig["idp"], data={"grant_type":"client_credentials",\
"client_id": self.platformConfig["client_id"],\ "client_id": self.platformConfig["client_id"],\
"client_secret": self.platformConfig["secret"],}) "client_secret": self.platformConfig["secret"],})
@ -73,12 +80,14 @@ class fortraEFC:
self.il.debug(f'getToken {self.tokenData["access_token"]}') self.il.debug(f'getToken {self.tokenData["access_token"]}')
def writeToken(self): def writeToken(self):
"""Writes a token to a local file named '.token'."""
fortraEFC.getToken(self) fortraEFC.getToken(self)
with open(self.tokenFilepath, "w") as f: with open(self.tokenFilepath, "w") as f:
self.j.dump(self.tokenData, f, indent = 2) self.j.dump(self.tokenData, f, indent = 2)
self.il.debug(f'writeToken {self.tokenData["access_token"]}') self.il.debug(f'writeToken {self.tokenData["access_token"]}')
def pushPayload(self): def pushPayload(self):
"""Sends data to fortra EFC. Requires a token from the idp."""
self.il.debug(f'pushPayload {self.tokenData["access_token"]}') self.il.debug(f'pushPayload {self.tokenData["access_token"]}')
url = f'{self.platformConfig["efc_url"]}/api/v1/unity/data/{self.platformConfig["tenant_id"]}/machine_event' url = f'{self.platformConfig["efc_url"]}/api/v1/unity/data/{self.platformConfig["tenant_id"]}/machine_event'
pushPayloadResponse = self.r.post(url, headers={'Authorization': f'Bearer {self.tokenData["access_token"]}'},\ pushPayloadResponse = self.r.post(url, headers={'Authorization': f'Bearer {self.tokenData["access_token"]}'},\

View File

@ -1,4 +1,8 @@
def dataTemplate(transactionType,**kwargs): def dataTemplate(transactionType,**kwargs):
"""Created templates for use. This function forms json data into an
appropriate model for EFC. It returnes the appropriate template based
on the transaction type passed into the function. The logic to process
this is at the bottom of the function."""
upload = { upload = {
"bytes" : kwargs.get('bytes'), "bytes" : kwargs.get('bytes'),
"dst_endpoint": { "dst_endpoint": {

View File

@ -1,7 +1,8 @@
def processData(data, template, **kwargs): def processData(data, template, **kwargs):
"""Translates data from sql query to the appropriate place in the respective template. """Translates data from sql query to the appropriate place in the respective template.
Accepts data, which is the sql query output, the template function, and finally Accepts data, which is the sql query output, the template function, and finally
additional data to insert into the template.""" additional data to insert into the template. Uses other functions to further
process row data."""
processedData = [] processedData = []
transactionLoginid = [] transactionLoginid = []
@ -17,6 +18,7 @@ def processData(data, template, **kwargs):
continue continue
userType = identifyUserType(row.get('user_type')) userType = identifyUserType(row.get('user_type'))
userHome = parseHomefolder(row.get('Actor'),row.get('VirtualFolderName'))
try: try:
processedData.append(template(identifyUtypecommand,\ processedData.append(template(identifyUtypecommand,\
prd_ext_tenant_name=kwargs.get('prd_ext_tenant_name'),\ prd_ext_tenant_name=kwargs.get('prd_ext_tenant_name'),\
@ -45,7 +47,7 @@ def processData(data, template, **kwargs):
duration=row.get('TransferTime'),\ duration=row.get('TransferTime'),\
user_type=userType,\ user_type=userType,\
user_name=row.get('Actor'),\ user_name=row.get('Actor'),\
user_home_directory=row.get('VirtualFolderName'),\ user_home_directory=userHome,\
utype=identifyUtypecommand)) utype=identifyUtypecommand))
except UnboundLocalError: except UnboundLocalError:
print(f'Problem row GUID:{row.get("TransactionGUID")} ::: TransactionObject:{row.get("TransactionObject")} Command: {row.get("Command")}') print(f'Problem row GUID:{row.get("TransactionGUID")} ::: TransactionObject:{row.get("TransactionObject")} Command: {row.get("Command")}')
@ -80,7 +82,7 @@ def processData(data, template, **kwargs):
user_uid=row.get('TransactionID'),\ user_uid=row.get('TransactionID'),\
user_type=userType,\ user_type=userType,\
user_name=row.get('Actor'),\ user_name=row.get('Actor'),\
user_home_directory=row.get('PhysicalFolderName'),\ user_home_directory=userHome,\
utype=identifyUtypetransactionObject\ utype=identifyUtypetransactionObject\
)) ))
transactionLoginid.append(row.get('TransactionGUID')) transactionLoginid.append(row.get('TransactionGUID'))
@ -100,6 +102,20 @@ def identifyUserType(obj):
else: else:
return None return None
def parseHomefolder(user, virtualfolder):
"""Extract users home folder using the username. Will not work on edge cases
such as when a users home folder does not have the user name. When that occurs
it is impossible to know based on the arm data what the home folder is.
This function is an assumption so it may return the incorrect home folder.
This function finds the user name and takes the path from the left of the folder
as the home folder. There are cases where this may not be accurate."""
if user:
userSplit = f'/{user}/'
if virtualfolder:
if userSplit in virtualfolder:
home = virtualfolder.split(userSplit)[0] + userSplit
return home if home else None
def identifyUtype(obj): def identifyUtype(obj):
"""Process Type of transaction based on string that passed in. """Process Type of transaction based on string that passed in.
Return transaction type.""" Return transaction type."""

View File

@ -1,6 +1,6 @@
class sqlQuerymodel: class sqlQuerymodel:
def queryData(overRideflag, configQuery, daysTopull): def queryData(overRideflag, configQuery, daysTopull):
"""Embedded query data""" """Embedded query data. Data is slightly modified to change the amount of days to pull."""
q ="""DECLARE @stopTime DATETIME2 q ="""DECLARE @stopTime DATETIME2
SET @stopTime=DATEADD(DAY, -30, GETDATE()) SET @stopTime=DATEADD(DAY, -30, GETDATE())
SELECT p.ProtocolCommandID, t.Time_stamp, p.RemoteIP, p.RemotePort, p.LocalIP, p.LocalPort, p.Protocol, p.SiteName, p.Command, p.FileName, p.PhysicalFolderName, p.VirtualFolderName, p.FileSize, p.TransferTime, p.BytesTransferred, p.Description, p.ResultID, t.TransactionID, p.Actor, t.TransactionObject, t.NodeName, t.TransactionGUID, a.Protocol user_type SELECT p.ProtocolCommandID, t.Time_stamp, p.RemoteIP, p.RemotePort, p.LocalIP, p.LocalPort, p.Protocol, p.SiteName, p.Command, p.FileName, p.PhysicalFolderName, p.VirtualFolderName, p.FileSize, p.TransferTime, p.BytesTransferred, p.Description, p.ResultID, t.TransactionID, p.Actor, t.TransactionObject, t.NodeName, t.TransactionGUID, a.Protocol user_type

14
test.py
View File

@ -15,8 +15,6 @@ def builddict(keys,*args,**kwargs):
dict[key] = kwargs.get(key) dict[key] = kwargs.get(key)
print(dict) print(dict)
testfolder = '/Usr/a/asdf/asf'
user = 'a'
def identifyUtype(obj): def identifyUtype(obj):
"""Process Type of transaction based on string that passed in. """Process Type of transaction based on string that passed in.
@ -37,6 +35,14 @@ def identifyUtype(obj):
else: else:
return "other" return "other"
transactionType = 'file_uploaded'
print(transactionType.split("_")[1].rstrip("d").rstrip("e")) testfolder = '/Usr/a/asdf/asf/asdfas/asdfasdf/'
user = 'a'
def parsehomefolder(user, virtualfolder):
userSplit = f'/{user}/'
home = virtualfolder.split(userSplit)[0] + userSplit
print(home)
return home
a = parsehomefolder(user, testfolder)