def setup(self):
     now = datetime.utcnow()
     super(TestUsersUpdate, self).setup()
     with self.app.app_context():
         user = User(
             id=123,
             email_address="*****@*****.**",
             name="my name",
             password=encryption.hashpw("my long password"),
             active=True,
             role='buyer',
             created_at=now,
             updated_at=now,
             password_changed_at=now
         )
         supplier = Supplier(
             supplier_id=456,
             name="A test supplier"
         )
         supplier_user = User(
             id=456,
             email_address="*****@*****.**",
             name="my supplier name",
             password=encryption.hashpw("my long password"),
             active=True,
             role='supplier',
             created_at=now,
             updated_at=now,
             supplier_id=456,
             password_changed_at=now
         )
         db.session.add(supplier)
         db.session.add(user)
         db.session.add(supplier_user)
         db.session.commit()
 def setup(self):
     now = datetime.utcnow()
     super(TestUsersUpdate, self).setup()
     with self.app.app_context():
         user = User(id=123,
                     email_address="*****@*****.**",
                     name="my name",
                     password=encryption.hashpw("my long password"),
                     active=True,
                     role='buyer',
                     created_at=now,
                     updated_at=now,
                     password_changed_at=now)
         supplier = Supplier(supplier_id=456, name="A test supplier")
         supplier_user = User(
             id=456,
             email_address="*****@*****.**",
             name="my supplier name",
             password=encryption.hashpw("my long password"),
             active=True,
             role='supplier',
             created_at=now,
             updated_at=now,
             supplier_id=456,
             password_changed_at=now)
         db.session.add(supplier)
         db.session.add(user)
         db.session.add(supplier_user)
         db.session.commit()
def update_user_details(**kwargs):
    """
        Update a user. Looks user up in DB, and updates where necessary.
    """

    user_id = kwargs.get('user_id', None)

    user = User.query.filter(User.id == user_id).first()

    if user is None:
        raise ValueError("Unable to modify user. User with id {} does not exist".format(user_id))

    if kwargs.get('password', None) is not None:
        user.password = encryption.hashpw(kwargs['password'])
        user.password_changed_at = datetime.utcnow()
    if kwargs.get('active', None) is not None:
        user.active = kwargs['active']
    if kwargs.get('name', None) is not None:
        user.name = kwargs['name']
    if kwargs.get('email_address', None) is not None:
        user.email_address = kwargs['email_address']
    if kwargs.get('role', None) is not None:
        if user.role == 'supplier' and kwargs['role'] != user.role:
            user.supplier_code = None
            kwargs.pop('supplierCode', None)
        user.role = kwargs['role']
    if kwargs.get('supplierCode', None) is not None:
        user.supplier_code = kwargs['supplierCode']
    if kwargs.get('application_id', None) is not None:
        user.application_id = kwargs['application_id']
    if kwargs.get('locked', None) and not kwargs['locked']:
        user.failed_login_count = 0
    if kwargs.get('termsAcceptedAt', None) is not None:
        user.terms_accepted_at = kwargs['termsAcceptedAt']

    check_supplier_role(user.role, user.supplier_code)

    update_data = {
        "user_id": user_id,
        "email_address": kwargs.get('email_address', None)
    }

    audit = AuditEvent(
        audit_type=AuditTypes.update_user,
        user=kwargs.get('updated_by', 'no user data'),
        data={
            'user': user.email_address,
            'update': update_data
        },
        db_object=user
    )

    db.session.add(user)
    db.session.add(audit)

    db.session.commit()

    return user
示例#4
0
def update_user_details(**kwargs):
    """
        Update a user. Looks user up in DB, and updates where necessary.
    """

    user_id = kwargs.get('user_id', None)

    user = User.query.filter(User.id == user_id).first()

    if user is None:
        raise ValueError("Unable to modify user. User with id {} does not exist".format(user_id))

    if kwargs.get('password', None) is not None:
        user.password = encryption.hashpw(kwargs['password'])
        user.password_changed_at = datetime.utcnow()
    if kwargs.get('active', None) is not None:
        user.active = kwargs['active']
    if kwargs.get('name', None) is not None:
        user.name = kwargs['name']
    if kwargs.get('email_address', None) is not None:
        user.email_address = kwargs['email_address']
    if kwargs.get('role', None) is not None:
        if user.role == 'supplier' and kwargs['role'] != user.role:
            user.supplier_code = None
            kwargs.pop('supplierCode', None)
        user.role = kwargs['role']
    if kwargs.get('supplierCode', None) is not None:
        user.supplier_code = kwargs['supplierCode']
    if kwargs.get('application_id', None) is not None:
        user.application_id = kwargs['application_id']
    if kwargs.get('locked', None) and not kwargs['locked']:
        user.failed_login_count = 0
    if kwargs.get('termsAcceptedAt', None) is not None:
        user.terms_accepted_at = kwargs['termsAcceptedAt']

    check_supplier_role(user.role, user.supplier_code)

    update_data = {
        "user_id": user_id,
        "email_address": kwargs.get('email_address', None)
    }

    audit = AuditEvent(
        audit_type=AuditTypes.update_user,
        user=kwargs.get('updated_by', 'no user data'),
        data={
            'user': user.email_address,
            'update': update_data
        },
        db_object=user
    )

    db.session.add(user)
    db.session.add(audit)

    db.session.commit()

    return user
