AddAdmin.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python3
  2. # Contest Management System - http://cms-dev.github.io/
  3. # Copyright © 2015-2016 Stefano Maggiolo <s.maggiolo@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. """This script creates a new admin in the database.
  18. """
  19. # We enable monkey patching to make many libraries gevent-friendly
  20. # (for instance, urllib3, used by requests)
  21. import gevent.monkey
  22. gevent.monkey.patch_all() # noqa
  23. import argparse
  24. import logging
  25. import sys
  26. from sqlalchemy.exc import IntegrityError
  27. from cms import utf8_decoder
  28. from cms.db import Admin, SessionGen
  29. from cmscommon.crypto import generate_random_password, hash_password
  30. logger = logging.getLogger(__name__)
  31. def add_admin(username, password=None):
  32. logger.info("Creating the admin on the database.")
  33. if password is None:
  34. password = generate_random_password()
  35. admin = Admin(username=username,
  36. authentication=hash_password(password),
  37. name=username,
  38. permission_all=True)
  39. try:
  40. with SessionGen() as session:
  41. session.add(admin)
  42. session.commit()
  43. except IntegrityError:
  44. logger.error("An admin with the given username already exists.")
  45. return False
  46. logger.info("Admin with complete access added. "
  47. "Login with username %s and password %s",
  48. username, password)
  49. return True
  50. def main():
  51. """Parse arguments and launch process.
  52. """
  53. parser = argparse.ArgumentParser(description="Add an admin to CMS.")
  54. parser.add_argument("username", action="store", type=utf8_decoder,
  55. nargs=1)
  56. parser.add_argument("-p", "--password", action="store", type=utf8_decoder)
  57. args = parser.parse_args()
  58. success = add_admin(args.username[0], args.password)
  59. return 0 if success is True else 1
  60. if __name__ == "__main__":
  61. sys.exit(main())