Skip to content

Commit

Permalink
email work around and cwd stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
kirklholub committed Jul 26, 2023
1 parent daab923 commit 50ab23e
Show file tree
Hide file tree
Showing 16 changed files with 369 additions and 123 deletions.
20 changes: 20 additions & 0 deletions backends/email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# https://medium.com/@hhuysamen/sending-emails-using-django-4-2-3e5de1ff64dc

import ssl

from django.core.mail.backends.smtp import EmailBackend as SMTPBackend
from django.utils.functional import cached_property


class EmailBackend(SMTPBackend):
@cached_property
def ssl_context(self):
if self.ssl_certfile or self.ssl_keyfile:
ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile)
return ssl_context
else:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context
61 changes: 37 additions & 24 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,46 +1,59 @@
asgiref==3.5.2
aenum==3.1.15
asgiref==3.7.2
backports.zoneinfo==0.2.1
boto3==1.26.79
botocore==1.29.79
certifi==2022.12.7
beautifulsoup4==4.12.2
boto3==1.26.163
botocore==1.29.163
bs4==0.0.1
certifi==2023.5.7
cffi==1.15.1
charset-normalizer==2.1.1
contourpy==1.0.6
cryptography==40.0.1
charset-normalizer==3.1.0
contourpy==1.1.0
cryptography==41.0.1
cycler==0.11.0
diagrams==0.23.3
Django==4.2.2
django-extensions==3.2.1
fonttools==4.38.0
django-extensions==3.2.3
fonttools==4.40.0
graphviz==0.20.1
gunicorn==20.1.0
idna==3.4
importlib-resources==5.12.0
isodate==0.6.1
jdcal==1.4.1
Jinja2==3.1.2
jmespath==1.0.1
kiwisolver==1.4.4
lxml==4.9.2
matplotlib==3.6.2
mysql-connector-python==8.0.32
mysqlclient==2.1.1
networkx==2.8.8
numpy==1.23.5
MarkupSafe==2.1.3
matplotlib==3.7.1
mysql-connector-python==8.0.33
mysqlclient==2.2.0
networkx==3.1
numpy==1.25.0
oauthlib==3.2.2
onelogin==3.1.0
packaging==21.3
Pillow==9.3.0
onelogin==3.1.5
packaging==23.1
Pillow==9.5.0
protobuf==3.20.3
pyclean==2.2.0
pyclean==2.7.3
pycparser==2.21
pydantic==1.10.9
pydot==1.4.2
PyJWT==2.6.0
pyOpenSSL==23.1.1
pyparsing==3.0.9
PyJWT==2.7.0
pyOpenSSL==23.2.0
pyparsing==3.1.0
python-dateutil==2.8.2
python3-saml==1.15.0
pytz==2022.6
pytz==2023.3
requests==2.31.0
requests-oauthlib==1.3.1
s3transfer==0.6.0
s3transfer==0.6.1
six==1.16.0
soupsieve==2.4.1
sqlparse==0.4.4
urllib3==1.26.12
typed-ast==1.5.4
typing_extensions==4.6.3
urllib3==1.26.16
xmlsec==1.3.13
zipp==3.15.0
46 changes: 46 additions & 0 deletions requirements.txt.orig
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
asgiref==3.5.2
backports.zoneinfo==0.2.1
boto3==1.26.79
botocore==1.29.79
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==2.1.1
contourpy==1.0.6
cryptography==40.0.1
cycler==0.11.0
Django==4.2.2
django-extensions==3.2.1
fonttools==4.38.0
gunicorn==20.1.0
idna==3.4
isodate==0.6.1
jdcal==1.4.1
jmespath==1.0.1
kiwisolver==1.4.4
lxml==4.9.2
matplotlib==3.6.2
mysql-connector-python==8.0.32
mysqlclient==2.1.1
networkx==2.8.8
numpy==1.23.5
oauthlib==3.2.2
onelogin==3.1.0
packaging==21.3
Pillow==9.3.0
protobuf==3.20.3
pyclean==2.2.0
pycparser==2.21
pydot==1.4.2
PyJWT==2.6.0
pyOpenSSL==23.1.1
pyparsing==3.0.9
python-dateutil==2.8.2
python3-saml==1.15.0
pytz==2022.6
requests==2.31.0
requests-oauthlib==1.3.1
s3transfer==0.6.0
six==1.16.0
sqlparse==0.4.4
urllib3==1.26.12
xmlsec==1.3.13
9 changes: 9 additions & 0 deletions sites/management/commands/diagrams_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# diagram.py
from diagrams import Diagram
from diagrams.aws.compute import EC2
from diagrams.aws.database import RDS
from diagrams.aws.network import ELB

with Diagram("Web Service", show=False):
ELB("lb") >> EC2("web") >> RDS("userdb")

17 changes: 17 additions & 0 deletions sites/management/commands/send_email_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# https://stackoverflow.com/questions/19475955/using-django-models-in-external-python-script
from django.core.management.base import BaseCommand
from django.core.mail import send_mail

class Command(BaseCommand):
help = "Test send_email"

def handle(self, *args, **options):
subject = "test from webstage8"
fromaddr = "[email protected]"
toaddr = ["[email protected]"]
body = "this worked form gsl-webstage8"
try:
send_mail(subject, body, fromaddr, toaddr, fail_silently=False)
except Exception as e:
print("Exception: " + str(e))

