Example #1
0
def sign_up():
    data_form = request.json
    mobile = data_form.get('mobile', None)
    password1 = data_form.get('password1', None)
    password2 = data_form.get('password2', None)
    verify_code = data_form.get('verify_code', None)
    if mobile and password1 and password2 and verify_code:
        if password1 != password2:
            return jsonify({
                "success": False,
                "message": "password is not correct"
            })
        if verify_code != int(session.get(str(mobile), None)):
            return jsonify({
                "success": False,
                "message": "verify_code is not correct"
            })
        if User.find_one(mobile=int(mobile)):
            return jsonify({
                "success": False,
                "message": "mobile is already exist"
            })
        user = User(mobile, password1)
        user.save()
        login_user(load_user(user.id), remember=True)
        return jsonify({"success": True, 'redirect_url': 'admin_panel'})
    else:
        return jsonify({
            "success": False,
            "message": "data form is not correct"
        })
Example #2
0
def test_user_update(app):
    user = User.find_by_id(_SOME_USER_ID)
    assert user.name != _UPDATED_NAME

    user.update({"name": _UPDATED_NAME})
    user.save()

    user = User.find_by_id(_SOME_USER_ID)
    assert user.name == _UPDATED_NAME
Example #3
0
 def post(self):
     data = UserRegister.parser.parse_args()
     if User.find_by_username(data['username']):
         return {'message': f"user {data['username']} already exists"}, 400
     user = User(username=data['username'], password=data['password'])
     user.add_user()
     return {
         'username': data['username'],
         'password': data['password']
     }, 201
Example #4
0
def create_user(name, email, password: str):
    if User.autenticate(email) is not None:
        return errors.bad_request({"email": "Email is already exists."})
    try:
        new_user = User.create(name, email, password)
        new_user.save()
    except SaveError as err:
        return errors.internal_error(err.messages)

    return new_user, 201
Example #5
0
def test_user_update_password(app):
    user = User.find_by_id(_SOME_USER_ID)
    current_hash = user.password
    some_pass = "******"

    user.update({"password": some_pass})
    user.save()

    user = User.find_by_id(_SOME_USER_ID)
    assert user.password != current_hash
    assert user.verify_passw(some_pass, user.password)
Example #6
0
def register(name: str, email: str, password: str):
    user = User.autenticate(email)
    if user is not None:
        return errors.bad_request(
            "User with this email is already in the system. Are you trying to logged in?"
        )

    user = User.create(name, email, password)
    user.save()

    return jwt_utils.response_with_tokens(user), 201
Example #7
0
def update_user(user: User, **params):
    if not params:
        return errors.error_response(200,
                                     "Nothing to update missing properties")

    if current_user.id != user.id and current_user.role != UserRoles.admin:
        return errors.forbidden("User can modify only his properties.")

    try:
        user.update(params)
        user.save()
    except SaveError as err:
        return errors.internal_error(err.messages)

    return {}, 204
Example #8
0
 def delete(self):
     username = UserRegister.parser.parse_args()['username']
     user = User.find_by_username(username)
     if not user:
         return {'message': f"user {username} doesn't exist"}, 400
     user.remove_user()
     return {}, 204
Example #9
0
def get_users(**search_params):
    users = User.filter_by(current_user.id, search_params)
    if current_user.role != UserRoles.admin:
        # TODO: implement address book
        pass

    return users, 200
