Пример #1
0
def reset():  # pragma: no cover
    response = {'status': 'ok', 'message': '', 'payload': []}
    data = request.get_json()

    request_types = {
        'username': ['str'],
        'email': ['str'],
    }
    validate_request_data(data, request_types)

    user = User.find_by_username(data['username'])
    if user and user.email == data['email'] and not user.is_active:
        lettersAndDigits = string.ascii_letters + string.digits
        newpass = ''.join(random.choice(lettersAndDigits) for i in range(10))
        passhash = User.generate_hash(newpass)

        user.req_pass_reset = True
        user.password = passhash

        mailbody = '''
        <h2>Password reset information</h2>
        <strong>username: </strong>''' + data['username'] + '''<br>
        <strong>new pass: </strong>''' + newpass + '''
        '''
        # SEND EMAIL TO USER ++> Not implemented
        db.session.commit()
        create_log(current_user, 'modify', 'User requested password reset',
                   'E-mail sent')
    response[
        'message'] = 'Password for {} sent to {} if credentials were correct. Check your email for instructions.'.format(
            data['username'], data['email'])

    return jsonify(response), 201
Пример #2
0
def reset_token():

    print("NOW WE'RE RESETING TOKEN\n\n")
    print("A PUERAA\n\n")

    token = request.headers.get('access_token')
    print(token)

    print("\n\n")
    print("this is:")
    payload = decode_token(token)['identity']

    print(payload)

    enteredOTP = request.form.get('OTP')

    # reset new password after OTP matches
    if (enteredOTP == payload['OTP']):
        enteredNewPassword = request.form.get('new_password')
        enteredConfirmNewPassword = request.form.get('confirm_new_password')

        if (enteredConfirmNewPassword == enteredNewPassword):
            user = User.query.get_or_404(payload['userid'])
            # newHashedPassword = hash_password(enteredNewPassword)
            newHashedPassword = User.generate_hash(enteredNewPassword)

            user.password = newHashedPassword
            user.save()
        else:
            abort(400, message="passwords don't match")

    else:
        abort(401, message="OTP not match")

    responseMsg = {"status": 200, "message": "Password reset success."}

    return responseMsg
Пример #3
0
def update_user_password(id):
    response = {'status': '', 'message': '', 'payload': []}
    data = request.get_json()

    if id != current_user.id:
        raise UnauthorizedError(
            "Can't modify the password for a different user than yourself.")

    # input validation
    request_types = {
        'password': ['str'],
        'newpassword': ['str'],
    }
    validate_request_data(data, request_types)

    if len(data['newpassword']) < 8:
        raise InputError("Password length must be greater than 8.")
    if not any(x.isupper() for x in data['newpassword']):
        raise InputError("Password must contain a capital letter.")
    if not any(x.lower() for x in data['newpassword']):
        raise InputError("Password must contain a lowercase letter.")
    if not any(x.isdigit() for x in data['newpassword']):
        raise InputError("Password must contain a number.")

    query = User.find_by_id(id)
    if not User.verify_hash(data['password'], query.password):
        raise UnauthorizedError("Password Invalid")

    query.password = User.generate_hash(data['newpassword'])
    query.req_pass_reset = False

    db.session.commit()
    response['message'] = 'Password changed'
    create_log(current_user, 'modify', 'User changed password for User',
               'ID: ' + str(id))

    return jsonify(response), 201
Пример #4
0
def seed_users(data):
    print("\n\033[34mSEED Users\033[0m\n")
    with api.app_context():
        try:
            for entry in data:
                new_user = User(
                    email=entry["email"],
                    first_name=entry["first_name"],
                    last_name=entry["last_name"],
                    username=entry["username"],
                    password=User.generate_hash(entry["password"]),
                    initials=entry["initials"],
                    role=entry["role"],
                )
                if "is_system_administrator" in entry.keys():
                    new_user.is_system_administrator = True
                if "is_superuser" in entry.keys():
                    new_user.is_superuser = True
                db.session.add(new_user)
            db.session.commit()
        except Exception as e:
            print("\n\t\033[31mERROR\033[0m => users\n")
            print(e)
            db.session.rollback()
Пример #5
0
def create_user():
    response = {'status': 'ok', 'message': '', 'payload': []}
    data = request.get_json()

    # input validation
    request_types = {
        'username': ['str'],
        'password': ['str'],
        'email': ['str'],
        'initials': ['str'],
        'first_name': ['str'],
        'last_name': ['str'],
        'role': ['str']
    }
    validate_request_data(data, request_types)
    # PASSWORD STRENGTH CHECKING
    if len(data['password']) < 8:
        raise InputError("Password length must be greater than 8.")
    if not any(x.isupper() for x in data['password']):
        raise InputError("Password must contain a capital letter.")
    if not any(x.lower() for x in data['password']):
        raise InputError("Password must contain a lowercase letter.")
    if not any(x.isdigit() for x in data['password']):
        raise InputError("Password must contain a number.")
    # Length checking
    if len(data['username']) < 1 or len(data['username']) > 64:
        raise InputError(
            'Username must be greater than 1 character and no more than 64')
    if len(data['password']) < 8 or len(data['password']) > 128:
        raise InputError(
            'Password must be greater than 1 character and no more than 128')
    if len(data['email']) < 1 or len(data['email']) > 128:
        raise InputError(
            'Password must be greater than 8 character and no more than 128')
    if not re.match(r".*\@.+(?:\..+)+", data['email']):
        raise InputError('E-mail must be of a valid e-mail format.')
    if len(data['initials']) < 1 or len(data['initials']) > 128:
        raise InputError(
            'Password must be greater than 1 character and no more than 128')
    if len(data['first_name']) < 1 or len(data['first_name']) > 128:
        raise InputError(
            'Password must be greater than 1 character and no more than 128')
    if len(data['last_name']) < 1 or len(data['last_name']) > 128:
        raise InputError(
            'Password must be greater than 1 character and no more than 128')

    # check if this username exists
    check = User.query.filter_by(username=data['username']).first()
    if check:
        raise InputError('Username {} already exists.'.format(
            data['username']))
    # check if this email exists
    check = User.query.filter_by(email=data['email']).first()
    if check:
        raise InputError('User email {} already exists.'.format(data['email']))
    # check if these initials exist
    check = User.query.filter_by(initials=data['initials']).first()
    if check:
        raise InputError('User initials {} already exist.'.format(
            data['initials']))

    # ENUM check
    if data['role'] not in Roles.__members__:
        raise InputError('Specified role does not exists')

    # INSERT user
    new_user = User(
        username=data['username'],
        password=User.generate_hash(data['password']),
        email=data['email'],
        initials=data['initials'].upper(),
        first_name=data['first_name'],
        last_name=data['last_name'],
        role=data['role'],
    )
    db.session.add(new_user)
    db.session.flush()

    db.session.commit()
    response['message'] = 'Created user {}'.format(data['username'])
    response['payload'] = [User.find_by_id(new_user.id).serialize]
    create_log(current_user, 'modify', 'User created a new User',
               'New Username: '******'username']))

    return jsonify(response), 201