示例#1
0
    def __init__(self, stomach, stale=False):
        Unauthorized.__init__(self)

        realm = stomach.realm
        nonce = stomach.gen_nonce()
        qop = stomach.qop

        self.config = (realm, nonce, [qop], None, 'MD5', stale)
示例#2
0
 def get_response(self, environ=None):
     response = Unauthorized.get_response(self, environ)
     # XXX With werkzeug-0.9 a full-featured Response object is
     # returned: there is no need for this.
     response = Response.force_type(response)
     response.www_authenticate.set_basic(config.realm_name)
     return response
示例#3
0
    def check_auth(self):
        request = ctx.request
        resource = ctx.resource
        auth = request.authorization

        if self._fauth is None:
            import warnings
            warnings.warn("The HTTP basic auth protector doesn't know how to validate "
                          "credentials. Please supply it with an auth_func parameter. "
                          "See the documentation for "
                          "findig.tools.protector.BasicProtector.auth_func.")

        if auth and self._fauth(auth.username, auth.password):
            return auth.username

        else:
            realm = self._realm(resource) if isinstance(self._realm, Callable) else self._realm
            response = Unauthorized().get_response(request)
            response.headers["WWW-Authenticate"] = "Basic realm=\"{}\"".format(realm)
            raise Unauthorized(response=response)