Example #10
0
def user_add():
    """Page with user add route."""
    route_to = url_for('user_add')
    form = UserAddForm(request.form)

    if form.validate_on_submit():
        newuser = User()
        newuser.name = form.name.data
        newuser.alias = form.alias.data
        newuser.role_id = form.role_id.data
        newuser.email = form.email.data
        newuser.password = form.password.data
        db.session.add(newuser)
        db.session.commit()
        subject = "Add User"
        msg = Message(app.config['ADMIN_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                      sender=app.config['ADMIN_MAIL_SENDER'],
                      recipients=[newuser.email])
        msg.body = """
                              From: %s to <%s>
                              Email: %s
                              Name: %s
                              Alias: %s
                              """ % (app.config['ADMIN_MAIL_SUBJECT_PREFIX'],
                                     newuser.email, newuser.email,
                                     newuser.name, newuser.alias)
        mail.send(msg)
        flash("User added and notification", category="success")
        return redirect(url_for('user_page'))

    return render_template('user_add.html', form=form, route_to=route_to)
Example #11
0
def test_some_user_password(app):
    user = User.find_by_id(_SOME_USER_ID)

    assert user.password != _SOME_USER_PASSWORD
    # same string if generate again shows different hash
    assert user.password != user.generate_passw(_SOME_USER_PASSWORD)

    # check that some_password and hash that stored are actually the same
    assert user.verify_passw(_SOME_USER_PASSWORD, user.password)
Example #12
0
def test_get_user_messages(app):
    user = User.find_by_id(_SOME_USER_ID)
    all_messages: Dict[str, List] = user.get_messages()

    received_message_ids = {message.id for message in all_messages["received"]}
    sent_message_ids = {message.id for message in all_messages["sent"]}

    assert received_message_ids == _RECEIVED_MESSAGES_IDS_BY_SOME_USER
    assert sent_message_ids == _SENT_MESSAGES_IDS_BY_SOME_USER
Example #13
0
def sign_in():
    data_form = request.json
    mobile = data_form.get('mobile', None)
    password1 = data_form.get('password1', None)
    if mobile and password1:
        user = User.find_one(mobile=int(mobile))
        if user and user['isActive'] and User.validate_login(
                user['password'], password1):
            user = load_user(user['id'])
            login_user(user, remember=True)

            return jsonify({"success": True, 'redirect_url': 'admin_panel'})
        else:
            return jsonify({
                "success": False,
                "message": "mobile or password not correct"
            })
    else:
        return jsonify({
            "success": False,
            "message": "mobile or password must not be null"
        })
Example #14
0
def login(email: str, password: str):
    user = User.autenticate(email)

    # TODO: if email is missing, using brute force to get existing users
    #       Consider limit number of tries or show 401 error Bad email or password
    #       Add dummy password to run verify password function to prevent timing attack
    if user is None:
        return errors.not_found("Couldn't find an account with this email.")

    if not user.verify_passw(password, user.password):
        return errors.unauthorized(
            "The email and password did not match our records.")

    return jwt_utils.response_with_tokens(user), 200
category = Category(category='Road accident', favicon='')
category1 = Category(category='Infrastructure accident', favicon='')
category2 = Category(category='Another accident', favicon='')
category3 = Category(category='Accident with animals', favicon='')

status1 = Status(status="new")
status2 = Status(status="on moderation")
status3 = Status(status="open")
status4 = Status(status="closed")
status5 = Status(status="deleted")
status6 = Status(status="pending close")

user1 = User(name='Bob',
             alias='Bobby',
             email='*****@*****.**',
             password='******',
             role_id='1')
user2 = User(name='Mark',
             alias='Marky',
             email='*****@*****.**',
             password='******',
             role_id='2')
user3 = User(name='Maria',
             alias='Mary',
             email='*****@*****.**',
             password='******',
             role_id='3')
user4 = User(name='Petya',
             alias='Petya',
             email='*****@*****.**',
Example #16
0
def authenticate(username, password):
    user = User.find_by_username(username)
    if user and user.password == password:
        return user
Example #17
0
def identity(payload):
    user_id = payload['identity']
    return User.find_by_id(user_id)
Example #18
0
def create_new_message(recipient: int, subject="Lorem", body: str = "Lorem"):
    if (recipient := User.find_by_id(recipient)) is None:
        return errors.bad_request("Recipient is not found.")
Example #19
0
def test_user_delete(app):
    user = User.find_by_id(_SOME_USER_ID)
    assert user.delete()
Example #20
0
def test_some_user_exists(app):
    assert User.find_by_id(_SOME_USER_ID) is not None
Example #21
0
def test_user_create(app):
    user = User.create("Tester", "*****@*****.**", _SOME_USER_PASSWORD)
    assert user.verify_passw(_SOME_USER_PASSWORD, user.password)

    user.save()
    assert user.id == _DEFAULT_USERS_COUNT + 1
Example #22
0
def test_user_autentication_fails(app):
    user = User.autenticate(_SOME_NON_EXISTING_EMAIL)

    assert user is None
Example #23
0
def test_user_authentication(app):
    user = User.autenticate(_SOME_USER_EMAIL)

    assert user is not None
    assert user.id == _SOME_USER_ID
    assert user.email == _SOME_USER_EMAIL
Example #24
0
def delete_user(user: User):
    try:
        user.delete()
        return {}, 204
    except DeleteError as err:
        return errors.internal_error(err.messages), 200