def users(client, app):
    with app.app_context():
        db.session.add(
            User(id=1,
                 email_address='*****@*****.**',
                 name='Test',
                 password=encryption.hashpw('test'),
                 active=True,
                 role='buyer',
                 password_changed_at=utcnow(),
                 agency_id=1))

        db.session.add(
            User(id=2,
                 email_address='*****@*****.**',
                 name='Test',
                 password=encryption.hashpw('test'),
                 active=True,
                 role='buyer',
                 password_changed_at=utcnow(),
                 agency_id=2))

        db.session.add(
            User(id=3,
                 email_address='*****@*****.**',
                 name='Test User Team Lead',
                 password=encryption.hashpw('test'),
                 active=True,
                 role='buyer',
                 password_changed_at=utcnow(),
                 agency_id=1))

        db.session.add(
            User(id=4,
                 email_address='*****@*****.**',
                 name='Test User No Team',
                 password=encryption.hashpw('test'),
                 active=True,
                 role='buyer',
                 password_changed_at=utcnow(),
                 agency_id=1))

        db.session.commit()

        yield db.session.query(User).all()
def buyer_dashboard_users(app, request):
    with app.app_context():
        db.session.add(User(
            id=1,
            email_address='*****@*****.**',
            name=fake.name(),
            password=encryption.hashpw('testpassword'),
            active=True,
            role='buyer',
            password_changed_at=utcnow()
        ))

        db.session.add(User(
            id=2,
            email_address='*****@*****.**',
            name=fake.name(),
            password=encryption.hashpw('testpassword'),
            active=True,
            role='buyer',
            password_changed_at=utcnow()
        ))

        db.session.add(User(
            id=3,
            email_address='*****@*****.**',
            name=fake.name(),
            password=encryption.hashpw('testpassword'),
            active=True,
            role='buyer',
            password_changed_at=utcnow()
        ))

        db.session.flush()

        framework = Framework.query.filter(Framework.slug == "digital-marketplace").first()
        db.session.add(UserFramework(user_id=1, framework_id=framework.id))
        db.session.add(UserFramework(user_id=2, framework_id=framework.id))
        db.session.commit()

        yield User.query.all()
示例#7
0
def admin_users(app, request):
    with app.app_context():
        db.session.add(
            User(id=7,
                 email_address='*****@*****.**',
                 name=fake.name(),
                 password=encryption.hashpw('testpassword'),
                 active=True,
                 role='admin',
                 password_changed_at=utcnow()))

        db.session.commit()
        yield User.query.filter(User.role == 'admin').all()
def buyer_user(app, request):
    with app.app_context():
        user = User.query.order_by(User.id.desc()).first()
        id = user.id + 1 if user else 1
        db.session.add(
            User(id=id,
                 email_address='*****@*****.**',
                 name=fake.name(),
                 password=encryption.hashpw('test'),
                 active=True,
                 role='buyer',
                 password_changed_at=utcnow()))
        db.session.commit()
        yield User.query.get(id)
示例#9
0
def upgrade():
    try:
        os.environ['CREATE_ADMIN_USER']
    except:
        print('CREATE_ADMIN_USER environment variable not found, skipping')
        return

    if os.environ['CREATE_ADMIN_USER'].lower() == 'true':
        print('Attempting to create [email protected] user...')
        insert_user = """INSERT INTO users (id, name, email_address, created_at, password_changed_at, failed_login_count, _password, mobile_number, state, platform_admin, auth_type)
                         VALUES ('{}', 'Notify Admin', '*****@*****.**', '{}', '{}', 0,'{}', '+61408184363', 'active', True, 'sms_auth')
                      """
        op.execute(
            insert_user.format(admin_user_id, datetime.utcnow(),
                               datetime.utcnow(), hashpw(str(uuid.uuid4()))))
        print('Successfully created [email protected] user')
 def setup(self):
     self.now = datetime.utcnow()
     super(TestUsersGet, self).setup()
     with self.app.app_context():
         user = User(
             id=123,
             email_address="*****@*****.**",
             name="my name",
             password=encryption.hashpw("my long password"),
             active=True,
             role='buyer',
             created_at=self.now,
             updated_at=self.now,
             password_changed_at=self.now
         )
         db.session.add(user)
         db.session.commit()
