def verify_user_code(user_id): data = request.get_json() validate(data, post_verify_code_schema) user_to_verify = get_user_by_id(user_id=user_id) code = get_user_code(user_to_verify, data['code'], data['code_type']) if(verify_within_time(user_to_verify) >= 2): raise InvalidRequest("Code already sent", status_code=400) if user_to_verify.failed_login_count >= current_app.config.get('MAX_VERIFY_CODE_COUNT'): raise InvalidRequest("Code not found", status_code=404) if not code: increment_failed_login_count(user_to_verify) raise InvalidRequest("Code not found", status_code=404) if datetime.utcnow() > code.expiry_datetime: # sms and email increment_failed_login_count(user_to_verify) raise InvalidRequest("Code has expired", status_code=400) if code.code_used: increment_failed_login_count(user_to_verify) raise InvalidRequest("Code has already been used", status_code=400) user_to_verify.current_session_id = str(uuid.uuid4()) user_to_verify.logged_in_at = datetime.utcnow() user_to_verify.failed_login_count = 0 save_model_user(user_to_verify) use_user_code(code.id) return jsonify({}), 204
def send_user_2fa_code(user_id, code_type): user_to_send_to = get_user_by_id(user_id=user_id) if (verify_within_time(user_to_send_to, age=timedelta(seconds=10)) >= 1): raise InvalidRequest("Code already sent, wait 10 seconds", status_code=400) if count_user_verify_codes(user_to_send_to) >= current_app.config.get( 'MAX_VERIFY_CODE_COUNT'): # Prevent more than `MAX_VERIFY_CODE_COUNT` active verify codes at a time current_app.logger.warning( 'Too many verify codes created for user {}'.format( user_to_send_to.id)) else: data = request.get_json() if code_type == SMS_TYPE: validate(data, post_send_user_sms_code_schema) send_user_sms_code(user_to_send_to, data) elif code_type == EMAIL_TYPE: validate(data, post_send_user_email_code_schema) send_user_email_code(user_to_send_to, data) else: abort(404) return '{}', 204
def test_will_find_verify_codes_sent_within_seconds(notify_api, notify_db, notify_db_session, sample_user): make_verify_code(sample_user) make_verify_code(sample_user, timedelta(seconds=10)) make_verify_code(sample_user, timedelta(seconds=32)) make_verify_code(sample_user, timedelta(hours=1)) count = verify_within_time(sample_user) assert count == 2