Example #1
0
def add_user(first_name, last_name, username, password, method, is_hashed,
             email, timezone, preferred_languages, overwrite=False):
    logger.info("Creating the user in the database.")
    pwd_generated = False
    if password is None:
        assert not is_hashed
        password = generate_random_password()
        pwd_generated = True
    if is_hashed:
        stored_password = build_password(password, method)
    else:
        stored_password = hash_password(password, method)

    if preferred_languages is None or preferred_languages == "":
        preferred_languages = "[]"
    else:
        preferred_languages = \
            "[" + ",".join("\"" + lang + "\""
                           for lang in preferred_languages.split(",")) + "]"
    user = User(first_name=first_name,
                last_name=last_name,
                username=username,
                password=stored_password,
                email=email,
                timezone=timezone,
                preferred_languages=preferred_languages)

    with SessionGen() as session:
        if overwrite:
            existing_user = session.query(User) \
                .filter(User.username == username).first()
            if existing_user is not None:
                user = existing_user
                user.first_name = first_name
                user.last_name = last_name
                user.username = username
                if not pwd_generated:
                    user.password = stored_password
                else:
                    pwd_generated = False
                user.email = email or user.email
                user.timezone = timezone or user.timezone
                user.preferred_languages = preferred_languages or \
                    user.preferred_languages
        try:
            session.add(user)
            session.commit()
        except IntegrityError:
            logger.error("A user with the given username already exists.")
            return False

    logger.info("User added%s. "
                "Use AddParticipation to add this user to a contest."
                % (" with password %s" % password if pwd_generated else ""))
    return True
Example #2
0
def add_user(first_name, last_name, username, password, email, timezone=None, preferred_languages=None):
    if password is None:
        password = generate_random_password()
    if preferred_languages is None or preferred_languages == "":
        preferred_languages = []
    else:
        preferred_languages = [lang for lang in preferred_languages.split(",")]
    user = User(
        first_name=first_name,
        last_name=last_name,
        username=username,
        password=password,
        email=email,
        timezone=timezone,
        preferred_languages=preferred_languages
    )

    try:
        with SessionGen() as session:
            session.add(user)
            session.commit()
    except IntegrityError:
        return False

    logger.info("Registered user {} with password {}".format(username, password))

    return True
Example #3
0
def add_user(first_name, last_name, username, password, email, timezone,
             preferred_languages):
    logger.info("Creating the user in the database.")
    if password is None:
        password = generate_random_password()
    if preferred_languages is None or preferred_languages == "":
        preferred_languages = "[]"
    else:
        preferred_languages = \
            "[" + ",".join("\"" + lang + "\""
                           for lang in preferred_languages.split(",")) + "]"
    user = User(first_name=first_name,
                last_name=last_name,
                username=username,
                password=password,
                email=email,
                timezone=timezone,
                preferred_languages=preferred_languages)
    try:
        with SessionGen() as session:
            session.add(user)
            session.commit()
    except IntegrityError:
        logger.error("A user with the given username already exists.")
        return False

    logger.info("User added. "
                "Use AddParticipation to add this user to a contest.")
    return True
Example #4
0
    def get_user(self, username):
        """See docstring in class Loader.

        """
        logger.info("Loading parameters for user %s." % username)
        conf = self.users_conf[username]
        assert username == conf['username']

        args = {}

        load(conf, args, "username")

        load(conf, args, "password")
        load(conf, args, "ip")

        load(conf, args, ["first_name", "nome"])
        load(conf, args, ["last_name", "cognome"])

        if "first_name" not in args:
            args["first_name"] = ""
        if "last_name" not in args:
            args["last_name"] = args["username"]

        load(conf, args, ["hidden", "fake"],
             conv=lambda a: a is True or a == "True")

        logger.info("User parameters loaded.")

        return User(**args)
Example #5
0
    def post(self):
        fallback_page = "/users/add"

        try:
            attrs = dict()

            self.get_string(attrs, "first_name")
            self.get_string(attrs, "last_name")
            self.get_string(attrs, "username", empty=None)
            self.get_string(attrs, "password")
            self.get_string(attrs, "email")

            assert attrs.get("username") is not None, \
                "No username specified."

            self.get_string(attrs, "timezone", empty=None)

            self.get_string(attrs, "preferred_languages")

            # Create the user.
            user = User(**attrs)
            self.sql_session.add(user)

        except Exception as error:
            self.application.service.add_notification(
                make_datetime(), "Invalid field(s)", repr(error))
            self.redirect(fallback_page)
            return

        if self.try_commit():
            # Create the user on RWS.
            self.application.service.proxy_service.reinitialize()
            self.redirect("/user/%s" % user.id)
        else:
            self.redirect(fallback_page)
Example #6
0
def add_users(users_info, contest_name=None):
    """
    Add the given users to the database, if they don't exist.
    If contest_name is given and it exists, participations are created
    (for existing users, too).

    Each user info should be a dictionary with the fields:
    username, password. Optionally:
    first_name (default is empty).
    last_name (default is empty).
    hidden (default is false).
    unrestricted (default is false).
    """

    with SessionGen() as session:
        existing_users = session.query(User).all()
        existing_usernames = {user.username: user for user in existing_users}

        # If the contest does not exist, this raises an exception,
        # and participations will not be created.
        try:
            contest = get_contest(session, contest_name)
            participations = session.query(Participation)\
                .filter(Participation.contest_id == contest.id)\
                .all()
            existing_participations = set(participation.user.username
                                          for participation in participations)
        except Exception:
            contest = None
            existing_participations = set()

        for user_info in users_info:
            username = user_info["username"]

            # If this user exists, fetch the User database object.
            # Otherwise, create one.
            if username in existing_usernames:
                user = existing_usernames[username]
            else:
                first_name = user_info.get("first_name", "")
                last_name = user_info.get("last_name", "")
                password = user_info["password"]
                user = User(first_name=unicode(first_name),
                            last_name=unicode(last_name),
                            username=unicode(username),
                            password=unicode(password))
                session.add(user)

            # If the participation does not exist and the contest is given,
            # add it.
            if contest is not None and \
               username not in existing_participations:
                participation = Participation(
                    user=user,
                    contest=contest,
                    hidden=user_info.get("hidden", False),
                    unrestricted=user_info.get("unrestricted", False))
                session.add(participation)
        session.commit()
