1
0

api_key_expire_mail.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import os
  4. import argparse
  5. from datetime import datetime, timedelta
  6. from sqlalchemy.exc import SQLAlchemyError
  7. import pagure.config
  8. import pagure.lib
  9. import pagure.lib.model as model
  10. if 'PAGURE_CONFIG' not in os.environ \
  11. and os.path.exists('/etc/pagure/pagure.cfg'):
  12. print('Using configuration file `/etc/pagure/pagure.cfg`')
  13. os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg'
  14. _config = pagure.config.reload_config()
  15. def main(check=False, debug=False):
  16. ''' The function that actually sends the email
  17. in case the expiration date is near'''
  18. current_time = datetime.utcnow()
  19. day_diff_for_mail = [10, 5, 1]
  20. email_dates = [email_day.date() for email_day in \
  21. [current_time + timedelta(days=i) for i in day_diff_for_mail]]
  22. session = pagure.lib.create_session(_config['DB_URL'])
  23. tokens = session.query(model.Token).all()
  24. for token in tokens:
  25. if debug:
  26. print(token.id, token.expiration.date())
  27. if token.expiration.date() in email_dates:
  28. user = token.user
  29. username = user.fullname or user.username
  30. user_email = user.default_email
  31. project = token.project
  32. days_left = token.expiration.day - datetime.utcnow().day
  33. subject = 'Pagure API key expiration date is near!'
  34. text = '''Hi %s, \nYour Pagure API key for the project %s will expire
  35. in %s day(s). Please get a new key for non-interrupted service. \n
  36. Thanks, \nYour Pagure Admin. ''' % (username, project.name, days_left)
  37. if not check:
  38. msg = pagure.lib.notify.send_email(text, subject, user_email)
  39. else:
  40. print('Sending email to %s (%s) about key: %s' % (
  41. username, user_emailk, token.id))
  42. if debug:
  43. print('Sent mail to %s' % username)
  44. session.remove()
  45. if debug:
  46. print('Done')
  47. if __name__ == '__main__':
  48. parser = argparse.ArgumentParser(
  49. description='Script to send email before the api token expires')
  50. parser.add_argument(
  51. '--check', dest='check', action='store_true', default=False,
  52. help='Print the some output but does not send any email')
  53. parser.add_argument(
  54. '--debug', dest='debug', action='store_true', default=False,
  55. help='Print the debugging output')
  56. args = parser.parse_args()
  57. main(debug=args.debug)