def supplier_user(app, request, suppliers):
    with app.app_context():
        db.session.add(User(
            id=100,
            email_address='*****@*****.**',
            name=fake.name(),
            password=encryption.hashpw('testpassword'),
            active=True,
            role='supplier',
            supplier_code=suppliers[0].code,
            password_changed_at=utcnow()
        ))
        db.session.commit()
        db.session.flush()
        framework = Framework.query.filter(Framework.slug == "digital-outcomes-and-specialists").first()
        db.session.add(UserFramework(user_id=100, framework_id=framework.id))
        db.session.commit()
        yield User.query.first()
示例#12
0
def supplier_user(app, request, suppliers):
    with app.app_context():
        user = User.query.order_by(User.id.desc()).first()
        id = user.id + 1 if user else 1
        db.session.add(
            User(id=id,
                 email_address='*****@*****.**',
                 name=fake.name(),
                 password=encryption.hashpw('testpassword'),
                 active=True,
                 role='supplier',
                 supplier_code=suppliers[0].code,
                 password_changed_at=utcnow()))
        db.session.commit()
        framework = Framework.query.filter(Framework.slug == "orams").first()
        db.session.add(UserFramework(user_id=id, framework_id=framework.id))
        db.session.commit()
        yield User.query.get(id)
def supplier_user(app, request, suppliers):
    with app.app_context():
        db.session.add(
            User(id=100,
                 email_address='*****@*****.**',
                 name=fake.name(),
                 password=encryption.hashpw('testpassword'),
                 active=True,
                 role='supplier',
                 supplier_code=suppliers[0].code,
                 password_changed_at=utcnow()))
        db.session.commit()
        db.session.flush()
        framework = Framework.query.filter(
            Framework.slug == "digital-outcomes-and-specialists").first()
        db.session.add(UserFramework(user_id=100, framework_id=framework.id))
        db.session.commit()
        yield User.query.first()
示例#14
0
def process_registration():
    form = RegistrationForm()
    if form.validate_on_submit():
        try:
            user = admin_api_client.register(form.email_address.data,
                                             form.password.data,
                                             form.mobile_number.data)
            code = ''.join(["%s" % randint(0, 9) for num in range(0, 5)])
            session['code'] = hashpw(code)
            session['new_user_id'] = user['users']['id']
            admin_api_client.send_sms(form.mobile_number.data, code)
            return redirect(url_for('.view_3fa'))
        except APIError as e:
            print(e.response.json())
            flash("Error creating user", "error")
            return render_template('register.html',
                                   **get_template_data(form=form)), 400

    else:
        return render_template('register.html',
                               **get_template_data(form=form)), 400
def users(app, request, agencies):
    params = request.param if hasattr(request, 'param') else {}
    user_role = params['user_role'] if 'user_role' in params else 'buyer'
    email_domain = params[
        'email_domain'] if 'email_domain' in params else 'digital.gov.au'
    framework_slug = params[
        'framework_slug'] if 'framework_slug' in params else 'digital-marketplace'
    with app.app_context():
        for i in range(1, 6):
            new_user = User(id=i,
                            email_address='{}{}@{}'.format(
                                fake.first_name(), i, email_domain).lower(),
                            name=fake.name(),
                            password=fake.password(),
                            active=True,
                            role=user_role,
                            password_changed_at=utcnow())
            if user_role == 'supplier':
                new_user.supplier_code = i
            db.session.add(new_user)
            db.session.flush()
            framework = Framework.query.filter(
                Framework.slug == framework_slug).first()
            db.session.add(UserFramework(user_id=i, framework_id=framework.id))

        if user_role == 'buyer':
            db.session.add(
                User(id=7,
                     email_address='*****@*****.**',
                     name=fake.name(),
                     password=encryption.hashpw('testpassword'),
                     active=True,
                     role='buyer',
                     password_changed_at=utcnow(),
                     agency_id=1))
            db.session.flush()
            db.session.add(UserFramework(user_id=7, framework_id=framework.id))

        db.session.commit()
        yield User.query.filter(User.role == user_role).all()
示例#16
0
def process_registration():
    form = RegistrationForm()
    if form.validate_on_submit():
        try:
            user = admin_api_client.register(form.email_address.data, form.password.data, form.mobile_number.data)
            code = ''.join(["%s" % randint(0, 9) for num in range(0, 5)])
            session['code'] = hashpw(code)
            session['new_user_id'] = user['users']['id']
            admin_api_client.send_sms(form.mobile_number.data, code)
            return redirect(url_for('.view_3fa'))
        except APIError as e:
            print(e.response.json())
            flash("Error creating user", "error")
            return render_template(
                'register.html',
                **get_template_data(form=form)
            ), 400

    else:
        return render_template(
            'register.html',
            **get_template_data(form=form)
        ), 400
def test_should_check_invalid_password():
    password = "******"
    password_hash = hashpw(password)
    assert_equal(checkpw("not my password", password_hash), False)