示例#4
0
    def post(self):
        args = parser.parse_args(strict=False)
        token = token_verify_or_raise(token=args["Authorization"], user=args["username"], ip=args["Ipaddress"])
        if token["role"] not in [ROLES_REVIEW_MANAGER, ROLES_EMPLOYER]:
            raise Unauthorized()
        forms_data = []
        parameters = ["FormType", "FormStatus", "Employer", "Member", "SubmittedFrom", "SubmittedTo", "PendingFrom",
                      "FormType"]
        parameters_dict = {}
        for arg in parameters:
            if args[arg] is None:
                parameters_dict[arg] = ""
            else:
                parameters_dict[arg] = args[arg]
        try:
            if parameters_dict["SubmittedFrom"] == "":
                parameters_dict["SubmittedFrom"] = datetime(year=1, month=1, day=1)
            if parameters_dict["SubmittedTo"] == "":
                parameters_dict["SubmittedTo"] = datetime(year=9999, month=1, day=1)
            form_status = parameters_dict["FormStatus"]
            submitted_from = parameters_dict["SubmittedFrom"]
            submitted_to = parameters_dict["SubmittedTo"]
            print(submitted_from)
            print(parameters_dict)
            if parameters_dict["FormType"] == TOKEN_FORMTYPE_TERMINATION or parameters_dict["FormType"] == "":

                termination_form_data = db.session.query(Token, Terminationform).filter(
                    Token.FormID == Terminationform.FormID,
                    Token.FormType == TOKEN_FORMTYPE_TERMINATION,
                    Token.TokenStatus == status.STATUS_ACTIVE,
                    or_(
                        Token.EmployerID.ilike("%" + parameters_dict["Employer"] + "%"),
                        Terminationform.EmployerName.ilike("%" + parameters_dict["Employer"] + "%")),
                    Terminationform.MemberName.ilike("%" + parameters_dict["Member"] + "%"),
                    Terminationform.PendingFrom.ilike("%" + parameters_dict["PendingFrom"] + "%"),
                    Token.FormStatus.ilike("%" + form_status + "%"),
                    Token.FormStatus != status.STATUS_DELETE)
                if submitted_from == submitted_to:
                    termination_form_data = termination_form_data.filter(Token.InitiatedDate >= submitted_to,
                                                                         Token.InitiatedDate < submitted_to + timedelta(
                                                                             days=1))
                else:
                    termination_form_data = termination_form_data.filter(Token.InitiatedDate <= submitted_to,
                                                                         Token.InitiatedDate >= submitted_from)
                print(str(termination_form_data))
                termination_form_data = termination_form_data.order_by(Token.LastModifiedDate.desc()).all()
                # print(termination_form_data)
                for tokens_data, terminations in termination_form_data:
                    forms_data.append({
                        "Token": tokens_data.TokenID,
                        "EmployerID": tokens_data.EmployerID,
                        "EmployerName": terminations.EmployerName,
                        "MemberName": terminations.MemberName,
                        "FormType": tokens_data.FormType,
                        "FormStatus": tokens_data.FormStatus,
                        "LastModifiedDate": tokens_data.LastModifiedDate,
                        "EmailID": terminations.EmailAddress,
                        "PendingFrom": tokens_data.PendingFrom
                    })
                    print(type(tokens_data.InitiatedDate))
                # print(forms_data)
            if parameters_dict["FormType"] == TOKEN_FORMTYPE_ENROLLMENT or parameters_dict["FormType"] == "":
                enrollment_form_data = db.session.query(Token, Enrollmentform).filter(
                    Token.FormID == Enrollmentform.FormID,
                    Token.FormType == TOKEN_FORMTYPE_ENROLLMENT,
                    Enrollmentform.PendingFrom.ilike("%" + parameters_dict["PendingFrom"] + "%"),
                    or_(Enrollmentform.FirstName.ilike("%" + parameters_dict["Member"] + "%"),
                        Enrollmentform.LastName.ilike("%" + parameters_dict["Member"] + "%")),
                    or_(Token.EmployerID.ilike("%" + parameters_dict["Employer"] + "%"),
                        Enrollmentform.EmployerName.ilike("%" + parameters_dict["Employer"] + "%")),
                    Token.TokenStatus == status.STATUS_ACTIVE,
                    Token.FormStatus.ilike("%" + form_status + "%"),
                    Token.FormStatus != status.STATUS_DELETE

                )
                if submitted_from == submitted_to:
                    enrollment_form_data = enrollment_form_data.filter(Token.InitiatedDate >= submitted_to,
                                                                       Token.InitiatedDate < submitted_to + timedelta(
                                                                           days=1)
                                                                       )
                else:
                    enrollment_form_data = enrollment_form_data.filter(Token.InitiatedDate <= submitted_to,
                                                                       Token.InitiatedDate >= submitted_from)
                enrollment_form_data = enrollment_form_data.order_by(Token.LastModifiedDate.desc()).all()
                for tokens_data, enrollments in enrollment_form_data:
                    forms_data.append({
                        "Token": tokens_data.TokenID,
                        "EmployerID": tokens_data.EmployerID,
                        "EmployerName": enrollments.EmployerName,
                        "MemberName": str(
                            enrollments.FirstName if enrollments.FirstName is not None else "") + " " + str(
                            enrollments.LastName if enrollments.LastName is not None else ""),
                        "FormType": tokens_data.FormType,
                        "FormStatus": tokens_data.FormStatus,
                        "LastModifiedDate": tokens_data.LastModifiedDate,
                        "EmailID": enrollments.EmailAddress,
                        "PendingFrom": tokens_data.PendingFrom
                    })
            if token["role"] == ROLES_REVIEW_MANAGER and \
                    (parameters_dict["FormType"] == TOKEN_FORMTYPE_CONTRIBUTION or parameters_dict["FormType"] == "") \
                    and (parameters_dict["Member"] is None or parameters_dict["Member"] == ""):
                contribution_forms = Contributionform.query \
                    .filter(Contributionform.PendingFrom.ilike("%" + parameters_dict["PendingFrom"] + "%"),
                            Contributionform.Status.ilike("%" + form_status + "%"),
                            or_(Contributionform.EmployerID.ilike("%" + parameters_dict["Employer"] + "%"),
                                Contributionform.EmployerName.ilike("%" + parameters_dict["Employer"] + "%")),
                            Contributionform.Status != status.STATUS_DELETE)
                if submitted_from == submitted_to:
                    contribution_forms = contribution_forms.filter(Contributionform.Date >= submitted_to,
                                                                   Contributionform.Date < submitted_to + timedelta(
                                                                       days=1)
                                                                   )
                else:
                    contribution_forms = contribution_forms.filter(Contributionform.Date <= submitted_to,
                                                                   Contributionform.Date >= submitted_from)
                    contribution_forms = contribution_forms.order_by(Contributionform.LastModifiedDate.desc()).all()
                for contributions in contribution_forms:
                    forms_data.append({
                        "FormID": contributions.FormID,
                        "EmployerID": contributions.EmployerID,
                        "EmployerName": contributions.EmployerName,
                        "FormType": "Contribution",
                        "FormStatus": contributions.Status,
                        "PendingFrom": contributions.PendingFrom,
                        "LastModifiedDate": contributions.LastModifiedDate,
                        "FileName": str(contributions.FilePath).replace("/", "\\").split("\\")[
                            len(str(contributions.FilePath).replace("/", "\\").split(
                                "\\")) - 1] if contributions.FilePath is not None else ""
                    })
            return {"forms": forms_data}, 200
        except Exception as e:
            LOG.error("Exception while adding employer to member", e)
            raise InternalServerError("Search failed")
