1
0

api_key_expire_mail.py 2.7 KB

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