def test_authenticate_user(user_is_locked, expected_auth_result):
    password = "******"
    password_hash = hashpw(password)
    mock_user = mock.Mock(password=password_hash, locked=user_is_locked)

    assert authenticate_user(password, mock_user) == expected_auth_result
def test_should_check_password():
    password = "******"
    password_hash = hashpw(password)
    assert checkpw(password, password_hash) is True
def test_should_hash_password():
    password = "******"
    assert password != hashpw(password)
def test_should_check_invalid_password():
    password = "******"
    password_hash = hashpw(password)
    assert checkpw("not my password", password_hash) is False
示例#22
0
 def password(self, password):
     self._password = hashpw(password)
示例#23
0
 def code(self, cde):
     self._code = hashpw(cde)
示例#24
0
def add_user(data):
    if data is None:
        raise DataError('create_user requires a data arg')

    name = data.get('name')
    password = data.get('password')
    role = data.get('user_type')
    email_address = data.get('email_address', None)
    framework_slug = data.get('framework', 'digital-marketplace')

    if email_address is None:
        email_address = data.get('emailAddress', None)

    if 'hashpw' in data and not data['hashpw']:
        password = password
    else:
        password = encryption.hashpw(password)

    if role == 'seller':
        role = 'applicant'

    now = datetime.utcnow()
    user = User(
        email_address=email_address.lower(),
        phone_number=data.get('phoneNumber', None),
        name=name,
        role=role,
        password=password,
        active=True,
        created_at=now,
        updated_at=now,
        password_changed_at=now
    )

    audit_data = {}

    if "supplier_code" in data:
        user.supplier_code = data['supplier_code']
        audit_data['supplier_code'] = user.supplier_code

    if user.role == 'supplier' and user.supplier_code is None:
        raise ValueError("'supplier_code' is required for users with 'supplier' role")

    if user.role != 'supplier' and user.supplier_code is not None:
        raise ValueError("'supplier_code' is only valid for users with 'supplier' role, not '{}'".format(user.role))

    if "application_id" in data:
        user.application_id = data['application_id']
    elif user.supplier_code is not None:
        appl = Application.query.filter_by(supplier_code=user.supplier_code).first()
        user.application_id = appl and appl.id or None

    if user.role == 'applicant' and user.application_id is None:
        raise ValueError("'application id' is required for users with 'applicant' role")
    elif user.role != 'applicant' and user.role != 'supplier' and user.application_id is not None:
        raise ValueError(
            "'application_id' is only valid for users with applicant' or 'supplier' role, not '{}'".format(user.role))

    db.session.add(user)
    db.session.flush()

    framework = Framework.query.filter(Framework.slug == framework_slug).first()
    db.session.add(UserFramework(user_id=user.id, framework_id=framework.id))

    audit = AuditEvent(
        audit_type=AuditTypes.create_user,
        user=email_address.lower(),
        data=audit_data,
        db_object=user
    )

    db.session.add(audit)
    db.session.commit()

    user = db.session.query(User).options(noload('*')).filter(User.id == user.id).one_or_none()
    publish_tasks.user.delay(
        publish_tasks.compress_user(user),
        'created'
    )

    return user
示例#25
0
def create_user():

    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ["users"])
    json_payload = json_payload["users"]
    validate_user_json_or_400(json_payload)
    email_address = json_payload.get('email_address', None)
    if email_address is None:
        email_address = json_payload.get('emailAddress', None)

    user = User.query.filter(
        User.email_address == email_address.lower()).first()

    if user:
        abort(409, "User already exists")

    if 'hashpw' in json_payload and not json_payload['hashpw']:
        password = json_payload['password']
    else:
        password = encryption.hashpw(json_payload['password'])

    now = datetime.utcnow()
    user = User(email_address=email_address.lower(),
                phone_number=json_payload.get('phoneNumber') or None,
                name=json_payload['name'],
                role=json_payload['role'],
                password=password,
                active=True,
                created_at=now,
                updated_at=now,
                password_changed_at=now)

    audit_data = {}

    if "supplierCode" in json_payload:
        user.supplier_code = json_payload['supplierCode']
        audit_data['supplier_code'] = user.supplier_code

    check_supplier_role(user.role, user.supplier_code)

    if "application_id" in json_payload:
        user.application_id = json_payload['application_id']
    elif user.supplier_code is not None:
        appl = Application.query.filter_by(
            supplier_code=user.supplier_code).first()
        user.application_id = appl and appl.id or None

    check_applicant_role(user.role, user.application_id)

    try:
        db.session.add(user)
        db.session.flush()

        audit = AuditEvent(audit_type=AuditTypes.create_user,
                           user=email_address.lower(),
                           data=audit_data,
                           db_object=user)

        db.session.add(audit)
        db.session.commit()

        user = db.session.query(User).options(
            noload('*')).filter(User.id == user.id).one_or_none()
        publish_tasks.user.delay(publish_tasks.compress_user(user), 'created')

        if user.role == 'buyer':
            notification_message = 'Domain: {}'.format(
                email_address.split('@')[-1])

            notification_text = 'A new buyer has signed up'
            notify_team(notification_text, notification_message)

    except IntegrityError:
        db.session.rollback()
        abort(400, "Invalid supplier code or application id")
    except DataError:
        db.session.rollback()
        abort(400, "Invalid user role")

    return jsonify(users=user.serialize()), 201