示例#5
0
def patch_request(request_id):
    """
    Modify the given request.

    :param int request_id: the request ID from the URL
    :return: a Flask JSON response
    :rtype: flask.Response
    :raise NotFound: if the request is not found
    :raise ValidationError: if the JSON is invalid
    """
    # Convert the allowed users to lower-case since they are stored in the database as lower-case
    # for consistency
    allowed_users = [user.lower() for user in flask.current_app.config['CACHITO_WORKER_USERNAMES']]
    # current_user.is_authenticated is only ever False when auth is disabled
    if current_user.is_authenticated and current_user.username not in allowed_users:
        raise Unauthorized('This API endpoint is restricted to Cachito workers')

    payload = flask.request.get_json()
    if not isinstance(payload, dict):
        raise ValidationError('The input data must be a JSON object')

    if not payload:
        raise ValidationError('At least one key must be specified to update the request')

    valid_keys = {'dependencies', 'state', 'state_reason'}
    invalid_keys = set(payload.keys()) - valid_keys
    if invalid_keys:
        raise ValidationError(
            'The following keys are not allowed: {}'.format(', '.join(invalid_keys)))

    for key, value in payload.items():
        if key == 'dependencies':
            if not isinstance(value, list):
                raise ValidationError('The value for "dependencies" must be an array')
            for dep in value:
                Dependency.validate_json(dep)
        elif not isinstance(value, str):
            raise ValidationError('The value for "{}" must be a string'.format(key))

    if 'state' in payload and 'state_reason' not in payload:
        raise ValidationError('The "state_reason" key is required when "state" is supplied')
    elif 'state_reason' in payload and 'state' not in payload:
        raise ValidationError('The "state" key is required when "state_reason" is supplied')

    request = Request.query.get_or_404(request_id)
    if 'state' in payload and 'state_reason' in payload:
        last_state = request.last_state
        new_state = payload['state']
        new_state_reason = payload['state_reason']
        # This is to protect against a Celery task getting executed twice and setting the
        # state each time
        if last_state.state_name == new_state and last_state.state_reason == new_state_reason:
            flask.current_app.logger.info('Not adding a new state since it matches the last state')
        else:
            request.add_state(new_state, new_state_reason)

    if 'dependencies' in payload:
        for dep in payload['dependencies']:
            dep_obj = Dependency.query.filter_by(**dep).first()
            if not dep_obj:
                dep_obj = Dependency.from_json(dep)
                db.session.add(dep_obj)

            if dep_obj not in request.dependencies:
                request.dependencies.append(dep_obj)

    db.session.commit()
    if current_user.is_authenticated:
        flask.current_app.logger.info(
            'The user %s patched request %d', current_user.username, request.id)
    else:
        flask.current_app.logger.info('An anonymous user patched request %d', request.id)

    return flask.jsonify(request.to_json()), 200
示例#6
0
 def raise_unauthorized_user():
     raise Unauthorized()
示例#7
0
def require_login_and_ingame():
    if not user_session.get("user_id", False):
        return Unauthorized()

    if not user_session.get("round_id", False):
        return Conflict("User is not in a game.")
示例#8
0
 def decorated_function(*args, **kwargs):
     if not session.get('csrf') or session.get('unconfirmed'):
         raise Unauthorized()
     return f(*args, **kwargs)
示例#9
0
def abort_unauthorized(description):
    """Raise an Unauthorized exception.
    """
    raise Unauthorized(description=description)
示例#10
0
def test_error_401(app):
    with app.app_context():
        result = error_401(Unauthorized())
        assert 'error' in result.json
        assert result.json['error'] == "Unauthorized"
        assert result == 401
