Beispiel #1
0
    def _create_test_users(self):
        # admin user and role
        admin_role = Role(name=self.ADMIN_ROLE)
        admin_role.save()

        admin_user = User(
            name=self.ADMIN_USER,
            password=self.encode_password(self.ADMIN_PW),
            is_active=True,
            # user_id=self._user_gen_id()
        )
        admin_user.save()
        admin_user.permissions.add(admin_role)
        # admin_user.save()

        self._users[self.ADMIN_USER] = admin_user

        # regular user
        regular_user = User(
            name=self.REGULAR_USER,
            password=self.encode_password(self.REGULAR_PW),
            is_active=True,
            # user_id=self._user_gen_id()
        )
        regular_user.save()

        self._users[self.REGULAR_USER] = regular_user

        # regular secondary user
        regular_user = User(
            name=self.REGULAR_ALT_USER,
            password=self.encode_password(self.REGULAR_ALT_PW),
            is_active=True,
            # user_id=self._user_gen_id()
        )
        regular_user.save()

        self._users[self.REGULAR_ALT_USER] = regular_user

        # inactive user
        inactive_user = User(
            name=self.INACTIVE_USER,
            password=self.encode_password(self.INACTIVE_PW),
            is_active=False,
            # user_id=self._user_gen_id()
        )
        inactive_user.save()

        self._users[self.INACTIVE_USER] = inactive_user

        pass
Beispiel #2
0
class TestUserResource:
    @patch.object(
        UserService, 'get_all', lambda:
        [make_user(),
         make_user(2, 'John', '*****@*****.**', b'metallica', 2)])
    def test_get(self, client: FlaskClient):
        with client:
            results = client.get(f'/api/{BASE_ROUTE}',
                                 follow_redirects=True).get_json()
            expected = (UserSchema(many=True).dump([
                make_user(),
                make_user(2, 'John', '*****@*****.**', b'metallica', 2)
            ]))
            for r in results:
                assert r in expected

    @patch.object(UserService, 'create',
                  lambda create_request: User(**create_request))
    def test_post(self, client: FlaskClient):
        with client:
            payload = dict(name='John',
                           email='*****@*****.**',
                           password='******')
            result = client.post(f'/api/{BASE_ROUTE}/',
                                 json=payload).get_json()
            expected = (UserSchema().dump(
                User(
                    name=payload['name'],
                    email=payload['email'],
                    password=payload['password'],
                )))
            assert result == expected
def UserSeeder():

    user = User(uuid=uuid.uuid4(),
                name="Test",
                email="*****@*****.**",
                password=bcrypt.generate_password_hash('test').decode('utf-8'))
    db.session.add(user)

    for _ in range(9):
        user = User(
            uuid=uuid.uuid4(),
            name=fake.name(),
            email=fake.email(),
            password=bcrypt.generate_password_hash('test').decode('utf-8'))
        db.session.add(user)

    db.session.commit()
Beispiel #4
0
def fake_update(user: User, changes: UserInterface):
    update_user = User(user_id=user.user_id,
                       name=changes['name'],
                       email=changes['email'],
                       password=changes['password'],
                       location_id=user.location_id)

    return update_user
Beispiel #5
0
 def create_data(self):
     user = User()
     user.username = "******"
     user.name = "User"
     user.last_name = "Teste"
     user.hash_password("123456")
     user.confirmed_on = True
     db.session.add(user)
     db.session.commit()
Beispiel #6
0
def make_user(user_id: int = 1,
              name: str = 'Gabriel Dylan',
              email: str = '*****@*****.**',
              password: bin = b'admin',
              location_id: int = 1):
    return User(user_id=user_id,
                name=name,
                email=email,
                password=password,
                location_id=location_id)
Beispiel #7
0
 def test_post(self, client: FlaskClient):
     with client:
         payload = dict(name='John',
                        email='*****@*****.**',
                        password='******')
         result = client.post(f'/api/{BASE_ROUTE}/',
                              json=payload).get_json()
         expected = (UserSchema().dump(
             User(
                 name=payload['name'],
                 email=payload['email'],
                 password=payload['password'],
             )))
         assert result == expected
Beispiel #8
0
def save_new_user(data):
    user = User.query.filter_by(email=data['email']).first()
    if not user:
        new_user = User(public_id=str(uuid.uuid4()),
                        email=data['email'],
                        username=data['username'],
                        password=data['password'],
                        registered_on=datetime.datetime.utcnow())
        save_changes(new_user)
        return generate_token(new_user)
    else:
        response_object = {
            'status': 'fail',
            'message': 'User already exists. Please Log in.',
        }
        return response_object, 409