示例#26
0
def update_user(user_id):
    """
        Update a user. Looks user up in DB, and updates where necessary.
    """
    update_details = validate_and_return_updater_request()

    user = User.query.options(
        noload('*')).filter(User.id == user_id).first_or_404()

    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ["users"])
    user_update = json_payload["users"]

    json_has_matching_id(user_update, user_id)
    existing_user = publish_tasks.compress_user(user)

    if 'password' in user_update:
        user.password = encryption.hashpw(user_update['password'])
        user.password_changed_at = datetime.utcnow()
        user_update['password'] = '******'
    if 'active' in user_update:
        user.active = user_update['active']
    if 'name' in user_update:
        user.name = user_update['name']
    if 'emailAddress' in user_update:
        user.email_address = user_update['emailAddress']
    if 'role' in user_update:
        if user.role == 'supplier' and user_update['role'] != user.role:
            user.supplier_code = None
            user_update.pop('supplierCode', None)
        user.role = user_update['role']
    if 'supplierCode' in user_update:
        user.supplier_code = user_update['supplierCode']
    if 'application_id' in user_update:
        user.application_id = user_update['application_id']
    if 'locked' in user_update and not user_update['locked']:
        user.failed_login_count = 0
    if 'termsAcceptedAt' in user_update:
        user.terms_accepted_at = user_update['termsAcceptedAt']

    check_supplier_role(user.role, user.supplier_code)

    audit = AuditEvent(audit_type=AuditTypes.update_user,
                       user=update_details.get('updated_by', 'no user data'),
                       data={
                           'user': user.email_address,
                           'update': user_update
                       },
                       db_object=user)

    db.session.add(user)
    db.session.add(audit)

    publish_tasks.user.delay(publish_tasks.compress_user(user),
                             'updated',
                             old_user=existing_user)

    try:
        db.session.commit()
        return jsonify(users=user.serialize()), 200
    except (IntegrityError, DataError):
        db.session.rollback()
        abort(400, "Could not update user with: {0}".format(user_update))
示例#27
0
def update_user(user_id):
    """
        Update a user. Looks user up in DB, and updates where necessary.
    """
    update_details = validate_and_return_updater_request()

    user = User.query.options(
        noload('*')
    ).filter(
        User.id == user_id
    ).first_or_404()

    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ["users"])
    user_update = json_payload["users"]

    json_has_matching_id(user_update, user_id)
    existing_user = publish_tasks.compress_user(user)

    if 'password' in user_update:
        user.password = encryption.hashpw(user_update['password'])
        user.password_changed_at = datetime.utcnow()
        user_update['password'] = '******'
    if 'active' in user_update:
        user.active = user_update['active']
    if 'name' in user_update:
        user.name = user_update['name']
    if 'emailAddress' in user_update:
        user.email_address = user_update['emailAddress']
    if 'role' in user_update:
        if user.role == 'supplier' and user_update['role'] != user.role:
            user.supplier_code = None
            user_update.pop('supplierCode', None)
        user.role = user_update['role']
    if 'supplierCode' in user_update:
        user.supplier_code = user_update['supplierCode']
    if 'application_id' in user_update:
        user.application_id = user_update['application_id']
    if 'locked' in user_update and not user_update['locked']:
        user.failed_login_count = 0
    if 'termsAcceptedAt' in user_update:
        user.terms_accepted_at = user_update['termsAcceptedAt']

    check_supplier_role(user.role, user.supplier_code)

    audit = AuditEvent(
        audit_type=AuditTypes.update_user,
        user=update_details.get('updated_by', 'no user data'),
        data={
            'user': user.email_address,
            'update': user_update
        },
        db_object=user
    )

    db.session.add(user)
    db.session.add(audit)

    publish_tasks.user.delay(
        publish_tasks.compress_user(user),
        'updated',
        old_user=existing_user
    )

    try:
        db.session.commit()
        return jsonify(users=user.serialize()), 200
    except (IntegrityError, DataError):
        db.session.rollback()
        abort(400, "Could not update user with: {0}".format(user_update))