示例#11
0
文件: user.py 项目: Blati/RSOI_5
def user_bookings_add(username, page):

    with open("{}/tokens/token.json".format(root_dir()), "r") as ff:
        try:
            token = json.load(ff)
        except:
            raise Unauthorized()
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(token['access_token'])
    }
    auth_check = requests.get("http://127.0.0.1:5004/check", headers=headers)
    auth_check = auth_check.json()
    if auth_check['msg'] != 'OK':
        raise Unauthorized(auth_check['msg'])

    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(token['refresh_token'])
    }
    if auth_check['msg'] == 'Token has expired':
        auth_refresh = requests.post("http://127.0.0.1:5004/refresh",
                                     headers=headers)

    if username not in users:
        raise NotFound("User '{}' not found.".format(username))

    if request.method == 'GET':
        result = {}
        try:
            showtimes = requests.get(
                "http://127.0.0.1:5002/showtimes/{}".format(page))
        except requests.exceptions.ConnectionError:
            raise ServiceUnavailable("The Showtimes service is unavailable.")

        showtimes = showtimes.json()

        for movieid in showtimes:
            result[movieid] = []
            try:
                movies_resp = requests.get(
                    "http://127.0.0.1:5001/movies/{}".format(movieid))
            except requests.exceptions.ConnectionError:
                raise ServiceUnavailable("The Movie service is unavailable.")
            try:
                movies_resp = movies_resp.json()
            except ValueError:
                raise ServiceUnavailable("Sorry! No movies in this day.")
            result[movieid].append({
                "title": movies_resp["title"],
                "rating": movies_resp["rating"]
            })

        return nice_json(result)

    if request.method == 'POST':
        raw = request.get_json()
        try:
            user_resp = requests.get(
                "http://127.0.0.1:5000/users/{}".format(username))
        except:
            raise ServiceUnavailable(
                "Sorry, service unavailable at the moment!")
        try:
            result = requests.post(
                "http://127.0.0.1:5003/bookings/{}/add".format(username),
                json={username: raw})
        except:
            raise ServiceUnavailable(
                "Sorry, service unavailable at the moment!")
        result = result.json()
        user_resp = user_resp.json()
        content = {
            "id": user_resp["id"],
            "name": user_resp["name"],
            "last_active": 0
        }
        content = {username: content}
        with open("{}/database/users.json".format(root_dir())) as ff:
            data = json.load(ff)

        data.update(content)
        with open("{}/database/users.json".format(root_dir()), "w+") as ff:
            json.dump(data, ff)
        users.update(content)
        return nice_json(result)

    raise NotImplementedError()
示例#12
0
 def jwt_expired_token_callback(self):
     raise Unauthorized("Your auth token has expired")
示例#13
0
 def jwt_revoked_token_loader_callback():
     raise Unauthorized("Token has been revoked")
示例#14
0
 def jwt_unauthorized_callback(self):
     raise Unauthorized("Your auth token or CSRF token are missing")
示例#15
0
 def jwt_invalid_token_loader_callback(self):
     raise Unauthorized("Your auth token or CSRF token are invalid")
示例#16
0
 def endpoint(*args, **kwargs):
     if not g.auth_user:
         raise Unauthorized('Not authenticated.')
     return f(*args, **kwargs)
示例#17
0
def _get_auth_header(auth_token):
    if current_app.config['use_caas']:
        if auth_token:
            return {"Authorization": str(auth_token)}
        else:
            raise Unauthorized('User not authorized to access this resource.')
示例#18
0
 def authenticate(self, request):
     valid_user = request.authorization and self.is_valid_user(
         request.authorization.get('username'),
         request.authorization.get('password'))
     if not valid_user:
         raise Unauthorized()
示例#19
0
def test_error_401_custom_description(app):
    with app.app_context():
        result = error_401(Unauthorized("You shall not pass."))
        assert 'error' in result.json
        assert result.json['error'] == "You shall not pass."
        assert result == 401
