Exemple #1
0
def create_new_user(data):
    """Create a new user.

    :param dict data: the data for the user to be created.
    :returns: an SQLAlchemy model object representing the user.

    """
    user = User()
    user.salt = h.generate_salt()
    user.password = unicode(
        h.encrypt_password(data['password'], str(user.salt)))
    user.username = h.normalize(data['username'])
    user.first_name = h.normalize(data['first_name'])
    user.last_name = h.normalize(data['last_name'])
    user.email = h.normalize(data['email'])
    user.affiliation = h.normalize(data['affiliation'])
    user.role = h.normalize(data['role'])
    user.markup_language = h.normalize(data['markup_language'])
    user.page_content = h.normalize(data['page_content'])
    user.html = h.get_HTML_from_contents(user.page_content,
                                         user.markup_language)

    # Many-to-One Data: input and output orthographies
    if data['input_orthography']:
        user.input_orthography = data['input_orthography']
    if data['output_orthography']:
        user.output_orthography = data['output_orthography']

    # OLD-generated Data
    user.datetime_modified = datetime.datetime.utcnow()

    # Create the user's directory
    h.create_user_directory(user)

    return user
Exemple #2
0
def create_new_user(data):
    """Create a new user.

    :param dict data: the data for the user to be created.
    :returns: an SQLAlchemy model object representing the user.

    """
    user = User()
    user.salt = h.generate_salt()
    user.password = unicode(h.encrypt_password(data['password'], str(user.salt)))
    user.username = h.normalize(data['username'])
    user.first_name = h.normalize(data['first_name'])
    user.last_name = h.normalize(data['last_name'])
    user.email = h.normalize(data['email'])
    user.affiliation = h.normalize(data['affiliation'])
    user.role = h.normalize(data['role'])
    user.markup_language = h.normalize(data['markup_language'])
    user.page_content = h.normalize(data['page_content'])
    user.html = h.get_HTML_from_contents(user.page_content, user.markup_language)

    # Many-to-One Data: input and output orthographies
    if data['input_orthography']:
        user.input_orthography= data['input_orthography']
    if data['output_orthography']:
        user.output_orthography = data['output_orthography']

    # OLD-generated Data
    user.datetime_modified = datetime.datetime.utcnow()

    # Create the user's directory
    h.create_user_directory(user)

    return user
Exemple #3
0
def update_user(user, data):
    """Update a user.

    :param user: the user model to be updated.
    :param dict data: representation of the updated user.
    :returns: the updated user model or, if ``changed`` has not been set
        to ``True``, ``False``.

    """
    changed = False

    # Unicode Data
    changed = user.set_attr('first_name', h.normalize(data['first_name']),
                            changed)
    changed = user.set_attr('last_name', h.normalize(data['last_name']),
                            changed)
    changed = user.set_attr('email', h.normalize(data['email']), changed)
    changed = user.set_attr('affiliation', h.normalize(data['affiliation']),
                            changed)
    changed = user.set_attr('role', h.normalize(data['role']), changed)
    changed = user.set_attr('page_content', h.normalize(data['page_content']),
                            changed)
    changed = user.set_attr('markup_language',
                            h.normalize(data['markup_language']), changed)
    changed = user.set_attr(
        'html',
        h.get_HTML_from_contents(user.page_content, user.markup_language),
        changed)

    # username and password need special treatment: a value of None means that
    # these should not be updated.
    if data['password'] is not None:
        changed = user.set_attr(
            'password',
            unicode(h.encrypt_password(data['password'], str(user.salt))),
            changed)
    if data['username'] is not None:
        username = h.normalize(data['username'])
        if username != user.username:
            h.rename_user_directory(user.username, username)
        changed = user.set_attr('username', username, changed)

    # Many-to-One Data
    changed = user.set_attr('input_orthography', data['input_orthography'],
                            changed)
    changed = user.set_attr('output_orthography', data['output_orthography'],
                            changed)

    if changed:
        user.datetime_modified = datetime.datetime.utcnow()
        return user
    return changed