示例#28
0
def create_user():

    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ["users"])
    json_payload = json_payload["users"]
    validate_user_json_or_400(json_payload)
    email_address = json_payload.get('email_address', None)
    if email_address is None:
        email_address = json_payload.get('emailAddress', None)

    user = User.query.filter(
        User.email_address == email_address.lower()).first()

    if user:
        abort(409, "User already exists")

    if 'hashpw' in json_payload and not json_payload['hashpw']:
        password = json_payload['password']
    else:
        password = encryption.hashpw(json_payload['password'])

    now = datetime.utcnow()
    user = User(
        email_address=email_address.lower(),
        phone_number=json_payload.get('phoneNumber') or None,
        name=json_payload['name'],
        role=json_payload['role'],
        password=password,
        active=True,
        created_at=now,
        updated_at=now,
        password_changed_at=now
    )

    audit_data = {}

    if "supplierCode" in json_payload:
        user.supplier_code = json_payload['supplierCode']
        audit_data['supplier_code'] = user.supplier_code

    check_supplier_role(user.role, user.supplier_code)

    if "application_id" in json_payload:
        user.application_id = json_payload['application_id']
    elif user.supplier_code is not None:
        appl = Application.query.filter_by(supplier_code=user.supplier_code).first()
        user.application_id = appl and appl.id or None

    check_applicant_role(user.role, user.application_id)

    try:
        db.session.add(user)
        db.session.flush()

        audit = AuditEvent(
            audit_type=AuditTypes.create_user,
            user=email_address.lower(),
            data=audit_data,
            db_object=user
        )

        db.session.add(audit)
        db.session.commit()

        user = db.session.query(User).options(noload('*')).filter(User.id == user.id).one_or_none()
        publish_tasks.user.delay(
            publish_tasks.compress_user(user),
            'created'
        )

        if user.role == 'buyer':
            notification_message = 'Domain: {}'.format(
                email_address.split('@')[-1]
            )

            notification_text = 'A new buyer has signed up'
            notify_team(notification_text, notification_message)

    except IntegrityError:
        db.session.rollback()
        abort(400, "Invalid supplier code or application id")
    except DataError:
        db.session.rollback()
        abort(400, "Invalid user role")

    return jsonify(users=user.serialize()), 201
def upgrade():
    password = hashpw(str(uuid.uuid4()))
    op.get_bind()
    user_insert = """INSERT INTO users (id, name, email_address, created_at, failed_login_count, _password, mobile_number, state, platform_admin)
                     VALUES ('{}', 'Notify service user', '[email protected]', '{}', 0,'{}', '+441234123412', 'active', False)
                  """
    op.execute(user_insert.format(user_id, datetime.utcnow(), password))
    service_history_insert = """INSERT INTO services_history (id, name, created_at, active, message_limit, restricted, research_mode, email_from, created_by_id, reply_to_email_address, version)
                        VALUES ('{}', 'Notify service', '{}', True, 1000, False, False, '*****@*****.**',
                        '{}', '*****@*****.**', 1)

                     """
    op.execute(
        service_history_insert.format(service_id, datetime.utcnow(), user_id))
    service_insert = """INSERT INTO services (id, name, created_at, active, message_limit, restricted, research_mode, email_from, created_by_id, reply_to_email_address, version)
                        VALUES ('{}', 'Notify service', '{}', True, 1000, False, False, '*****@*****.**',
                        '{}', '*****@*****.**', 1)
                    """
    op.execute(service_insert.format(service_id, datetime.utcnow(), user_id))
    user_to_service_insert = """INSERT INTO user_to_service (user_id, service_id) VALUES ('{}', '{}')"""
    op.execute(user_to_service_insert.format(user_id, service_id))

    template_history_insert = """INSERT INTO templates_history (id, name, template_type, created_at,
                                                                content, archived, service_id,
                                                                subject, created_by_id, version)
                                 VALUES ('{}', '{}', '{}', '{}', '{}', False, '{}', '{}', '{}', 1)
                              """
    template_insert = """INSERT INTO templates (id, name, template_type, created_at,
                                                content, archived, service_id, subject, created_by_id, version)
                                 VALUES ('{}', '{}', '{}', '{}', '{}', False, '{}', '{}', '{}', 1)
                              """
    email_verification_content = \
        """Hi ((name)),\n\nTo complete your registration for GOV.UK Notify please click the link below\n\n((url))"""
    op.execute(
        template_history_insert.format(
            uuid.uuid4(), 'Notify email verification code', 'email',
            datetime.utcnow(), email_verification_content, service_id,
            'Confirm GOV.UK Notify registration', user_id))
    op.execute(
        template_insert.format('ece42649-22a8-4d06-b87f-d52d5d3f0a27',
                               'Notify email verification code', 'email',
                               datetime.utcnow(), email_verification_content,
                               service_id,
                               'Confirm GOV.UK Notify registration', user_id))

    invitation_subject = "((user_name)) has invited you to collaborate on ((service_name)) on GOV.UK Notify"
    invitation_content = """((user_name)) has invited you to collaborate on ((service_name)) on GOV.UK Notify.\n\n
        GOV.UK Notify makes it easy to keep people updated by helping you send text messages, emails and letters.\n\n
        Click this link to create an account on GOV.UK Notify:\n((url))\n\n
        This invitation will stop working at midnight tomorrow. This is to keep ((service_name)) secure.
        """
    op.execute(
        template_history_insert.format('4f46df42-f795-4cc4-83bb-65ca312f49cc',
                                       'Notify invitation email', 'email',
                                       datetime.utcnow(), invitation_content,
                                       service_id, invitation_subject,
                                       user_id))
    op.execute(
        template_insert.format('4f46df42-f795-4cc4-83bb-65ca312f49cc',
                               'Notify invitation email', 'email',
                               datetime.utcnow(), invitation_content,
                               service_id, invitation_subject, user_id))

    sms_code_content = '((verify_code)) is your Notify authentication code'
    op.execute(
        template_history_insert.format('36fb0730-6259-4da1-8a80-c8de22ad4246',
                                       'Notify SMS verify code', 'sms',
                                       datetime.utcnow(), sms_code_content,
                                       service_id, None, user_id))

    op.execute(
        template_insert.format('36fb0730-6259-4da1-8a80-c8de22ad4246',
                               'Notify SMS verify code', 'sms',
                               datetime.utcnow(), sms_code_content, service_id,
                               None, user_id))

    password_reset_content = "Hi ((user_name)),\n\n" \
                             "We received a request to reset your password on GOV.UK Notify.\n\n" \
                             "If you didn''t request this email, you can ignore it – " \
                             "your password has not been changed.\n\n" \
                             "To reset your password, click this link:\n\n" \
                             "((url))"

    op.execute(
        template_history_insert.format('474e9242-823b-4f99-813d-ed392e7f1201',
                                       'Notify password reset email', 'email',
                                       datetime.utcnow(),
                                       password_reset_content, service_id,
                                       'Reset your GOV.UK Notify password',
                                       user_id))
    op.execute(
        template_insert.format('474e9242-823b-4f99-813d-ed392e7f1201',
                               'Notify password reset email', 'email',
                               datetime.utcnow(), password_reset_content,
                               service_id, 'Reset your GOV.UK Notify password',
                               user_id))