示例#20
0
    def get(self):
        args = parser.parse_args(strict=False)
        token = token_verify_or_raise(token=args["Authorization"], user=args["username"], ip=args["Ipaddress"])
        offset = args["offset"]
        if offset is None or str(offset) == "":
            offset = 0
        offset = int(offset)
        if token["role"] not in [roles.ROLES_HR, roles.ROLES_EMPLOYER, roles.ROLES_REVIEW_MANAGER]:
            raise Unauthorized()
        if args["role"] == roles.ROLES_REVIEW_MANAGER:
            if token["role"] != roles.ROLES_REVIEW_MANAGER:
                raise Unauthorized()
            forms_data = []
            enrollment_form_data = db.session.query(Token, Enrollmentform).filter(
                Token.FormID == Enrollmentform.FormID,
                Token.TokenStatus == status.STATUS_ACTIVE,
                Token.FormType == TOKEN_FORMTYPE_ENROLLMENT).order_by(Token.LastModifiedDate.desc()) \
                .offset(offset) \
                .limit(25).all()

            for tokens_data, enrollments in enrollment_form_data:
                forms_data.append({
                    "Token": tokens_data.TokenID,
                    "EmployerID": tokens_data.EmployerID,
                    "MemberName": str(enrollments.FirstName if enrollments.FirstName is not None else "") + " " + str(enrollments.LastName if enrollments.LastName is not None else ""),
                    "FormType": tokens_data.FormType,
                    "EmployerName": enrollments.EmployerName,
                    "FormStatus": tokens_data.FormStatus,
                    "LastModifiedDate": tokens_data.LastModifiedDate,
                    "EmailID": enrollments.EmailAddress,
                    "PendingFrom": tokens_data.PendingFrom
                })

            termination_form_data = db.session.query(Token, Terminationform).filter(
                Token.FormID == Terminationform.FormID,
                Token.TokenStatus == status.STATUS_ACTIVE,
                Token.FormType == TOKEN_FORMTYPE_TERMINATION).order_by(Token.LastModifiedDate.desc()) \
                .offset(offset) \
                .limit(25).all()

            for tokens_data, terminations in termination_form_data:
                forms_data.append({
                    "Token": tokens_data.TokenID,
                    "EmployerID": tokens_data.EmployerID,
                    "MemberName": terminations.MemberName,
                    "EmployerName": terminations.EmployerName,
                    "FormType": tokens_data.FormType,
                    "FormStatus": tokens_data.FormStatus,
                    "LastModifiedDate": tokens_data.LastModifiedDate,
                    "EmailID": terminations.EmailAddress,
                    "PendingFrom": tokens_data.PendingFrom
                })

            contribution_forms = Contributionform.query.filter(Contributionform.Status != status.STATUS_DELETE)\
                .order_by(Contributionform.LastModifiedDate.desc()).all()
            for contributions in contribution_forms:
                forms_data.append({
                    "FormID": contributions.FormID,
                    "EmployerID": contributions.EmployerID,
                    "EmployerName": contributions.EmployerName,
                    "FormType": "Contribution",
                    "FormStatus": contributions.Status,
                    "LastModifiedDate": contributions.LastModifiedDate,
                    "PendingFrom": contributions.PendingFrom,
                    "FileName": str(contributions.FilePath).replace("/", "\\").split("\\")[len(str(contributions.FilePath).replace("/", "\\").split("\\")) - 1] if contributions.FilePath is not None else ""
                })
            # documents = Documents.query.order_by(Documents.Date.desc()).all()
            # for document in documents:
            #     forms_data.append({
            #         "FormID": document.FormID,
            #         "EmployerID": document.EmployerID,
            #         "EmployerName": document.EmployerName,
            #         "FormType": "Document",
            #         "FormStatus": document.Status,
            #         "LastModifiedDate": document.LastModifiedDate,
            #         "PendingFrom": document.PendingFrom,
            #         "FileName": str(document.FilePath).replace("/", "\\").split("\\")[len(
            #             str(document.FilePath).replace("/", "\\").split(
            #                 "\\")) - 1] if document.FilePath is not None else ""
            #     })
            #     print("form_data", forms_data)
            return {"myforms": forms_data}, 200
        elif args["role"] == roles.ROLES_EMPLOYER:
            employer_id = args["user"]
            offset = args["offset"]
            if offset is None or str(offset) == "":
                offset = 0
            forms_data = []
            enrollment_form_data = db.session.query(Token, Enrollmentform).filter(
                Token.FormID == Enrollmentform.FormID,
                Token.TokenStatus == status.STATUS_ACTIVE,
                Token.EmployerID == employer_id,
                Token.FormType == TOKEN_FORMTYPE_ENROLLMENT).order_by(Token.LastModifiedDate.desc()) \
                .offset(offset) \
                .limit(25).all()

            for tokens_data, enrollments in enrollment_form_data:
                forms_data.append({
                    "Token": tokens_data.TokenID,
                    "EmployerID": tokens_data.EmployerID,
                    "MemberName": str(enrollments.FirstName if enrollments.FirstName is not None else "") + " " + str(enrollments.LastName if enrollments.LastName is not None else ""),
                    "FormType": tokens_data.FormType,
                    "EmployerName": enrollments.EmployerName,
                    "FormStatus": tokens_data.FormStatus,
                    "LastModifiedDate": tokens_data.LastModifiedDate,
                    "EmailID": enrollments.EmailAddress,
                    "PendingFrom": tokens_data.PendingFrom
                })

            termination_form_data = db.session.query(Token, Terminationform).filter(
                Token.FormID == Terminationform.FormID,
                Token.TokenStatus == status.STATUS_ACTIVE,
                Token.EmployerID == employer_id,
                Token.FormType == TOKEN_FORMTYPE_TERMINATION).order_by(Token.LastModifiedDate.desc()) \
                .offset(offset) \
                .limit(25).all()

            for tokens_data, terminations in termination_form_data:
                forms_data.append({
                    "Token": tokens_data.TokenID,
                    "EmployerID": tokens_data.EmployerID,
                    "MemberName": terminations.MemberName,
                    "EmployerName": terminations.EmployerName,
                    "FormType": tokens_data.FormType,
                    "FormStatus": tokens_data.FormStatus,
                    "LastModifiedDate": tokens_data.LastModifiedDate,
                    "EmailID": terminations.EmailAddress,
                    "PendingFrom": tokens_data.PendingFrom
                })
            # contribution_forms = Contributionform.query.order_by(Contributionform.LastModifiedDate.desc()).all()
            # for contributions in contribution_forms:
            #     forms_data.append({
            #         "FormID": contributions.FormID,
            #         "EmployerID": contributions.EmployerID,
            #         "FormType": "Contribution",
            #         "FormStatus": contributions.Status,
            #         "LastModifiedDate": contributions.LastModifiedDate,
            #         "FilePath": contributions.FilePath
            #     })

            return {"myforms": forms_data}, 200