10 changes: 10 additions & 0 deletions sites/management/commands/web_service
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
digraph "Web Service" {
graph [fontcolor="#2D3436" fontname="Sans-Serif" fontsize=15 label="Web Service" nodesep=0.60 pad=2.0 rankdir=LR ranksep=0.75 splines=ortho]
node [fixedsize=true fontcolor="#2D3436" fontname="Sans-Serif" fontsize=13 height=1.4 imagescale=true labelloc=b shape=box style=rounded width=1.4]
edge [color="#7B8894"]
aa87ab6ec1a5404f8a7dfbf745fd8a60 [label=lb height=1.9 image="/opt/ssop/venv/lib64/python3.9/site-packages/resources/aws/network/elastic-load-balancing.png" shape=none]
"9c33105ee3a44262b91f00922e59e7a4" [label=web height=1.9 image="/opt/ssop/venv/lib64/python3.9/site-packages/resources/aws/compute/ec2.png" shape=none]
aa87ab6ec1a5404f8a7dfbf745fd8a60 -> "9c33105ee3a44262b91f00922e59e7a4" [dir=forward fontcolor="#2D3436" fontname="Sans-Serif" fontsize=13]
"48053bbab0ac4d80a16c6279e0859504" [label=userdb height=1.9 image="/opt/ssop/venv/lib64/python3.9/site-packages/resources/aws/database/rds.png" shape=none]
"9c33105ee3a44262b91f00922e59e7a4" -> "48053bbab0ac4d80a16c6279e0859504" [dir=forward fontcolor="#2D3436" fontname="Sans-Serif" fontsize=13]
}
43 changes: 15 additions & 28 deletions sites/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1247,28 +1247,14 @@ def is_user_a_sysad(**kwargs):

oukeylist = []
keys = kwargs['request'].session['samlUserdata'].keys()
msg = " samlUserdata keys: " + str(keys)
logger.info(msg)
for k in kwargs['request'].session['samlUserdata'].keys():
if str(k).startswith('ou'):
oukeylist.append(str(k))
if len(oukeylist) > int(1):
oukeylist.sort()
msg = " oukeylist: " + str(oukeylist)
logger.info(msg)
oukeylist = ['ou0', 'ou1', 'ou2']
for k in oukeylist:
msg = " k = " + str(k)
logger.info(msg)
orglist.append(kwargs['request'].session['samlUserdata'][str(k)][0])
msg = " samlUserdata = " + str(kwargs['request'].session['samlUserdata'][str(k)][0])
logger.info(msg)
msg = " user: " + str(user)
logger.info(msg)
msg = " homeorg: " + str(homeorg)
logger.info(msg)
msg = " orglist: " + str(orglist)
logger.info(msg)
get_or_add_sysadmin(user, homeorg, orglist)

class Sysadmin(models.Model):
Expand Down Expand Up @@ -1318,7 +1304,6 @@ def post_auth_user_has_authenticated(sender, **kwargs):
is_user_a_sysad(**kwargs)
user_has_authenticated_sendemail(**kwargs)


@receiver(user_login_failure)
def post_auth_user_login_failure(sender, **kwargs):
now = datetime.datetime.utcnow()
Expand Down Expand Up @@ -1372,7 +1357,7 @@ def user_has_authenticated_sendemail(**kwargs):
hashedtoken = hl.hexdigest()
existingtoken = 'none'

fname = '/tmp/ssop_' + str(kwargs['user'].id) + '.txt'
fname = 'uploads/ssopuid_' + str(kwargs['user'].id) + '.txt'
try:
if os.path.exists(fname):
fh = open(fname, 'r')
Expand All @@ -1389,9 +1374,6 @@ def user_has_authenticated_sendemail(**kwargs):
firstname = kwargs['user'].first_name
ymdhms = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
subject = settings.USER_HAS_AUTHENTICATED_SUBJECT
#body = 'Hello ' + firstname + ',\nWe noticed you logged into SSOPSB at ' + str(ymdhms) + '.\n'
#body = body + 'If you did not login at this time, please immediately contact ' + str(settings.SSOP_ADMIN_EMAIL)
#body = body + '\n\nYou can also direct message @Kirk Holub on https://oar-gsl.slack.com'
body = settings.USER_HAS_AUTHENTICATED_BODY
body = body.replace( 'firstname', firstname )
body = body.replace( 'ymdhms', ymdhms )
Expand All @@ -1402,15 +1384,11 @@ def user_has_authenticated_sendemail(**kwargs):
if settings.DEBUG:
msg = "DEBUG -- running: send_mail(subject, body, fromaddr, toaddr, fail_silently=False)"
msg = msg + ' -- toaddr: ' + str(toaddr)
logger.debug(msg)
send_mail(subject, body, fromaddr, toaddr, fail_silently=False)
else:
send_mail(subject, body, fromaddr, toaddr, fail_silently=False)
except SMTPException as e:
now = datetime.datetime.utcnow()
msg = str(now) + ":User has logged in email failed:" + str(email) + ":post_auth_user_has_authenticated:" + str(e)
logger.info(msg)
except ConnectionRefusedError as e:
msg = msg + ' -- fromaddr: ' + str(fromaddr)
msg = msg + ' -- subject: ' + str(subject)
logger.info(msg)
send_mail(subject, body, fromaddr, toaddr, fail_silently=False)
except Exception as e:
now = datetime.datetime.utcnow()
msg = str(now) + ":User has logged in email failed:" + str(email) + ":post_auth_user_has_authenticated:" + str(e)
logger.info(msg)
Expand All @@ -1430,3 +1408,12 @@ def fullname(self):

def mode(self):
return self.current_state

def colors(self):
if 'normal' in str(self.mode()).lower():
# light green used by NCO
colors = ('black', '#e7f4e4')
else:
colors = ('white', 'red')
return colors

Loading

0 comments on commit 50ab23e

Please sign in to comment.