AddUser.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #!/usr/bin/env python3
  2. # Contest Management System - http://cms-dev.github.io/
  3. # Copyright © 2016 Stefano Maggiolo <s.maggiolo@gmail.com>
  4. # Copyright © 2017-2018 Luca Wehrstedt <luca.wehrstedt@gmail.com>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as
  8. # published by the Free Software Foundation, either version 3 of the
  9. # License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """This script creates a new user in the database.
  19. """
  20. # We enable monkey patching to make many libraries gevent-friendly
  21. # (for instance, urllib3, used by requests)
  22. import gevent.monkey
  23. gevent.monkey.patch_all() # noqa
  24. import argparse
  25. import logging
  26. import sys
  27. from sqlalchemy.exc import IntegrityError
  28. from cms import utf8_decoder
  29. from cms.db import SessionGen, User
  30. from cmscommon.crypto import generate_random_password, build_password, \
  31. hash_password
  32. logger = logging.getLogger(__name__)
  33. def add_user(first_name, last_name, username, password, method, is_hashed,
  34. email, timezone, preferred_languages):
  35. logger.info("Creating the user in the database.")
  36. pwd_generated = False
  37. if password is None:
  38. assert not is_hashed
  39. password = generate_random_password()
  40. pwd_generated = True
  41. if is_hashed:
  42. stored_password = build_password(password, method)
  43. else:
  44. stored_password = hash_password(password, method)
  45. if preferred_languages is None:
  46. preferred_languages = []
  47. else:
  48. preferred_languages = list(
  49. lang.strip() for lang in preferred_languages.split(",") if
  50. lang.strip())
  51. user = User(first_name=first_name,
  52. last_name=last_name,
  53. username=username,
  54. password=stored_password,
  55. email=email,
  56. timezone=timezone,
  57. preferred_languages=preferred_languages)
  58. try:
  59. with SessionGen() as session:
  60. session.add(user)
  61. session.commit()
  62. except IntegrityError:
  63. logger.error("A user with the given username already exists.")
  64. return False
  65. logger.info("User added%s. "
  66. "Use AddParticipation to add this user to a contest."
  67. % (" with password %s" % password if pwd_generated else ""))
  68. return True
  69. def main():
  70. """Parse arguments and launch process.
  71. """
  72. parser = argparse.ArgumentParser(description="Add a user to CMS.")
  73. parser.add_argument("first_name", action="store", type=utf8_decoder,
  74. help="given name of the user")
  75. parser.add_argument("last_name", action="store", type=utf8_decoder,
  76. help="family name of the user")
  77. parser.add_argument("username", action="store", type=utf8_decoder,
  78. help="username used to log in")
  79. parser.add_argument("-e", "--email", action="store", type=utf8_decoder,
  80. help="email of the user")
  81. parser.add_argument("-t", "--timezone", action="store", type=utf8_decoder,
  82. help="timezone of the user, e.g. Europe/London")
  83. parser.add_argument("-l", "--languages", action="store", type=utf8_decoder,
  84. help="comma-separated list of preferred languages")
  85. password_group = parser.add_mutually_exclusive_group()
  86. password_group.add_argument(
  87. "-p", "--plaintext-password", action="store", type=utf8_decoder,
  88. help="password of the user in plain text")
  89. password_group.add_argument(
  90. "-H", "--hashed-password", action="store", type=utf8_decoder,
  91. help="password of the user, already hashed using the given algorithm "
  92. "(currently only --bcrypt)")
  93. method_group = parser.add_mutually_exclusive_group()
  94. method_group.add_argument(
  95. "--bcrypt", dest="method", action="store_const", const="bcrypt",
  96. help="whether the password will be stored in bcrypt-hashed format "
  97. "(if omitted it will be stored in plain text)")
  98. args = parser.parse_args()
  99. if args.hashed_password is not None and args.method is None:
  100. parser.error("hashed password given but no method specified")
  101. success = add_user(args.first_name, args.last_name, args.username,
  102. args.plaintext_password or args.hashed_password,
  103. args.method or "plaintext",
  104. args.hashed_password is not None, args.email,
  105. args.timezone, args.languages)
  106. return 0 if success is True else 1
  107. if __name__ == "__main__":
  108. sys.exit(main())