示例#21
0
 def side_effect_function(*args, **kwargs):
     raise Unauthorized("Unable to get valid credentials")
示例#22
0
 def write(self):
     """Initial writes allowed, and updates if same patient"""
     if not self._kc_ident_in_resource():
         raise Unauthorized("authorized identifier not found")
     return True
示例#23
0
文件: v1.py 项目: dkraklan/ADReset2
def reset_password():
    """
    Reset a user's password using their secret answers.

    :rtype: flask.Response
    """
    req_json = request.get_json(force=True)
    _validate_api_input(req_json, 'answers', list)
    _validate_api_input(req_json, 'new_password', string_types)
    _validate_api_input(req_json, 'username', string_types)
    answers = req_json['answers']
    new_password = req_json['new_password']
    username = req_json['username']

    not_setup_msg = (
        'You must have configured at least {0} secret answers before resetting your '
        'password').format(current_app.config['REQUIRED_ANSWERS'])
    # Verify the user exists in the database
    ad = adreset.ad.AD()
    ad.service_account_login()
    user_id = User.get_id_from_ad_username(username, ad)
    if not user_id:
        msg = 'The user attempted a password reset but does not exist in the database'
        log.debug({'message': msg, 'user': username})
        raise ValidationError(not_setup_msg)

    # Make sure the user isn't locked out
    if User.is_user_locked_out(user_id):
        msg = 'The user attempted a password reset but their account is locked in ADReset'
        log.info({'message': msg, 'user': username})
        raise Unauthorized('Your account is locked. Please try again later.')

    db_answers = Answer.query.filter_by(user_id=user_id).all()
    # Create a dictionary of question_id to answer from entries in the database. This will avoid
    # the need to continuously loop through these answers looking for specific answers later on.
    q_id_to_answer_db = {}
    for answer in db_answers:
        q_id_to_answer_db[answer.question_id] = answer.answer

    # Make sure the user has all their answers configured
    if len(q_id_to_answer_db.keys()) != current_app.config['REQUIRED_ANSWERS']:
        msg = (
            'The user did not have their secret answers configured and attempted to reset their '
            'password')
        log.debug({'message': msg, 'user': username})
        raise ValidationError(not_setup_msg)

    seen_question_ids = set()
    for answer in answers:
        if not isinstance(
                answer,
                dict) or 'question_id' not in answer or 'answer' not in answer:
            raise ValidationError(
                'The answers must be an object with the keys "question_id" and "answer"'
            )
        _validate_api_input(answer, 'question_id', int)
        _validate_api_input(answer, 'answer', string_types)

        if answer['question_id'] not in q_id_to_answer_db:
            msg = (
                'The user answered a question they did not previously configure while '
                'attempting to reset their password')
            log.info({'message': msg, 'user': username})
            raise ValidationError(
                'One of the answers was to a question that wasn\'t previously configured'
            )
        # Don't allow an attacker to enter in the same question and answer combination more than
        # once
        if answer['question_id'] in seen_question_ids:
            msg = (
                'The user answered the same question multiple times while attempting to reset '
                'their password')
            log.info({'message': msg, 'user': username})
            raise ValidationError(
                'You must answer {0} different questions'.format(
                    current_app.config['REQUIRED_ANSWERS']))
        seen_question_ids.add(answer['question_id'])

    # Only check if the answers are correct after knowing the input is valid as to not give away
    # any hints as to which answer is incorrect for an attacker
    for answer in answers:
        if current_app.config['CASE_SENSITIVE_ANSWERS'] is True:
            input_answer = answer['answer']
        else:
            input_answer = answer['answer'].lower()
        is_correct_answer = Answer.verify_answer(
            input_answer, q_id_to_answer_db[answer['question_id']])
        if is_correct_answer is not True:
            log.info({
                'message': 'The user entered an incorrect answer',
                'user': username
            })
            failed_attempt = FailedAttempt(user_id=user_id,
                                           time=datetime.utcnow())
            db.session.add(failed_attempt)
            db.session.commit()

            if User.is_user_locked_out(user_id):
                msg = 'The user failed too many password reset attempts. They are now locked out.'
                log.info({'message': msg, 'user': username})
                raise Unauthorized(
                    'You have answered incorrectly too many times. Your account is '
                    'now locked. Please try again later.')
            raise Unauthorized(
                'One or more answers were incorrect. Please try again.')

    log.debug({
        'message': 'The user successfully answered their questions',
        'user': username
    })
    ad.reset_password(username, new_password)
    log.info({
        'message': 'The user successfully reset their password',
        'user': username
    })
    return jsonify({}), 204