示例#30
0
def add_user(data):
    if data is None:
        raise DataError('create_user requires a data arg')

    name = data.get('name')
    password = data.get('password')
    role = data.get('user_type')
    email_address = data.get('email_address', None)
    framework_slug = data.get('framework', 'digital-marketplace')

    if email_address is None:
        email_address = data.get('emailAddress', None)

    if 'hashpw' in data and not data['hashpw']:
        password = password
    else:
        password = encryption.hashpw(password)

    if role == 'seller':
        role = 'applicant'

    now = datetime.utcnow()
    user = User(email_address=email_address.lower(),
                phone_number=data.get('phoneNumber', None),
                name=name,
                role=role,
                password=password,
                active=True,
                created_at=now,
                updated_at=now,
                password_changed_at=now)

    audit_data = {}

    if "supplier_code" in data:
        user.supplier_code = data['supplier_code']
        audit_data['supplier_code'] = user.supplier_code

    if user.role == 'supplier' and user.supplier_code is None:
        raise ValueError(
            "'supplier_code' is required for users with 'supplier' role")

    if user.role != 'supplier' and user.supplier_code is not None:
        raise ValueError(
            "'supplier_code' is only valid for users with 'supplier' role, not '{}'"
            .format(user.role))

    if "application_id" in data:
        user.application_id = data['application_id']
    elif user.supplier_code is not None:
        appl = Application.query.filter_by(
            supplier_code=user.supplier_code).first()
        user.application_id = appl and appl.id or None

    if user.role == 'applicant' and user.application_id is None:
        raise ValueError(
            "'application id' is required for users with 'applicant' role")
    elif user.role != 'applicant' and user.role != 'supplier' and user.application_id is not None:
        raise ValueError(
            "'application_id' is only valid for users with applicant' or 'supplier' role, not '{}'"
            .format(user.role))

    db.session.add(user)
    db.session.flush()

    framework = Framework.query.filter(
        Framework.slug == framework_slug).first()
    db.session.add(UserFramework(user_id=user.id, framework_id=framework.id))

    audit = AuditEvent(audit_type=AuditTypes.create_user,
                       user=email_address.lower(),
                       data=audit_data,
                       db_object=user)

    db.session.add(audit)
    db.session.commit()

    return user
def test_should_check_password():
    password = "******"
    password_hash = hashpw(password)
    assert_equal(checkpw(password, password_hash), True)
def test_should_hash_password():
    password = "******"
    assert_not_equal(password, hashpw(password))