Exemple #4
0
    def authenticate(self):
        """Session-based authentication.

        :URL: ``POST /login/authenticate``
        :request body: A JSON object with ``"username"`` and ``"password"``
            string values
        :returns: ``{"authenticated": True}`` on success, an error dictionary on
            failure.

        """
        try:
            schema = LoginSchema()
            values = json.loads(unicode(request.body, request.charset))
            result = schema.to_python(values)
            username = result['username']
            user_from_username = Session.query(User).filter(
                User.username == username).first()
            if user_from_username:
                salt = user_from_username.salt
                password = unicode(
                    h.encrypt_password(result['password'], str(salt)))
                user = Session.query(User).filter(
                    User.username == username).filter(
                        User.password == password).first()
                if user:
                    session['user'] = user
                    session.save()
                    home_page = Session.query(Page).filter(
                        Page.name == u'home').first()
                    return {
                        'authenticated': True,
                        'user': user,
                        'homepage': home_page
                    }
                else:
                    response.status_int = 401
                    return {
                        'error':
                        u'The username and password provided are not valid.'
                    }
            else:
                response.status_int = 401
                return {
                    'error':
                    u'The username and password provided are not valid.'
                }
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Exemple #5
0
    def email_reset_password(self):
        """Reset the user's password and email them a new one.

        :URL: ``POST /login/email_reset_password``
        :request body: a JSON object with a ``"username"`` attribute.
        :returns: a dictionary with ``'valid_username'`` and ``'password_reset'``
            keys whose values are booleans.

        """
        try:
            schema = PasswordResetSchema()
            values = json.loads(unicode(request.body, request.charset))
            result = schema.to_python(values)
            user = Session.query(User).filter(
                User.username == result['username']).first()
            if user:
                try:
                    new_password = h.generate_password()
                    h.send_password_reset_email_to(user,
                                                   new_password,
                                                   config=config)
                    user.password = unicode(
                        h.encrypt_password(new_password, str(user.salt)))
                    Session.add(user)
                    Session.commit()
                    if os.path.split(config['__file__'])[-1] == 'test.ini':
                        return {
                            'valid_username': True,
                            'password_reset': True,
                            'new_password': new_password
                        }
                    else:
                        return {'valid_username': True, 'password_reset': True}
                except:  # socket.error was too specific ...
                    response.status_int = 500
                    return {'error': 'The server is unable to send email.'}
            else:
                response.status_int = 400
                return {'error': 'The username provided is not valid.'}
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Exemple #6
0
    def authenticate(self):
        """Session-based authentication.

        :URL: ``POST /login/authenticate``
        :request body: A JSON object with ``"username"`` and ``"password"``
            string values
        :returns: ``{"authenticated": True}`` on success, an error dictionary on
            failure.

        """
        try:
            schema = LoginSchema()
            values = json.loads(unicode(request.body, request.charset))
            result = schema.to_python(values)
            username = result['username']
            user_from_username = Session.query(User).filter(User.username==username).first()
            if user_from_username:
                salt = user_from_username.salt
                password = unicode(h.encrypt_password(result['password'], str(salt)))
                user = Session.query(User).filter(User.username==username).filter(
                    User.password==password).first()
                if user:
                    session['user'] = user
                    session.save()
                    home_page = Session.query(Page).filter(
                        Page.name==u'home').first()
                    return {
                        'authenticated': True,
                        'user': user,
                        'homepage': home_page
                    }
                else:
                    response.status_int = 401
                    return {'error':
                        u'The username and password provided are not valid.'}
            else:
                response.status_int = 401
                return {'error': u'The username and password provided are not valid.'}
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Exemple #7
0
def update_user(user, data):
    """Update a user.

    :param user: the user model to be updated.
    :param dict data: representation of the updated user.
    :returns: the updated user model or, if ``changed`` has not been set
        to ``True``, ``False``.

    """
    changed = False

    # Unicode Data
    changed = user.set_attr('first_name', h.normalize(data['first_name']), changed)
    changed = user.set_attr('last_name', h.normalize(data['last_name']), changed)
    changed = user.set_attr('email', h.normalize(data['email']), changed)
    changed = user.set_attr('affiliation', h.normalize(data['affiliation']), changed)
    changed = user.set_attr('role', h.normalize(data['role']), changed)
    changed = user.set_attr('page_content', h.normalize(data['page_content']), changed)
    changed = user.set_attr('markup_language', h.normalize(data['markup_language']), changed)
    changed = user.set_attr('html', h.get_HTML_from_contents(user.page_content, user.markup_language), changed)

    # username and password need special treatment: a value of None means that
    # these should not be updated.
    if data['password'] is not None:
        changed = user.set_attr('password',
                    unicode(h.encrypt_password(data['password'], str(user.salt))), changed)
    if data['username'] is not None:
        username = h.normalize(data['username'])
        if username != user.username:
            h.rename_user_directory(user.username, username)
        changed = user.set_attr('username', username, changed)

    # Many-to-One Data
    changed = user.set_attr('input_orthography', data['input_orthography'], changed)
    changed = user.set_attr('output_orthography', data['output_orthography'], changed)

    if changed:
        user.datetime_modified = datetime.datetime.utcnow()
        return user
    return changed
Exemple #8
0
    def email_reset_password(self):
        """Reset the user's password and email them a new one.

        :URL: ``POST /login/email_reset_password``
        :request body: a JSON object with a ``"username"`` attribute.
        :returns: a dictionary with ``'valid_username'`` and ``'password_reset'``
            keys whose values are booleans.

        """
        try:
            schema = PasswordResetSchema()
            values = json.loads(unicode(request.body, request.charset))
            result = schema.to_python(values)
            user = Session.query(User).filter(User.username==result['username']).first()
            if user:
                try:
                    new_password = h.generate_password()
                    h.send_password_reset_email_to(user, new_password, config=config)
                    user.password = unicode(h.encrypt_password(new_password, str(user.salt)))
                    Session.add(user)
                    Session.commit()
                    if os.path.split(config['__file__'])[-1] == 'test.ini':
                        return {'valid_username': True, 'password_reset': True,
                                'new_password': new_password}
                    else:
                        return {'valid_username': True, 'password_reset': True}
                except:     # socket.error was too specific ...
                    response.status_int = 500
                    return {'error': 'The server is unable to send email.'}
            else:
                response.status_int = 400
                return {'error': 'The username provided is not valid.'}
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}