Example #7
0
    def post(self):
        if not self.contest.allow_registration:
            raise tornado.web.HTTPError(404)

        try:
            first_name = self.get_argument("first_name")
            last_name = self.get_argument("last_name")
            username = self.get_argument("username")
            password = self.get_argument("password")

            if not 1 <= len(first_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(last_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(username) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not re.match(r"^[A-Za-z0-9_-]+$", username):
                raise ValueError()
            if not self.MIN_PASSWORD_LENGTH <= len(password) \
                    <= self.MAX_INPUT_LENGTH:
                raise ValueError()
        except (tornado.web.MissingArgumentError, ValueError):
            raise tornado.web.HTTPError(400)

        # Override password with its hash
        password = hash_password(password)

        # If we have teams, we assume that the 'team' field is mandatory
        if self.sql_session.query(Team).count() > 0:
            try:
                team_code = self.get_argument("team")
                team = self.sql_session.query(Team)\
                           .filter(Team.code == team_code)\
                           .one()
            except (tornado.web.MissingArgumentError, NoResultFound):
                raise tornado.web.HTTPError(400)
        else:
            team = None

        # Check if the username is available
        tot_users = self.sql_session.query(User)\
                        .filter(User.username == username).count()
        if tot_users != 0:
            # HTTP 409: Conflict
            raise tornado.web.HTTPError(409)

        # Store new user and participation
        user = User(first_name, last_name, username, password)
        self.sql_session.add(user)

        participation = Participation(user=user,
                                      contest=self.contest,
                                      team=team)
        self.sql_session.add(participation)

        self.sql_session.commit()

        self.finish(username)
Example #8
0
 def get_user(cls, **kwargs):
     """Create a user"""
     args = {
         "username": unique_unicode_id(),
         "password": "",
         "first_name": unique_unicode_id(),
         "last_name": unique_unicode_id(),
     }
     args.update(kwargs)
     user = User(**args)
     return user
Example #9
0
 def add_user(self, **kwargs):
     """Add a user."""
     args = {
         "username": unique_unicode_id(),
         "password": "",
         "first_name": unique_unicode_id(),
         "last_name": unique_unicode_id(),
     }
     args.update(kwargs)
     user = User(**args)
     self.session.add(user)
     return user
Example #10
0
    def _create_user(self):
        try:
            first_name = self.get_argument("first_name")
            last_name = self.get_argument("last_name")
            username = self.get_argument("username")
            password = self.get_argument("password")
            email = self.get_argument("email")
            if len(email) == 0:
                email = None
            if self.contest.registration_requires_captcha:
                captcha_input = self.get_argument("captcha")
                captcha_input_signature = self.signature(captcha_input)
                captcha_cookie = self.get_secure_cookie("captcha").decode(
                    'utf-8')
                captcha_clear_signature, captcha_username = captcha_cookie.split(
                    '_', 1)

            if not 1 <= len(first_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(last_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(username) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not re.match(r"^[A-Za-z0-9_-]+$", username):
                raise ValueError()
            if not self.MIN_PASSWORD_LENGTH <= len(password) \
                    <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if self.contest.registration_requires_captcha:
                if not re.match(r"^[0-9]+$", captcha_input):
                    raise ValueError()
                if not captcha_input_signature == captcha_clear_signature:
                    raise ValueError()
                if not username == captcha_username:
                    raise ValueError()
        except (tornado_web.MissingArgumentError, ValueError):
            raise tornado_web.HTTPError(400)

        # Override password with its hash
        password = hash_password(password)

        # Check if the username is available
        tot_users = self.sql_session.query(User)\
                        .filter(User.username == username).count()
        if tot_users != 0:
            # HTTP 409: Conflict
            raise tornado_web.HTTPError(409)

        # Store new user
        user = User(first_name, last_name, username, password, email=email)
        self.sql_session.add(user)

        return user
Example #11
0
    def _makeuser(self, username):
        """
        Return a User object for the specified user which can be saved
        to the database.

        username (unicode): the name of the user to generate

        return (User,Participation): database object for the user

        """
        user = self.users[username]

        # The user should never actually use this password, because we set
        # different passwords for each participation.
        udb = User(username=user.username,
                   first_name=user.firstname,
                   last_name=user.lastname,
                   password=build_password(user.password))

        udb.timezone = user.timezone
        udb.preferred_languages = user.primary_statements

        return udb
Example #12
0
    def _makeuser(self, username):
        """
        Return a User object for the specified user which can be saved
        to the database.

        username (unicode): the name of the user to generate

        return (User,Participation): database object for the user

        """
        user = self.users[username]

        # The user should never actually use this password, because we set
        # different passwords for each participation.
        udb = User(username=user.username,
                   first_name=user.firstname,
                   last_name=user.lastname,
                   password=build_password(user.password))

        udb.timezone = user.timezone
        udb.preferred_languages = user.primary_statements

        return udb
Example #13
0
def add_user(contest_id, first_name, last_name, username, password, ip_address,
             email, hidden):
    with SessionGen() as session:
        contest = Contest.get_from_id(contest_id, session)
        user = User(first_name=first_name,
                    last_name=last_name,
                    username=username,
                    password=password,
                    email=email,
                    ip=ip_address,
                    hidden=hidden,
                    contest=contest)
        session.add(user)
        session.commit()
Example #14
0
    def get_users(self):
        users = self.read_users()
        result = []
        for user in users:
            args = {'username': user['username'],
                    'first_name': user.get('name', user['username']),
                    'last_name': user.get('last_name', ''),
                    'email': user.get('email', None)}
            password = user.get('password')
            if password:
                args['password'] = password

            user_obj = User(**args)

            result.append(user_obj)
        return result
Example #15
0
    def get_user(self, username):
        """See docstring in class Loader.

        """
        logger.info("Loading parameters for user %s.", username)
        user = self.users_conf[username]
        args = {}
        args['username'] = user[0]
        args['password'] = user[1]
        args['first_name'] = user[2]
        args['last_name'] = user[3]
        args['hidden'] = (len(user) > 4 and user[4] == '1')

        logger.info("User parameters loaded.")

        return User(**args)
Example #16
0
    def get_user(self):
        """See docstring in class UserLoader."""

        if not os.path.exists(
                os.path.join(os.path.dirname(self.path), "contest.yaml")):
            logger.critical("File missing: \"contest.yaml\"")
            return None

        username = os.path.basename(self.path)
        logger.info("Loading parameters for user %s.", username)

        conf = yaml.safe_load(
            io.open(os.path.join(os.path.dirname(self.path), "contest.yaml"),
                    "rt",
                    encoding="utf-8"))

        args = {}

        conf = load(conf, None, ["users", "utenti"])
        if not conf:
            conf = []
        conf += load_csv(os.path.dirname(self.path))

        for user in conf:
            if user["username"] == username:
                conf = user
                break
        else:
            logger.critical("The specified user cannot be found.")
            return None

        load(conf, args, "username")
        load(conf, args, "password")
        load(conf, args, "level")
        load(conf, args, "school")

        load(conf, args, ["first_name", "nome"])
        load(conf, args, ["last_name", "cognome"])

        if "first_name" not in args:
            args["first_name"] = ""
        if "last_name" not in args:
            args["last_name"] = args["username"]

        logger.info("User parameters loaded.")
        return User(**args)
Example #17
0
    def do_import(self):
        """Get the contest from the Loader and store it."""
        if not self._prepare_db():
            return False

        # Get the contest
        contest, tasks, users = self.loader.get_contest()

        # Get the tasks
        for task in tasks:
            contest.tasks.append(self.loader.get_task(task))

        # Get the users or, if asked, generate them
        if self.user_number is None:
            for user in users:
                contest.users.append(self.loader.get_user(user))
        else:
            logger.info("Generating %s random users." % self.user_number)
            contest.users = [
                User("User %d" % i, "Last name %d" % i, "user%03d" % i)
                for i in xrange(self.user_number)
            ]

        # Apply the modification flags
        if self.zero_time:
            contest.start = datetime.datetime(1970, 1, 1)
            contest.stop = datetime.datetime(1970, 1, 1)
        elif self.test:
            contest.start = datetime.datetime(1970, 1, 1)
            contest.stop = datetime.datetime(2100, 1, 1)

            for user in contest.users:
                user.password = '******'
                user.ip = None

        # Store
        logger.info("Creating contest on the database.")
        with SessionGen() as session:
            session.add(contest)
            session.commit()
            contest_id = contest.id

        logger.info("Import finished (new contest id: %s)." % contest_id)
Example #18
0
    def get_user(self):
        """See docstring in class Loader.

        """

        username = os.path.basename(self.path)
        userdata = None

        # This is not standard Polygon feature, but useful for CMS users
        # we assume contestants.txt contains one line for each user:
        #
        # username;password;first_name;last_name;hidden
        #
        # For example:
        #
        # contestant1;123;Cont;Estant;0
        # jury;1234;Ju;Ry;1

        users_path = os.path.join(os.path.dirname(self.path),
                                  'contestants.txt')
        if os.path.exists(users_path):
            with io.open(users_path, "rt", encoding="utf-8") as users_file:
                for user in users_file.readlines():
                    user = user.strip().split(';')
                    name = user[0].strip()
                    if name == username:
                        userdata = [x.strip() for x in user]

        if userdata is not None:
            logger.info("Loading parameters for user %s.", username)
            args = {}
            args['username'] = userdata[0]
            args['password'] = build_password(userdata[1])
            args['first_name'] = userdata[2]
            args['last_name'] = userdata[3]
            args['hidden'] = (len(userdata) > 4 and userdata[4] == '1')
            logger.info("User parameters loaded.")
            return User(**args)
        else:
            logger.critical("User %s not found in contestants.txt file.",
                            username)
            return None
Example #19
0
    def post(self):
        fallback_page = self.url("users", "add")

        try:
            attrs = dict()

            self.get_string(attrs, "first_name")
            self.get_string(attrs, "last_name")
            self.get_string(attrs, "username", empty=None)

            self.get_int(attrs, "grade")
            self.get_string(attrs, "city_region")
            self.get_string(attrs, "school_name")

            self.get_password(attrs, None, False)

            self.get_string(attrs, "email", empty=None)

            assert attrs.get("username") is not None, \
                "No username specified."

            self.get_string(attrs, "timezone", empty=None)

            self.get_string_list(attrs, "preferred_languages")

            # Create the user.
            user = User(**attrs)
            self.sql_session.add(user)

        except Exception as error:
            self.service.add_notification(make_datetime(), "Invalid field(s)",
                                          repr(error))
            self.redirect(fallback_page)
            return

        if self.try_commit():
            # Create the user on RWS.
            self.service.proxy_service.reinitialize()
            self.redirect(self.url("user", user.id))
        else:
            self.redirect(fallback_page)
Example #20
0
    def get_user(self):
        """See docstring in class UserLoader."""

        if not os.path.exists(os.path.join(os.path.dirname(self.path),
                                           "contest.yaml")):
            logger.critical("File missing: \"contest.yaml\"")
            return None

        username = os.path.basename(self.path)
        logger.info("Loading parameters for user %s.", username)

        conf = load_yaml_from_path(
            os.path.join(os.path.dirname(self.path), "contest.yaml"))

        args = {}

        conf = load(conf, None, ["users", "utenti"])

        for user in conf:
            if user["username"] == username:
                conf = user
                break
        else:
            logger.critical("The specified user cannot be found.")
            return None

        load(conf, args, "username")
        load(conf, args, "password", conv=build_password)

        load(conf, args, ["first_name", "nome"])
        load(conf, args, ["last_name", "cognome"])

        if "first_name" not in args:
            args["first_name"] = ""
        if "last_name" not in args:
            args["last_name"] = args["username"]

        logger.info("User parameters loaded.")

        return User(**args)
Example #21
0
    def _create_user(self):
        try:
            first_name = self.get_argument("first_name")
            last_name = self.get_argument("last_name")
            username = self.get_argument("username")
            password = self.get_argument("password")
            email = self.get_argument("email")
            if len(email) == 0:
                email = None

            if not 1 <= len(first_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(last_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(username) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not re.match(r"^[A-Za-z0-9_-]+$", username):
                raise ValueError()
            if not self.MIN_PASSWORD_LENGTH <= len(password) \
                    <= self.MAX_INPUT_LENGTH:
                raise ValueError()
        except (tornado_web.MissingArgumentError, ValueError):
            raise tornado_web.HTTPError(400)

        # Override password with its hash
        password = hash_password(password)

        # Check if the username is available
        tot_users = self.sql_session.query(User)\
                        .filter(User.username == username).count()
        if tot_users != 0:
            # HTTP 409: Conflict
            raise tornado_web.HTTPError(409)

        # Store new user
        user = User(first_name, last_name, username, password, email=email)
        self.sql_session.add(user)

        return user
Example #22
0
    def get_user(self):

        # due to the terrible AddUser script
        conf_path = os.path.dirname(self.path)
        username = os.path.basename(self.path)

        if not exists(conf_path):
            logger.critical("cannot find user config file")
            return None

        logger.info("loading parameters for user \"%s\"", username)

        conf = load_yaml(conf_path)
        candidates = [u for u in conf['users'] if u['username'] == username]

        if len(candidates) == 0:
            logger.critical("cannot find specified user")
            return None
        if len(candidates) > 1:
            logger.critical("multiple users found with the same name")
            return None

        user_conf = candidates[0]

        # default values
        user_conf.setdefault('first_name', '')
        user_conf.setdefault('last_name', username)

        user = {}

        assign(user, user_conf, 'username')
        assign(user, user_conf, 'first_name')
        assign(user, user_conf, 'last_name')
        assign(user, user_conf, 'password', build_password)

        logger.info("user parameters loaded")

        return User(**user)
Example #23
0
def add_user(first_name, last_name, username, password, method, is_hashed,
             email, timezone, preferred_languages):
    logger.info("Creating the user in the database.")
    pwd_generated = False
    if password is None:
        assert not is_hashed
        password = generate_random_password()
        pwd_generated = True
    if is_hashed:
        stored_password = build_password(password, method)
    else:
        stored_password = hash_password(password, method)

    if preferred_languages is None:
        preferred_languages = []
    else:
        preferred_languages = list(lang.strip()
                                   for lang in preferred_languages.split(",")
                                   if lang.strip())
    user = User(first_name=first_name,
                last_name=last_name,
                username=username,
                password=stored_password,
                email=email,
                timezone=timezone,
                preferred_languages=preferred_languages)
    try:
        with SessionGen() as session:
            session.add(user)
            session.commit()
    except IntegrityError:
        logger.error("A user with the given username already exists.")
        return False

    logger.info("User added%s. "
                "Use AddParticipation to add this user to a contest." %
                (" with password %s" % password if pwd_generated else ""))
    return True
Example #24
0
File: main.py Project: rvisser7/cms
    def post(self):
        if not self.contest.allow_registration:
            raise tornado.web.HTTPError(404)

        try:
            first_name = self.get_argument("first_name")
            last_name = self.get_argument("last_name")
            username = self.get_argument("username")
            password = self.get_argument("password")
            email = self.get_argument("email")
            if len(email) == 0:
                email = None

            if not 1 <= len(first_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(last_name) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not 1 <= len(username) <= self.MAX_INPUT_LENGTH:
                raise ValueError()
            if not re.match(r"^[A-Za-z0-9_-]+$", username):
                raise ValueError()
            if not self.MIN_PASSWORD_LENGTH <= len(password) \
                    <= self.MAX_INPUT_LENGTH:
                raise ValueError()
        except (tornado.web.MissingArgumentError, ValueError):
            raise tornado.web.HTTPError(400)

        # Override password with its hash
        password = hash_password(password)

        # If we have teams, we assume that the 'team' field is mandatory
        if self.sql_session.query(Team).count() > 0:
            try:
                team_code = self.get_argument("team")
                school = self.get_argument("school")

                team = self.sql_session.query(Team)\
                           .filter(Team.code == team_code)\
                           .one()
            except (tornado.web.MissingArgumentError, NoResultFound):
                raise tornado.web.HTTPError(400)
        else:
            team = None
            school = None

        # Check if the username is available
        tot_users = self.sql_session.query(User)\
                        .filter(User.username == username).count()
        if tot_users != 0:
            # HTTP 409: Conflict
            raise tornado.web.HTTPError(409)
	
        # Store new user and participation
        user = User(first_name, last_name, username, password, email=email)
        self.sql_session.add(user)
	
#        # Get contest IDs of all contests which are public
#        f = open('/home/ubuntu/public_contests')
#        public_contests = set()
#        for line in f:
#            digit_contain = False
#            if (line[0] == '#'):
#                continue
#            for c in line:
#                if (48 <= ord(c)) and (ord(c) <= 57):
#                    digit_contain = True
#                    break
#            if digit_contain:
#                public_contests.add(int(line.strip()))
#        f.close()

        # Add participation to all public contests
        for contest in self.sql_session.query(Contest):
#            if (contest.id in public_contests):
            if (contest.allow_registration):
                self.sql_session.add(Participation(user=user, contest=contest, team=team))

        # Make log to add additional school
        if (school != None) and (len(school) > 0):
            f = open('/home/ubuntu/logs/TODO_logs', 'a')
            l = str(datetime.datetime.now())
            l += " ADD SCHOOL REQUEST "
            l += " Username: "******" School: " + school
            f.write(l+'\n')
            f.close()

        self.sql_session.commit()
	
        self.finish(username)
Example #25
0
    def get_user(self):
        """See docstring in class Loader.

        """

        username = os.path.basename(self.path)
        userdata = None

        # Shaker user format (CSV-based):
        #
        # This is not standard Polygon feature, but useful for CMS users
        # we assume contestants.txt contains one line for each user, and
        # a header line, as follow:
        #
        # ...,Prénom,Nom,Pseudo,Mot de passe,...
        # (additionnal columns are accepted, and order isn't important)
        #

        users_path = os.path.join(os.path.dirname(self.path),
                                  'contestants.csv')
        if not os.path.exists(users_path):
            users_path = os.path.join(os.path.dirname(self.path),
                                      '../contestants.csv')
        if not os.path.exists(users_path):
            logger.critical("contestants.csv not found!")
            exit(1)
            return None

        try:
            headers = dict()
            if os.path.exists(users_path):
                with io.open(users_path, "rt", encoding="utf-8") as users_file:
                    reader = unicode_csv_reader(users_file)

                    # Headers
                    headers_list = next(reader)
                    headers = dict(zip(headers_list, range(len(headers_list))))

                    # Content
                    for user in reader:
                        if len(user) == 0:
                            continue
                        name = user[headers['Pseudo']].strip()
                        if name == username:
                            userdata = [x.strip() for x in user]
                            break

            def get_param(param, default=None):
                try:
                    return userdata[headers[param]]
                except KeyError as _:
                    if default is None:
                        raise _
                    return default

            if userdata is not None:
                logger.info("Loading parameters for user %s.", username)
                args = {
                    'username': get_param('Pseudo'),
                    'password': get_param('Mot de passe', ''),
                    'first_name': get_param('Prénom', ''),
                    'last_name': get_param('Nom', '')
                }
                # args['hidden'] = get_param('hidden', False) == '1'

                # Generate a password if none is defined
                if len(args['password']) == 0:
                    args['password'] = random_password()

                # Build an auth string from the password
                args['password'] = build_password(args['password'])

                logger.info("User parameters loaded.")
                return User(**args)
            else:
                logger.critical("User %s not found in contestants.csv file.",
                                username)
                exit(1)
                return None
        except KeyError as e:
            logger.critical(
                "contestants.csv is ill-formed: column %s not found!", e)
            exit(1)
            return None
Example #26
0
    def user_handler(self):
        if local.data['action'] == 'new':
            try:
                username = local.data['username']
                password = local.data['password']
                email = local.data['email'].lower()
                firstname = local.data['firstname']
                lastname = local.data['lastname']
                recaptcha_response = local.data['recaptcha_response']
            except KeyError:
                logger.warning('Missing parameters')
                return 'Bad request'

            # Check captcha
            r = requests.post(
                "https://www.google.com/recaptcha/api/siteverify",
                data={'secret': config.get("core", "recaptcha_secret_key"),
                      'response': recaptcha_response}, #, 'remoteip': ''},
                verify=False)
            try:
                assert r.json()["success"] == True
            except:
                return "Bad request"

            token = self.hashpw(password)

            err = self.check_user(username)
            if err is not None:
                return err
            err = self.check_email(email)
            if err is not None:
                return err

            user = User(
                first_name=firstname,
                last_name=lastname,
                username=username,
                password=token,
                email=email
            )
            social_user = SocialUser(
                access_level=6,
                registration_time=make_datetime()
            )
            contest = local.session.query(Contest)\
                .filter(Contest.id == self.CONTEST_ID)\
                .first()
            participation = Participation(
                user=user,
                contest=contest
            )

            social_user.user = user

            if 'institute' in local.data:
                social_user.institute_id = int(local.data['institute'])

            try:
                local.session.add(user)
                local.session.add(social_user)
                local.session.add(participation)
                local.session.commit()
            except IntegrityError:
                return 'User already exists'
        elif local.data['action'] == 'login':
            try:
                username = local.data['username']
                password = local.data['password']
            except KeyError:
                logger.warning('Missing parameter')
                return 'Bad request'

            token = self.hashpw(password)

            participation = self.get_participation(username, token)
            if participation is None:
                return 'login.error'
            else:
                user = participation.user
                local.resp['token'] = token
                local.resp['user'] = self.get_user_info(user)
        elif local.data['action'] == 'get':
            user = local.session.query(User)\
                .filter(User.username == local.data['username']).first()
            if user is None:
                return 'Not found'
            local.resp = self.get_user_info(user)
            # Append scores of tried tasks
            local.resp['scores'] = []
            for ts in user.social_user.taskscores:
                taskinfo = dict()
                taskinfo['name'] = ts.task.name
                taskinfo['score'] = ts.score
                taskinfo['title'] = ts.task.title
                local.resp['scores'].append(taskinfo)
        elif local.data['action'] == 'list':
            query = local.session.query(User)\
                .join(SocialUser)\
                .order_by(desc(SocialUser.score))\
                .order_by(desc(SocialUser.id))
            if 'institute' in local.data:
                query = query\
                    .filter(SocialUser.institute_id == local.data['institute'])
            users, local.resp['num'] = self.sliced_query(query)
            local.resp['users'] = map(self.get_user_info, users)
        elif local.data['action'] == 'update':
            if local.user is None:
                return 'Unauthorized'
            if 'institute' in local.data and \
               local.data['institute'] is not None:
                local.user.institute_id = int(local.data['institute'])
            if 'email' in local.data and \
               local.data['email'] != '' and \
               local.user.email != local.data['email']:
                err = self.check_email(local.data['email'])
                if err is not None:
                    return err
                local.user.email = local.data['email']
            if 'old_password' in local.data and \
               local.data['old_password'] != '':
                old_token = self.hashpw(local.data['old_password'])
                if local.user.password != old_token:
                    return 'Wrong password'
                if len(local.data['password']) < 5:
                    return 'Password\'s too short'
                new_token = self.hashpw(local.data['password'])
                local.user.password = new_token
                local.resp['token'] = new_token
            local.session.commit()
        else:
            return 'Bad request'
Example #27
0
    def post(self):
        fallback_page = self.url("users", "import")

        r_params = self.render_params()
        action = self.get_body_argument('action', 'upload')

        if action == 'upload':
            ignore_existing = self.get_body_argument('ignore_existing', False)
            generate_passwords = self.get_body_argument(
                'generate_passwords', False)
            ignored = 0
            try:
                user_csv = self.request.files["users_csv"][0]
                users = CsvUserLoader(None, None, user_csv['body']).get_users()
                processed_users = []
                for user in users:
                    if generate_passwords or callable(user.password):
                        user.password = None
                    db_user = self.sql_session.query(User).filter_by(
                        username=user.username).first()
                    if db_user:
                        if ignore_existing:
                            if db_user.password:
                                db_user.password = '******'
                            processed_users.append((False, db_user))
                            ignored += 1
                        else:
                            self.application.service.add_notification(
                                make_datetime(), 'Import failed',
                                'User "%s" already exists' % user.username)
                            self.redirect(fallback_page)
                            return
                    else:
                        processed_users.append((True, user))

                if ignored:
                    self.application.service.add_notification(
                        make_datetime(), "User exists",
                        '%d users already exist, ignored' % ignored)
                r_params['users'] = processed_users
                self.render("users_import_preview.html", **r_params)
                return
            except Exception as error:
                self.application.service.add_notification(
                    make_datetime(), "Bad CSV file", repr(error))
                self.redirect(fallback_page)
                return
        elif action == 'save':
            usernames = self.get_body_arguments('username', False)
            first_names = self.get_body_arguments('first_name', False)
            last_names = self.get_body_arguments('last_name', False)
            passwords = self.get_body_arguments('password', False)
            emails = self.get_body_arguments('email', False)
            for i in range(len(usernames)):
                args = {
                    'username': usernames[i],
                    'first_name': first_names[i],
                    'last_name': last_names[i],
                    'email': emails[i],
                }
                if passwords[i]:
                    args['password'] = passwords[i]
                else:
                    args['password'] = crypto.generate_random_password()
                args['password'] = crypto.hash_password(args['password'],
                                                        method='plaintext')
                user = User(**args)
                self.sql_session.add(user)
            if self.try_commit():
                # Create the user on RWS.
                self.application.service.proxy_service.reinitialize()
                self.redirect(self.url("users"))
                return
            else:
                self.redirect(fallback_page)
                return
        self.redirect(fallback_page)
Example #28
0
    def post(self):
        if not self.contest.online_registration:
            raise tornado.web.HTTPError(404)
        fail_redirect = lambda msg: self.redirect("/register?register_error=" +
                                                  escape.url_escape(msg))

        attrs = dict()
        attrs['password'] = self.get_argument("password", "")
        attrs['first_name'] = self.get_argument("first_name", "").strip()
        attrs['last_name'] = self.get_argument("last_name", "").strip()
        attrs['email'] = self.get_argument("email", "").strip()
        attrs['city'] = self.get_argument("city", "").strip()
        attrs['school'] = self.get_argument("school", "").strip()
        attrs['username'] = self.get_argument("email", "").strip()

        if len(attrs['username']) < 3:
            fail_redirect('El usuario tiene que tener al menos 3 caracteres.')
            return
        if len(attrs['password']) < 3:
            fail_redirect('La clave tiene que tener al menos 3 caracteres.')
            return
        if not re.match(r"[A-Za-z0-9]*$", attrs['password']):
            fail_redirect('La clave sólo puede tener letras y números.')
            return
        if len(attrs['first_name']) < 3:
            fail_redirect('El nombre tiene que tener al menos 3 caracteres.')
            return
        if len(attrs['last_name']) < 3:
            fail_redirect('El apellido tiene que tener al menos 3 caracteres.')
            return
        if not re.match(r"([^@|\s]+@[^@]+\.[^@|\s]+)", attrs['email']):
            fail_redirect('Email invalido.')
            return
        if len(attrs['city']) < 3:
            fail_redirect('La ciudad tiene que tener al menos 3 caracteres.')
            return
        if len(attrs['school']) < 3:
            fail_redirect('La escuela tiene que tener al menos 3 caracteres.')
            return

        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': self.contest.captcha_server_code,
            'response': self.get_argument("g-recaptcha-response", ""),
            'remoteip': self.request.remote_ip
        }

        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        captcha = json.load(response)['success']
        if not captcha:
            fail_redirect('Por favor, vuelva a verificar el captcha.')
            return

        try:
            user = self.sql_session.query(User)\
                .filter(User.username == attrs['username'])\
                .first()
            if user is not None:
                fail_redirect('El nombre de usuario ya existe.')
                return
            user = self.sql_session.query(User)\
                .filter(User.email == attrs['email'])\
                .first()
            if user is not None:
                fail_redirect(
                    'El email ya esta asociado a una cuenta existente.')
                return
        except Exception as error:
            fail_redirect("Error verificando usuario.")
            return

        code = uuid.uuid4().hex
        attrs['activation_code'] = code
        attrs['activation_expire'] = datetime.now() + timedelta(days=3)

        self.sql_session.query(User)\
                .filter(User.activation_expire < datetime.now())\
                .delete()
        try:
            # Create the user.
            user = User(**attrs)
            self.sql_session.add(user)
            self.sql_session.commit()
            send_confirmation_code(self.contest.gmail_sender,
                                   self.contest.gmail_password, attrs,
                                   self.request.host)
        except Exception as error:
            fail_redirect("Error creando usuario.")
        else:
            # Create the user on RWS.
            self.application.service.proxy_service.reinitialize()
            self.redirect("/?msg=" + escape.url_escape(
                "Un correo electrónico fue enviado al email conteniendo el link para activar la cuenta."
            ))
Example #29
0
    def user_handler(self):
        if local.data['action'] == 'new':
            try:
                username = local.data['username']
                password = local.data['password']
                email = local.data['email']
                firstname = local.data['firstname']
                lastname = local.data['lastname']
                institute = int(local.data['institute'])
            except KeyError:
                logger.warning('Missing parameters')
                return 'Bad request'

            token = self.hashpw(password)

            err = self.check_user(username)
            if err is not None:
                return err
            err = self.check_email(email)
            if err is not None:
                return err

            user = User(
                first_name=firstname,
                last_name=lastname,
                username=username,
                password=token,
                email=email,
                access_level=6,
                registration_time=make_datetime()
            )
            user.institute_id = institute
            try:
                local.session.add(user)
                local.session.commit()
            except IntegrityError:
                return 'signup.user_exists'
        elif local.data['action'] == 'login':
            try:
                username = local.data['username']
                password = local.data['password']
            except KeyError:
                logger.warning('Missing parameter')
                return 'Bad request'

            token = self.hashpw(password)

            user = self.get_user(username, token)
            if user is None:
                return 'login.error'
            else:
                local.resp['token'] = token
                local.resp['user'] = self.get_user_info(user)
        elif local.data['action'] == 'get':
            user = local.session.query(User)\
                .filter(User.username == local.data['username']).first()
            if user is None:
                return 'Not found'
            local.resp = self.get_user_info(user)
            # Append scores of tried tasks
            local.resp['scores'] = []
            for ts in user.taskscores:
                taskinfo = dict()
                taskinfo['name'] = ts.task.name
                taskinfo['score'] = ts.score
                taskinfo['title'] = ts.task.title
                local.resp['scores'].append(taskinfo)
        elif local.data['action'] == 'list':
            query = local.session.query(User)\
                .filter(User.hidden == False)\
                .order_by(desc(User.score))\
                .order_by(desc(User.id))
            if 'institute' in local.data:
                query = query\
                    .filter(User.institute_id == local.data['institute'])
            users, local.resp['num'] = self.sliced_query(query)
            local.resp['users'] = map(self.get_user_info, users)
        elif local.data['action'] == 'update':
            if local.user is None:
                return 'Unauthorized'
            if 'institute' in local.data and \
               local.data['institute'] is not None:
                local.user.institute_id = int(local.data['institute'])
            if 'email' in local.data and \
               local.data['email'] != '' and \
               local.user.email != local.data['email']:
                err = self.check_email(local.data['email'])
                if err is not None:
                    return err
                local.user.email = local.data['email']
            if 'old_password' in local.data and \
               local.data['old_password'] != '':
                old_token = self.hashpw(local.data['old_password'])
                if local.user.password != old_token:
                    return 'Wrong password'
                if len(local.data['password']) < 5:
                    return 'Password\'s too short'
                new_token = self.hashpw(local.data['password'])
                local.user.password = new_token
                local.resp['token'] = new_token
            local.session.commit()
        else:
            return 'Bad request'
Example #30
0
    def user_handler(self):
        if local.data["action"] == "new":
            try:
                username = local.data["username"]
                password = local.data["password"]
                email = local.data["email"]
                firstname = local.data["firstname"]
                lastname = local.data["lastname"]
                institute = int(local.data["institute"])
            except KeyError:
                logger.warning("Missing parameters")
                return "Bad request"

            token = self.hashpw(password)

            err = self.check_user(username)
            if err is not None:
                return err
            err = self.check_email(email)
            if err is not None:
                return err

            user = User(
                first_name=firstname,
                last_name=lastname,
                username=username,
                password=token,
                email=email,
                access_level=6,
                registration_time=make_datetime(),
            )
            user.institute_id = institute
            try:
                local.session.add(user)
                local.session.commit()
            except IntegrityError:
                return "signup.user_exists"
        elif local.data["action"] == "login":
            try:
                username = local.data["username"]
                password = local.data["password"]
            except KeyError:
                logger.warning("Missing parameter")
                return "Bad request"

            token = self.hashpw(password)

            user = self.get_user(username, token)
            if user is None:
                return "login.error"
            else:
                local.resp["token"] = token
                local.resp["user"] = self.get_user_info(user)
        elif local.data["action"] == "get":
            user = local.session.query(User).filter(User.username == local.data["username"]).first()
            if user is None:
                return "Not found"
            local.resp = self.get_user_info(user)
            # Append scores of tried tasks
            local.resp["scores"] = []
            for ts in user.taskscores:
                taskinfo = dict()
                taskinfo["name"] = ts.task.name
                taskinfo["score"] = ts.score
                taskinfo["title"] = ts.task.title
                local.resp["scores"].append(taskinfo)
        elif local.data["action"] == "list":
            query = (
                local.session.query(User)
                .filter(User.hidden == False)
                .order_by(desc(User.score))
                .order_by(desc(User.id))
            )
            if "institute" in local.data:
                query = query.filter(User.institute_id == local.data["institute"])
            users, local.resp["num"] = self.sliced_query(query)
            local.resp["users"] = map(self.get_user_info, users)
        elif local.data["action"] == "update":
            if local.user is None:
                return "Unauthorized"
            if "institute" in local.data and local.data["institute"] is not None:
                local.user.institute_id = int(local.data["institute"])
            if "email" in local.data and local.data["email"] != "" and local.user.email != local.data["email"]:
                err = self.check_email(local.data["email"])
                if err is not None:
                    return err
                local.user.email = local.data["email"]
            if "old_password" in local.data and local.data["old_password"] != "":
                old_token = self.hashpw(local.data["old_password"])
                if local.user.password != old_token:
                    return "Wrong password"
                if len(local.data["password"]) < 5:
                    return "Password's too short"
                new_token = self.hashpw(local.data["password"])
                local.user.password = new_token
                local.resp["token"] = new_token
            local.session.commit()
        else:
            return "Bad request"
Example #31
0
def load_participations(path):
    logger.info("Loading...")
    with open(path, 'r') as io:
        data = json.load(io)

    participations = data['participations']
    with SessionGen() as session:
        for entry in participations:
            logger.info('Loading: %s' % (entry))
            contest = Contest.get_from_id(entry['contest_id'], session)
            if contest is None:
                logger.error("  Contest ID %d not found" %
                             (entry['contest_id']))
                session.rollback()
                return False

            userdata = entry['user']
            user = session.query(User).filter(
                User.username == userdata['username']).first()
            if user is None:
                user = User(username=userdata['username'],
                            first_name=userdata['first_name'],
                            last_name=userdata['last_name'],
                            password=build_password(
                                generate_random_password()))
                logger.info('  Creating new user: %s' % (user.username))
                session.add(user)
            else:
                logger.info('  Using existing user: %s (id=%d)' %
                            (user.username, user.id))

            if 'plaintext_password' in userdata:
                logger.info('  * password')
                user.password = build_password(userdata['plaintext_password'],
                                               'plaintext')

            if 'first_name' in userdata:
                logger.info('  * first_name: %s' % (userdata['first_name']))
                user.first_name = userdata['first_name']
            if 'last_name' in userdata:
                logger.info('  * last_name: %s' % (userdata['last_name']))
                user.last_name = userdata['last_name']

            participation = session.query(Participation).join(
                Participation.user).filter(
                    Participation.contest == contest).filter(
                        User.username == user.username).first()
            if participation is None:
                participation = Participation(user=user, contest=contest)
                logger.info(
                    '  Creating new participation for contest_id=%d user=%s' %
                    (contest.id, user.username))
                session.add(participation)
            else:
                logger.info(
                    '  Updating participation: id=%d contest_id=%d user=%s' %
                    (participation.id, participation.contest_id,
                     participation.user.username))

            if 'plaintext_password' in entry:
                logger.info('  * plaintext_password')
                participation.password = build_password(
                    entry['plaintext_password'], 'plaintext')
            if 'ip' in entry:
                logger.info('  * ip: %s' % (entry['ip']))
                participation.ip = [ipaddress.ip_network(entry['ip'])]
            if 'delay_time' in entry:
                logger.info('  * delay_time: %d' % (entry['delay_time']))
                participation.delay_time = datetime.timedelta(
                    seconds=entry['delay_time'])
            if 'extra_time' in entry:
                logger.info('  * extra_time: %d' % (entry['extra_time']))
                participation.extra_time = datetime.timedelta(
                    seconds=entry['extra_time'])
            if 'hidden' in entry:
                logger.info('  * hidden: %s' % (entry['hidden']))
                participation.hidden = entry['hidden']
            if 'unrestricted' in entry:
                logger.info('  * unrestricted: %s' % (entry['unrestricted']))
                participation.unrestricted = entry['unrestricted']

            if 'team' in userdata:
                team = session.query(Team).filter(
                    Team.code == userdata['team']['code']).first()
                if team is None:
                    team = Team(code=userdata['team']['code'],
                                name=userdata['team']['name'])
                    logger.info('  Creating new team: %s' % (team.code))
                    session.add(team)
                else:
                    logger.info('  Using existing team: %s' % (team.code))
                if 'name' in userdata['team']:
                    logger.info('  * name: %s' % (userdata['team']['name']))
                    team.name = userdata['team']['name']
                participation.team = team

        session.commit()

    logger.info("Done.")
    return True