def upgrade():
    password = hashpw(str(uuid.uuid4()))
    op.get_bind()
    user_insert = """INSERT INTO users (id, name, email_address, created_at, failed_login_count, _password, mobile_number, state, platform_admin)
                     VALUES ('{}', 'Notify service user', '[email protected]', '{}', 0,'{}', '+441234123412', 'active', False)
                  """
    op.execute(user_insert.format(user_id, datetime.utcnow(), password))
    service_history_insert = """INSERT INTO services_history (id, name, created_at, active, message_limit, restricted, research_mode, email_from, created_by_id, reply_to_email_address, version)
                        VALUES ('{}', 'Notify service', '{}', True, 1000, False, False, '*****@*****.**',
                        '{}', '*****@*****.**', 1)

                     """
    op.execute(service_history_insert.format(service_id, datetime.utcnow(), user_id))
    service_insert = """INSERT INTO services (id, name, created_at, active, message_limit, restricted, research_mode, email_from, created_by_id, reply_to_email_address, version)
                        VALUES ('{}', 'Notify service', '{}', True, 1000, False, False, '*****@*****.**',
                        '{}', '*****@*****.**', 1)
                    """
    op.execute(service_insert.format(service_id, datetime.utcnow(), user_id))
    user_to_service_insert = """INSERT INTO user_to_service (user_id, service_id) VALUES ('{}', '{}')"""
    op.execute(user_to_service_insert.format(user_id, service_id))

    template_history_insert = """INSERT INTO templates_history (id, name, template_type, created_at,
                                                                content, archived, service_id,
                                                                subject, created_by_id, version)
                                 VALUES ('{}', '{}', '{}', '{}', '{}', False, '{}', '{}', '{}', 1)
                              """
    template_insert = """INSERT INTO templates (id, name, template_type, created_at,
                                                content, archived, service_id, subject, created_by_id, version)
                                 VALUES ('{}', '{}', '{}', '{}', '{}', False, '{}', '{}', '{}', 1)
                              """
    email_verification_content = \
        """Hi ((name)),\n\nTo complete your registration for GOV.UK Notify please click the link below\n\n((url))"""
    op.execute(template_history_insert.format(uuid.uuid4(), 'Notify email verification code', 'email',
                                              datetime.utcnow(), email_verification_content, service_id,
                                              'Confirm GOV.UK Notify registration', user_id))
    op.execute(template_insert.format('ece42649-22a8-4d06-b87f-d52d5d3f0a27', 'Notify email verification code', 'email',
                                      datetime.utcnow(), email_verification_content, service_id,
                                      'Confirm GOV.UK Notify registration', user_id))

    invitation_subject = "((user_name)) has invited you to collaborate on ((service_name)) on GOV.UK Notify"
    invitation_content = """((user_name)) has invited you to collaborate on ((service_name)) on GOV.UK Notify.\n\n
        GOV.UK Notify makes it easy to keep people updated by helping you send text messages, emails and letters.\n\n
        Click this link to create an account on GOV.UK Notify:\n((url))\n\n
        This invitation will stop working at midnight tomorrow. This is to keep ((service_name)) secure.
        """
    op.execute(template_history_insert.format('4f46df42-f795-4cc4-83bb-65ca312f49cc', 'Notify invitation email',
                                              'email', datetime.utcnow(), invitation_content, service_id,
                                              invitation_subject, user_id))
    op.execute(template_insert.format('4f46df42-f795-4cc4-83bb-65ca312f49cc', 'Notify invitation email',
                                      'email', datetime.utcnow(), invitation_content, service_id,
                                      invitation_subject, user_id))

    sms_code_content = '((verify_code)) is your Notify authentication code'
    op.execute(template_history_insert.format('36fb0730-6259-4da1-8a80-c8de22ad4246', 'Notify SMS verify code',
                                              'sms', datetime.utcnow(), sms_code_content, service_id, None, user_id))

    op.execute(template_insert.format('36fb0730-6259-4da1-8a80-c8de22ad4246', 'Notify SMS verify code',
                                      'sms', datetime.utcnow(), sms_code_content, service_id, None, user_id))

    password_reset_content = "Hi ((user_name)),\n\n" \
                             "We received a request to reset your password on GOV.UK Notify.\n\n" \
                             "If you didn''t request this email, you can ignore it – " \
                             "your password has not been changed.\n\n" \
                             "To reset your password, click this link:\n\n" \
                             "((url))"

    op.execute(template_history_insert.format('474e9242-823b-4f99-813d-ed392e7f1201', 'Notify password reset email',
                                              'email', datetime.utcnow(), password_reset_content, service_id,
                                              'Reset your GOV.UK Notify password', user_id))
    op.execute(template_insert.format('474e9242-823b-4f99-813d-ed392e7f1201', 'Notify password reset email',
                                      'email', datetime.utcnow(), password_reset_content, service_id,
                                      'Reset your GOV.UK Notify password', user_id))