Beispiel #9
0
def user_sign_up(data):
    try:
        if User.username_exists(data["username"]):
            return Response(mimetype="application/json",
                            response=json.dumps(
                                {'error': "Username already exists"}),
                            status=403)
        if User.email_exists(data["email"]):
            return Response(mimetype="application/json",
                            response=json.dumps(
                                {'error': "email already exists"}),
                            status=403)
        password_hash = User.generate_hash_password(data["password"])
        new_user = User(username=data["username"],
                        name=data["name"],
                        email=data["email"],
                        password=password_hash)
        new_user.save()

        # # Now we'll send the email confirmation link
        # subject = "Confirm your email"

        # token = ts.dumps(self.email, salt='email-confirm-key')

        # confirm_url = url_for(
        #     'confirm_email',
        #     token=token,
        #     _external=True)

        # html = render_template(
        #     'email/activate.html',
        #     confirm_url=confirm_url)

        # # We'll assume that send_email has been defined in myapp/util.py
        # send_email(user.email, subject, html)

        return Response(mimetype="application/json",
                        response=json.dumps(
                            {'success': "User created successfully"}),
                        status=201)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Beispiel #10
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400
    username = request.json.get("username")
    password = request.json.get('password')
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    access_token = create_access_token(identity=username)
    refresh_token = create_refresh_token(identity=username)
    user = User(password="******")
    # user.username = "******"
    # user.password = "******"
    user.__dict__ = request.json
    user.status = VerrifyStatus.checking
    return jsonify(
        user.__dict__
    )  #jsonify(access_token=access_token, refresh_token=refresh_token)
Beispiel #11
0
    def create_new_user(self, email, password, data):
        user = User.get_user_from_email(email=email)
        if user:
            return {'status': 400, 'message': 'User already exist'}

        if 'rname' in data:
            res = self.resto_service.create_new_restaurant(
                data['rname'], email, data['address'])
            if res['status'] != 200:
                return res

        hashed_password = generate_password_hash(password, method='sha256')
        new_user = User(fname=data['fname'],
                        lname=data['lname'],
                        email=email,
                        password=hashed_password,
                        address=data['address'],
                        rname=data['rname'] if 'rname' in data else None)
        if self.persist_user_to_mongo(new_user):
            return {'status': 200, 'message': 'User created'}
        return {'status': 500, 'message': 'User not created'}
Beispiel #12
0
    def save_new_user(json_body):

        username = json_body.get("username")
        email = json_body.get("email")
        password = json_body.get("password")
        password_confirm = json_body.get("password_confirm")

        if not username or not password or not password_confirm:
            return ResponseReturnKit.error400("Required field missing")

        if any(list(StringKit.password_check(password).values())):
            return ResponseReturnKit.error400(
                """A password is considered strong if: 6 characters length or more and 1 digit or more and 1 symbol or more and 1 uppercase letter or more and 1 lowercase letter or more"""
            )

        if password_confirm != password:
            return ResponseReturnKit.error400("Password is not matching")

        find_user = User.query.filter_by(username=username).first()
        if find_user and not find_user.confirmed:
            return ResponseReturnKit.error400("User already exists")

        if find_user and find_user.confirmed:
            return ResponseReturnKit.error400("User or password invalid")

        if not ValidateKit.validate_email(email):
            return ResponseReturnKit.error400("Email is invalid")

        user = User(username=username)
        if email:
            user.email = email
        user.hash_password(password)
        user.registered_on = datetime.datetime.now()
        db.session.add(user)
        db.session.commit()

        token = StringKit.generate_confirmation_token(user.username)
        confirm_url = url_for('confirm_email', token=token, _external=True)

        return {"url": confirm_url}, 201
def create_new_user(data):
    try:
        print("=" * 80, "Creating New User:"******"\n")
        user = User.get_user_via_email(data['email'])
        if (user):
            print("User already exists")
            print("=" * 80)
            return Response(mimetype="application/json",
                            response=json.dumps({'error': 'user exsists'}),
                            status=403)
        hashed_password = User.generate_hash_password(data['password'])
        new_user = User(username=data['username'],
                        email=data['email'],
                        password=hashed_password)
        new_user.save()
        print("New User Created", "=" * 80, sep="\n")
        return Response(mimetype="application/json",
                        response=json.dumps({'success': "New User Created"}),
                        status=201)
    except Exception as e:
        return Response(mimetype="application/json",
                        response=json.dumps({'error': str(e)}),
                        status=400)
Beispiel #14
0
def test_user(test_app, test_db):
    user = User(email="*****@*****.**", password="******", name="test")
    expected = {"name": "Test", "email": "*****@*****.**"}
    response = create(test_db, user)
    assert response == expected
Beispiel #15
0
def create(data: dict) -> User:
    return save(User(id=str(uuid4()), login=data['login'], senha=data['senha']))
Beispiel #16
0
 def make_user(self, data, **kwargs):
     return User(**data)
Beispiel #17
0
#!env/bin/python

from app.user.model import User
from app.group.model import Group

group = Group('admin', 'grupo dos administradores')
group.add(group)

user = User('clodonil', '*****@*****.**', '(11)97987987987')
user.add(user, group.titulo)
user.group_add(user, group)

user.status = 3

user.update()