def create_session(data):
user = User.find_by_email_or_username(data['username'])
if not (user and user.password == data['password']):
return make_error_response('Invalid username/password combination', 401)
session = Session(user=user)
# TODO can this be made more accurate?
session.ip_address = request.remote_addr
if request.user_agent:
session.user_agent = request.user_agent.string
# Denormalize user agent
session.platform = request.user_agent.platform
session.browser = request.user_agent.browser
db.session.add(session)
db.session.commit()
return session
python类remote_addr()的实例源码
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if request.method == 'POST' and form.validate_on_submit():
username = form.username.data
if '@' in username:
existing_user = User.query.filter_by(email=username).first()
else:
existing_user = User.query.filter_by(username=username).first()
if not (existing_user and existing_user.check_password(form.password.data)):
flash('Invalid username or password. Please try again.', 'warning')
return render_template('login.html', form=form)
login_user(existing_user)
db.session.add(Connection(user=existing_user, address=request.remote_addr))
db.session.commit()
return redirect(url_for('index'))
if form.errors:
flash(form.errors, 'danger')
return render_template('login.html', form=form)
def access_write_task(original_requester, key=None):
"""
Determine whether a requester can write to a task or its runs.
"""
requester = request.remote_addr
# Local interfaces are always okay.
if requester in local_ips:
return True
# Tasks without keys are limited to the original requester only
if key is None:
return requester == original_requester
# Beyond here, the task has a key.
request_key = arg_string("key")
return (request_key is not None) and (request_key == key)
def get_role_credentials(api_version, requested_role, junk=None):
try:
role_params = roles.get_role_params_from_ip(
request.remote_addr,
requested_role=requested_role
)
except roles.UnexpectedRoleError:
return '', 403
try:
assumed_role = roles.get_assumed_role_credentials(
role_params=role_params,
api_version=api_version
)
except roles.GetRoleError as e:
return '', e.args[0][0]
return jsonify(assumed_role)
def zmirror_status():
"""????????????"""
if request.remote_addr and request.remote_addr != '127.0.0.1':
return generate_simple_resp_page(b'Only 127.0.0.1 are allowed', 403)
output = ""
output += strx('extract_real_url_from_embedded_url', extract_real_url_from_embedded_url.cache_info())
output += strx('\nis_content_type_streamed', is_mime_streamed.cache_info())
output += strx('\nembed_real_url_to_embedded_url', embed_real_url_to_embedded_url.cache_info())
output += strx('\ncheck_global_ua_pass', check_global_ua_pass.cache_info())
output += strx('\nextract_mime_from_content_type', extract_mime_from_content_type.cache_info())
output += strx('\nis_content_type_using_cdn', is_content_type_using_cdn.cache_info())
output += strx('\nis_ua_in_whitelist', is_content_type_using_cdn.cache_info())
output += strx('\nis_mime_represents_text', is_mime_represents_text.cache_info())
output += strx('\nis_domain_match_glob_whitelist', is_domain_match_glob_whitelist.cache_info())
output += strx('\nverify_ip_hash_cookie', verify_ip_hash_cookie.cache_info())
output += strx('\nis_denied_because_of_spider', is_denied_because_of_spider.cache_info())
output += strx('\nis_ip_not_in_allow_range', is_ip_not_in_allow_range.cache_info())
output += strx('\n\ncurrent_threads_number', threading.active_count())
# output += strx('\nclient_requests_text_rewrite', client_requests_text_rewrite.cache_info())
# output += strx('\nextract_url_path_and_query', extract_url_path_and_query.cache_info())
output += strx('\n----------------\n')
output += strx('\ndomain_alias_to_target_set', domain_alias_to_target_set)
return "<pre>" + output + "</pre>\n"
def retrieveAlertsJson():
""" Retrieve last 5 Alerts in JSON without IPs """
# set cacheItem independent from url parameters, respect community index
cacheEntry = request.url
# get result from cache
getCacheResult = getCache(cacheEntry, "url")
if getCacheResult is not False:
app.logger.debug('Returning /retrieveAlertsJson from Cache %s' % str(request.remote_addr))
return jsonify(getCacheResult)
# query ES
else:
numAlerts = 35
# Retrieve last X Alerts from ElasticSearch and return JSON formatted with limited alert content
returnResult = formatAlertsJson(queryAlertsWithoutIP(numAlerts, checkCommunityIndex(request)))
setCache(cacheEntry, returnResult, 25, "url")
app.logger.debug('UNCACHED %s' % str(request.url))
return jsonify(returnResult)
def accept_webhook():
try:
log.debug("POST request received from {}.".format(request.remote_addr))
data = json.loads(request.data)
if type(data) == dict: # older webhook style
data_queue.put(data)
else: # For RM's frame
for frame in data:
data_queue.put(frame)
except Exception as e:
log.error("Encountered error while receiving webhook ({}: {})".format(type(e).__name__, e))
abort(400)
return "OK" # request ok
# Thread used to distribute the data into various processes (for RocketMap format)
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
response = request.json.get('g-recaptcha-response', '')
else:
response = request.form.get('g-recaptcha-response', '')
remote_ip = request.remote_addr
if not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
response = request.json.get('g-recaptcha-response', '')
else:
response = request.form.get('g-recaptcha-response', '')
remote_ip = request.remote_addr
if not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def get_accounts():
system_id = request.args.get('system_id')
if not system_id:
log.error("Request from {} is missing system_id".format(request.remote_addr))
abort(400)
count = int(request.args.get('count', 1))
min_level = int(request.args.get('min_level', 1))
max_level = int(request.args.get('max_level', 40))
reuse = parse_bool(request.args.get('reuse')) or parse_bool(request.args.get('include_already_assigned'))
banned_or_new = parse_bool(request.args.get('banned_or_new'))
# lat = request.args.get('latitude')
# lat = float(lat) if lat else lat
# lng = request.args.get('longitude')
# lng = float(lng) if lng else lng
log.info(
"System ID [{}] requested {} accounts level {}-{} from {}".format(system_id, count, min_level, max_level,
request.remote_addr))
accounts = Account.get_accounts(system_id, count, min_level, max_level, reuse, banned_or_new)
if len(accounts) < count:
log.warning("Could only deliver {} accounts.".format(len(accounts)))
return jsonify(accounts[0] if accounts and count == 1 else accounts)
def log_exception(self, exc_info):
self.logger.error("""
Path: %s
HTTP Method: %s
Client IP Address: %s
User Agent: %s
User Platform: %s
User Browser: %s
User Browser Version: %s
GET args: %s
view args: %s
URL: %s
""" % (
request.path,
request.method,
request.remote_addr,
request.user_agent.string,
request.user_agent.platform,
request.user_agent.browser,
request.user_agent.version,
dict(request.args),
request.view_args,
request.url
), exc_info=exc_info)
def log_request(code='-'):
proto = request.environ.get('SERVER_PROTOCOL')
msg = request.method + ' ' + request.path + ' ' + proto
code = str(code)
if code[0] == '1': # 1xx - Informational
msg = color(msg, attrs=['bold'])
if code[0] == '2': # 2xx - Success
msg = color(msg, color='white')
elif code == '304': # 304 - Resource Not Modified
msg = color(msg, color='cyan')
elif code[0] == '3': # 3xx - Redirection
msg = color(msg, color='green')
elif code == '404': # 404 - Resource Not Found
msg = color(msg, color='yellow')
elif code[0] == '4': # 4xx - Client Error
msg = color(msg, color='red', attrs=['bold'])
else: # 5xx, or any other response
msg = color(msg, color='magenta', attrs=['bold'])
logger.info('%s - - [%s] "%s" %s', request.remote_addr, log_date_time_string(), msg, code)
def configure_before_handlers(app):
"""Configures the before request handlers."""
@app.before_request
def update_lastseen():
"""Updates `lastseen` before every reguest if the user is
authenticated."""
if current_user.is_authenticated:
current_user.lastseen = datetime.datetime.utcnow()
db.session.add(current_user)
db.session.commit()
if app.config["REDIS_ENABLED"]:
@app.before_request
def mark_current_user_online():
if current_user.is_authenticated:
mark_online(current_user.username)
else:
mark_online(request.remote_addr, guest=True)
def configure_before_handlers(app):
"""Configures the before request handlers."""
@app.before_request
def update_lastseen():
"""Updates `lastseen` before every reguest if the user is
authenticated."""
if current_user.is_authenticated:
current_user.lastseen = datetime.datetime.utcnow()
db.session.add(current_user)
db.session.commit()
if app.config["REDIS_ENABLED"]:
@app.before_request
def mark_current_user_online():
if current_user.is_authenticated:
mark_online(current_user.username)
else:
mark_online(request.remote_addr, guest=True)
def configure_before_handlers(app):
"""Configures the before request handlers."""
@app.before_request
def update_lastseen():
"""Updates `lastseen` before every reguest if the user is
authenticated."""
if current_user.is_authenticated:
current_user.lastseen = datetime.datetime.utcnow()
db.session.add(current_user)
db.session.commit()
if app.config["REDIS_ENABLED"]:
@app.before_request
def mark_current_user_online():
if current_user.is_authenticated:
mark_online(current_user.username)
else:
mark_online(request.remote_addr, guest=True)
def _capture_change_info(self):
"""Capture the change info for the new version. By default calls:
(1) :meth:`_fetch_current_user_id` which should return a string or None; and
(2) :meth:`_fetch_remote_addr` which should return an IP address string or None;
(3) :meth:`_get_custom_change_info` which should return a 1-depth dict of additional keys.
These 3 methods generate a ``change_info`` and with 2+ top-level keys (``user_id``,
``remote_addr``, and any keys from :meth:`_get_custom_change_info`)
"""
change_info = {
'user_id': self._fetch_current_user_id(),
'remote_addr': self._fetch_remote_addr(),
}
extra_info = self._get_custom_change_info()
if extra_info:
change_info.update(extra_info)
return change_info
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
challenge = request.json.get('recaptcha_challenge_field', '')
response = request.json.get('recaptcha_response_field', '')
else:
challenge = request.form.get('recaptcha_challenge_field', '')
response = request.form.get('recaptcha_response_field', '')
remote_ip = request.remote_addr
if not challenge or not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(challenge, response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def report_event():
"""
update DB with new container task state change event
:return: str. 'true' if successful
"""
if not request.json:
logger.error('received non-json data')
abort(400)
logger.info('Received event from {}'.format(request.remote_addr))
logger.debug('Event payload {}'.format(request.json))
event_id = request.json['event_id']
event = request.json['event']
timestamp = request.json['timestamp']
db.put(str(timestamp)+"_"+str(event_id),
{'container_id': event_id, 'event_action': event, 'timestamp': timestamp},
'ecs_id_mapper_events')
return 'true'
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
challenge = request.json.get('recaptcha_challenge_field', '')
response = request.json.get('recaptcha_response_field', '')
else:
challenge = request.form.get('recaptcha_challenge_field', '')
response = request.form.get('recaptcha_response_field', '')
remote_ip = request.remote_addr
if not challenge or not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(challenge, response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def make_all_files_public(bucket_id):
initSession()
config_array = {}
config_array["wait_time"] = 1
config_array["max_allowed_from_one_ip"] = 1
config_array["mode"] = 1
if session['logged_in'] or (request.remote_addr == "127.0.0.1" and can_login_local_without_auth()):
public_file_sharing_manager = OwnStorjPublicFileSharingManager()
files_manager = OwnStorjFilesManager(str(bucket_id))
files_list = files_manager.get_files_list()
for file in files_list:
if not public_file_sharing_manager.is_file_public(bucket_id=bucket_id, file_id=file["id"]):
public_file_hash = public_file_sharing_manager.generate_public_file_hash(
input_string=bucket_id + "_" + file["id"] + file["filename"] + str(file["size"]) + file["created"])
public_file_sharing_manager.save_public_file_to_db(bucket_id, file["id"], public_file_hash,
public_file_hash,
config_array, file["size"], file["filename"],
file["created"])
return "SUCCESS", 200
else:
return make_response(redirect("/login"))
def add_playlist():
initSession()
if session['logged_in'] or (request.remote_addr == "127.0.0.1" and can_login_local_without_auth()):
playlist_name = None
playlist_category = None
playlist_description = None
success = False
if request.method == 'GET':
playlist_name = request.args.get('playlist_name')
playlist_category = request.args.get('playlist_category')
playlist_description = request.args.get('playlist_description')
if playlist_name != None:
ownstorj_playlist_manager = OwnStorjPlaylistManager()
ownstorj_playlist_manager.add_new_playlist(playlist_name=playlist_name,
playlist_description=playlist_description,
playlist_category=playlist_category)
return "SUCCESS", 200
else:
return make_response(redirect("/login"))
def insert_file_to_playlist_endpoint(file_local_public_hash, playlist_id):
initSession()
ownstorj_playlist_manager = OwnStorjPlaylistManager()
ownstorj_public_file_sharing_manager = OwnStorjPublicFileSharingManager()
if session['logged_in'] or (request.remote_addr == "127.0.0.1" and can_login_local_without_auth()):
if file_local_public_hash != "":
public_file_details = ownstorj_public_file_sharing_manager.get_public_file_details_by_local_hash(file_local_public_hash)
ownstorj_playlist_manager.insert_track(track_name=public_file_details[0]["file_name"]
, track_local_file_id=file_local_public_hash
, playlist_id=playlist_id)
return '{result: "success"}', 200 # return the HTTP 200 statuss code - OK
else:
return '{result: "unauthorized"}', 401
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
response = request.json.get('g-recaptcha-response', '')
else:
response = request.form.get('g-recaptcha-response', '')
remote_ip = request.remote_addr
if not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def after_request_log(response):
name = dns_resolve(request.remote_addr)
current_app.logger.warn(u"""[client {ip} {host}] {http} "{method} {path}" {status}
Request: {method} {path}
Version: {http}
Status: {status}
Url: {url}
IP: {ip}
Hostname: {host}
Agent: {agent_platform} | {agent_browser} | {agent_browser_version}
Raw Agent: {agent}
""".format(method=request.method,
path=request.path,
url=request.url,
ip=request.remote_addr,
host=name if name is not None else '?',
agent_platform=request.user_agent.platform,
agent_browser=request.user_agent.browser,
agent_browser_version=request.user_agent.version,
agent=request.user_agent.string,
http=request.environ.get('SERVER_PROTOCOL'),
status=response.status))
return response
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
challenge = request.json.get('recaptcha_challenge_field', '')
response = request.json.get('recaptcha_response_field', '')
else:
challenge = request.form.get('recaptcha_challenge_field', '')
response = request.form.get('recaptcha_response_field', '')
remote_ip = request.remote_addr
if not challenge or not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(challenge, response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def configuration(node=None):
'''
Retrieve an osquery configuration for a given node.
:returns: an osquery configuration file
'''
current_app.logger.info(
"%s - %s checking in to retrieve a new configuration",
request.remote_addr, node
)
config = node.get_config()
# write last_checkin, last_ip
db.session.add(node)
db.session.commit()
return jsonify(config, node_invalid=False)
def distributed_read(node=None):
'''
'''
data = request.get_json()
current_app.logger.info(
"%s - %s checking in to retrieve distributed queries",
request.remote_addr, node
)
queries = node.get_new_queries()
# need to write last_checkin, last_ip, and update distributed
# query state
db.session.add(node)
db.session.commit()
return jsonify(queries=queries, node_invalid=False)
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
response = request.json.get('g-recaptcha-response', '')
else:
response = request.form.get('g-recaptcha-response', '')
remote_ip = request.remote_addr
if not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
def get_user():
"""User information.
.. note::
**Privacy note** A users IP address, user agent string, and user id
(if logged in) is sent to a message queue, where it is stored for about
5 minutes. The information is used to:
- Detect robot visits from the user agent string.
- Generate an anonymized visitor id (using a random salt per day).
- Detect the users host contry based on the IP address.
The information is then discarded.
"""
return dict(
ip_address=request.remote_addr,
user_agent=request.user_agent.string,
user_id=(
current_user.get_id() if current_user.is_authenticated else None
),
)
def downloadPic(source,id,fileName):
file, ext = os.path.splitext(fileName)
result =None
article = Article.query.get(id)
article.download_num = article.download_num+1
view = ArticleDownload()
view.article_id=id
view.ip = request.remote_addr
if current_user.is_authenticated:
view.user_id = current_user.get_id()
db.session.add(view)
db.session.commit()
result = send_from_directory('pics/'+source, file+ext)
return result