示例#24
0
 def unauth_read(self):
     """Override for unauthenticated reads (i.e. no token)"""
     raise Unauthorized(
         f"Unauthorized; can't view {self.resource['resourceType']}")
示例#25
0
 def raise_invalid_credentials():
     raise Unauthorized(description="Invalid email or password.")
示例#26
0
 def write(self):
     """Default case, no FHIR objects writeable"""
     raise Unauthorized(f"can't write {self.resource['resourceType']}")
示例#27
0
 def authenticate(self, token: str, *args, **kw) -> User:
     try:
         return User.query.filter_by(token=token).one()
     except (ResourceNotFound, DataError):
         raise Unauthorized('Provide a suitable token.')
示例#28
0
 def unauth_read(self):
     """Only allow if no patient is set in CarePlan"""
     if self.resource.get('subject'):
         raise Unauthorized(
             "Unauthorized can't view CarePlan with well defined 'subject'")
     return True
示例#29
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        This is the authentication to self service. If you want to do
        ANYTHING with the selfservice, you need to be authenticated. The
        _before_ is executed before any other function in this controller.

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context["action"]

        try:
            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            c.version_ref = base64.encodebytes(c.version.encode())[:6]

            g.audit["success"] = False
            self.client = get_client(request)
            g.audit["client"] = self.client

            # -------------------------------------------------------------- --

            # handle requests which dont require authetication

            if action in ["logout", "custom_style"]:
                return

            # -------------------------------------------------------------- --

            # get the authenticated user

            auth_type, auth_user, auth_state = get_auth_user(request)

            # -------------------------------------------------------------- --

            # handle not authenticated requests

            if not auth_user or auth_type not in ["user_selfservice"]:

                if action in ["login"]:
                    return

                if action in ["index"]:
                    return redirect(url_for(".login"))

                else:
                    raise Unauthorized("No valid session")

            # -------------------------------------------------------------- --

            # handle authenticated requests

            # there is only one special case, which is the login that
            # could be forwarded to the index page

            if action in ["login"]:
                if auth_state != "authenticated":
                    return

                return redirect(url_for(".index"))

            # -------------------------------------------------------------- --

            # in case of user_selfservice, an unauthenticated request should
            # always go to login
            if (
                auth_user
                and auth_type == "user_selfservice"
                and auth_state != "authenticated"
            ):
                return redirect(url_for(".login"))

            # futher processing with the authenticated user

            if auth_state != "authenticated":
                raise Unauthorized("No valid session")

            c.user = auth_user.login
            c.realm = auth_user.realm
            self.authUser = auth_user

            # -------------------------------------------------------------- --

            # authenticated session verification

            if auth_type == "user_selfservice":

                # checking the session only for not_form_access actions
                if action not in self.form_access_methods:

                    valid_session = check_session(
                        request, auth_user, self.client
                    )

                    if not valid_session:
                        g.audit["action"] = request.path[1:]
                        g.audit["info"] = "session expired"
                        current_app.audit_obj.log(g.audit)

                        raise Unauthorized("No valid session")

            # -------------------------------------------------------------- --

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = get_selfservice_actions(self.authUser)
            c.actions = actions

            for action_name, action_value in actions.items():
                if action_value is True:
                    c.__setattr__(action_name, -1)
                    continue
                c.__setattr__(action_name, action_value)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(
                config, c.actions
            )

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(
                config, actions
            )
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1

            c.pin_policy = _get_auth_PinPolicy(user=self.authUser)

        except (flap.HTTPUnauthorized, flap.HTTPForbidden) as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r", action, acc)
            db.session.rollback()
            raise acc

        except Exception as exx:
            log.error("[__before__] failed with error: %r", exx)
            db.session.rollback()
            return sendError(response, exx, context="before")
示例#30
0
 def write(self):
     """Initial writes allowed, and updates if same patient"""
     if not self.user.patient_id():
         return True
     if not self.owned:
         raise Unauthorized("Write CarePlan failed; mismatched owner")
示例#31
0
RESOURCE = "test-resource"
EMAIL = "*****@*****.**"
PUBLIC_KEY = {"kid": 1, "foo": "bar"}
JWKS = {"keys": [PUBLIC_KEY, {"kid": 2, "baz": "buz"}]}
HEADER = {"kid": 1}
PAYLOAD = {"email": EMAIL}


def make_raiser(exception):
    def raise_e(*args, **kwargs):
        raise exception

    return raise_e


throw_auth_error = make_raiser(Unauthorized("foo"))


@pytest.fixture
def bearer_auth(monkeypatch):
    monkeypatch.setattr("config.secrets.CloudStorageSecretManager", MagicMock)
    return BearerAuth()


def test_check_auth_smoketest(monkeypatch, app, bearer_auth):
    """Check that authentication succeeds if no errors are thrown"""
    # No authentication errors
    monkeypatch.setattr(bearer_auth, "token_auth", lambda _: PAYLOAD)
    # No authorization errors
    def fake_role_auth(*args):
        _request_ctx_stack.top.current_user = Users(email=EMAIL)
示例#32
0
 def test_handle_error_401_no_challenge_by_default(self, api):
     resp = api.handle_error(Unauthorized())
     assert resp.status_code == 401
     assert 'WWW-Autheneticate' not in resp.headers
示例#33
0
 def test_handle_error_401_sends_challege_configured_realm(self, api):
     resp = api.handle_error(Unauthorized())
     assert resp.status_code == 401
     assert resp.headers['WWW-Authenticate'] == 'Basic realm="test-realm"'
示例#34
0
 def get_response(self, environ=None):
     response = Unauthorized.get_response(self, environ)
     response.www_authenticate.set_digest(*self.config)
     return response