Search is not available for this dataset
text stringlengths 75 104k |
|---|
def daily(date=None, last='', token='', version=''):
'''https://iexcloud.io/docs/api/#stats-historical-daily
Args:
token (string); Access token
version (string); API version
Returns:
dict: result
'''
if date:
date = _strOrDate(date)
return _getJson('stats/historical/daily?date=' + date, token, version)
elif last:
return _getJson('stats/historical/daily?last=' + last, token, version)
return _getJson('stats/historical/daily', token, version) |
def dailyDF(date=None, last='', token='', version=''):
'''https://iexcloud.io/docs/api/#stats-historical-daily
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.DataFrame(daily(date, last, token, version))
_toDatetime(df)
return df |
def topsWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#tops'''
symbols = _strToList(symbols)
if symbols:
sendinit = ('subscribe', ','.join(symbols))
return _stream(_wsURL('tops'), sendinit, on_data)
return _stream(_wsURL('tops'), on_data=on_data) |
def lastWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#last'''
symbols = _strToList(symbols)
if symbols:
sendinit = ('subscribe', ','.join(symbols))
return _stream(_wsURL('last'), sendinit, on_data)
return _stream(_wsURL('last'), on_data=on_data) |
def deepWS(symbols=None, channels=None, on_data=None):
'''https://iextrading.com/developer/docs/#deep'''
symbols = _strToList(symbols)
channels = channels or []
if isinstance(channels, str):
if channels not in DeepChannels.options():
raise PyEXception('Channel not recognized: %s', type(channels))
channels = [channels]
elif isinstance(channels, DeepChannels):
channels = [channels.value]
elif isinstance(channels, list):
for i, c in enumerate(channels):
if isinstance(c, DeepChannels):
channels[i] = c.value
elif not isinstance(c, str) or isinstance(c, str) and c not in DeepChannels.options():
raise PyEXception('Channel not recognized: %s', c)
sendinit = ({'symbols': symbols, 'channels': channels},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def bookWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#book51'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['book']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def tradesWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#trades'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['trades']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def tradingStatusWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#trading-status'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['tradingstatus']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def opHaltStatusWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#operational-halt-status'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['ophaltstatus']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def ssrStatusWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#short-sale-price-test-status'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['ssr']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def securityEventWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#security-event'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['securityevent']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def tradeBreakWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#trade-break'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['tradebreaks']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def auctionWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#auction'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['auction']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def officialPriceWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#official-price'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['official-price']},)
return _stream(_wsURL('deep'), sendinit, on_data) |
def tops(symbols=None, token='', version=''):
'''TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book.
TOPS is ideal for developers needing both quote and trade data.
https://iexcloud.io/docs/api/#tops
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
symbols = _strToList(symbols)
if symbols:
return _getJson('tops?symbols=' + ','.join(symbols) + '%2b', token, version)
return _getJson('tops', token, version) |
def topsDF(symbols=None, token='', version=''):
'''TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book.
TOPS is ideal for developers needing both quote and trade data.
https://iexcloud.io/docs/api/#tops
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(tops(symbols, token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df |
def last(symbols=None, token='', version=''):
'''Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.
Last is ideal for developers that need a lightweight stock quote.
https://iexcloud.io/docs/api/#last
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
symbols = _strToList(symbols)
if symbols:
return _getJson('tops/last?symbols=' + ','.join(symbols) + '%2b', token, version)
return _getJson('tops/last', token, version) |
def lastDF(symbols=None, token='', version=''):
'''Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.
Last is ideal for developers that need a lightweight stock quote.
https://iexcloud.io/docs/api/#last
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(last(symbols, token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df |
def deep(symbol=None, token='', version=''):
'''DEEP is used to receive real-time depth of book quotations direct from IEX.
The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side,
and do not indicate the size or number of individual orders at any price level.
Non-displayed orders and non-displayed portions of reserve orders are not represented in DEEP.
DEEP also provides last trade price and size information. Trades resulting from either displayed or non-displayed orders matching on IEX will be reported. Routed executions will not be reported.
https://iexcloud.io/docs/api/#deep
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep?symbols=' + symbol, token, version)
return _getJson('deep', token, version) |
def deepDF(symbol=None, token='', version=''):
'''DEEP is used to receive real-time depth of book quotations direct from IEX.
The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side,
and do not indicate the size or number of individual orders at any price level.
Non-displayed orders and non-displayed portions of reserve orders are not represented in DEEP.
DEEP also provides last trade price and size information. Trades resulting from either displayed or non-displayed orders matching on IEX will be reported. Routed executions will not be reported.
https://iexcloud.io/docs/api/#deep
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(deep(symbol, token, version))
_toDatetime(df)
return df |
def auction(symbol=None, token='', version=''):
'''DEEP broadcasts an Auction Information Message every one second between the Lock-in Time and the auction match for Opening and Closing Auctions,
and during the Display Only Period for IPO, Halt, and Volatility Auctions. Only IEX listed securities are eligible for IEX Auctions.
https://iexcloud.io/docs/api/#deep-auction
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/auction?symbols=' + symbol, token, version)
return _getJson('deep/auction', token, version) |
def auctionDF(symbol=None, token='', version=''):
'''DEEP broadcasts an Auction Information Message every one second between the Lock-in Time and the auction match for Opening and Closing Auctions,
and during the Display Only Period for IPO, Halt, and Volatility Auctions. Only IEX listed securities are eligible for IEX Auctions.
https://iexcloud.io/docs/api/#deep-auction
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(auction(symbol, token, version))
_toDatetime(df)
return df |
def book(symbol=None, token='', version=''):
'''Book shows IEX’s bids and asks for given symbols.
https://iexcloud.io/docs/api/#deep-book
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/book?symbols=' + symbol, token, version)
return _getJson('deep/book', token, version) |
def bookDF(symbol=None, token='', version=''):
'''Book shows IEX’s bids and asks for given symbols.
https://iexcloud.io/docs/api/#deep-book
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
x = book(symbol, token, version)
data = []
for key in x:
d = x[key]
d['symbol'] = key
data.append(d)
df = pd.io.json.json_normalize(data)
_toDatetime(df)
return df |
def opHaltStatus(symbol=None, token='', version=''):
'''The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message.
IEX disseminates a full pre-market spin of Operational halt status messages indicating the operational halt status of all securities.
In the spin, IEX will send out an Operational Halt Message with “N” (Not operationally halted on IEX) for all securities that are eligible for trading at the start of the Pre-Market Session.
If a security is absent from the dissemination, firms should assume that the security is being treated as operationally halted in the IEX Trading System at the start of the Pre-Market Session.
After the pre-market spin, IEX will use the Operational halt status message to relay changes in operational halt status for an individual security.
https://iexcloud.io/docs/api/#deep-operational-halt-status
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/op-halt-status?symbols=' + symbol, token, version)
return _getJson('deep/op-halt-status', token, version) |
def opHaltStatusDF(symbol=None, token='', version=''):
'''The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message.
IEX disseminates a full pre-market spin of Operational halt status messages indicating the operational halt status of all securities.
In the spin, IEX will send out an Operational Halt Message with “N” (Not operationally halted on IEX) for all securities that are eligible for trading at the start of the Pre-Market Session.
If a security is absent from the dissemination, firms should assume that the security is being treated as operationally halted in the IEX Trading System at the start of the Pre-Market Session.
After the pre-market spin, IEX will use the Operational halt status message to relay changes in operational halt status for an individual security.
https://iexcloud.io/docs/api/#deep-operational-halt-status
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
x = opHaltStatus(symbol, token, version)
data = []
for key in x:
d = x[key]
d['symbol'] = key
data.append(d)
df = pd.DataFrame(data)
_toDatetime(df)
return df |
def officialPrice(symbol=None, token='', version=''):
'''The Official Price message is used to disseminate the IEX Official Opening and Closing Prices.
These messages will be provided only for IEX Listed Securities.
https://iexcloud.io/docs/api/#deep-official-price
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/official-price?symbols=' + symbol, token, version)
return _getJson('deep/official-price', token, version) |
def officialPriceDF(symbol=None, token='', version=''):
'''The Official Price message is used to disseminate the IEX Official Opening and Closing Prices.
These messages will be provided only for IEX Listed Securities.
https://iexcloud.io/docs/api/#deep-official-price
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(officialPrice(symbol, token, version))
_toDatetime(df)
return df |
def securityEvent(symbol=None, token='', version=''):
'''The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/security-event?symbols=' + symbol, token, version)
return _getJson('deep/security-event', token, version) |
def securityEventDF(symbol=None, token='', version=''):
'''The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
x = securityEvent(symbol, token, version)
data = []
for key in x:
d = x[key]
d['symbol'] = key
data.append(d)
df = pd.DataFrame(data)
_toDatetime(df)
return df |
def ssrStatus(symbol=None, token='', version=''):
'''In association with Rule 201 of Regulation SHO, the Short Sale Price Test Message is used to indicate when a short sale price test restriction is in effect for a security.
IEX disseminates a full pre-market spin of Short sale price test status messages indicating the Rule 201 status of all securities.
After the pre-market spin, IEX will use the Short sale price test status message in the event of an intraday status change.
The IEX Trading System will process orders based on the latest short sale price test restriction status.
https://iexcloud.io/docs/api/#deep-short-sale-price-test-status
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/ssr-status?symbols=' + symbol, token, version)
return _getJson('deep/ssr-status', token, version) |
def ssrStatusDF(symbol=None, token='', version=''):
'''In association with Rule 201 of Regulation SHO, the Short Sale Price Test Message is used to indicate when a short sale price test restriction is in effect for a security.
IEX disseminates a full pre-market spin of Short sale price test status messages indicating the Rule 201 status of all securities.
After the pre-market spin, IEX will use the Short sale price test status message in the event of an intraday status change.
The IEX Trading System will process orders based on the latest short sale price test restriction status.
https://iexcloud.io/docs/api/#deep-short-sale-price-test-status
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
x = ssrStatus(symbol, token, version)
data = []
for key in x:
d = x[key]
d['symbol'] = key
data.append(d)
df = pd.DataFrame(data)
_toDatetime(df)
return df |
def systemEventDF(token='', version=''):
'''The System event message is used to indicate events that apply to the market or the data feed.
There will be a single message disseminated per channel for each System Event type within a given trading session.
https://iexcloud.io/docs/api/#deep-system-event
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(systemEvent(token, version))
_toDatetime(df)
return df |
def trades(symbol=None, token='', version=''):
'''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.
https://iexcloud.io/docs/api/#deep-trades
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/trades?symbols=' + symbol, token, version)
return _getJson('deep/trades', token, version) |
def tradesDF(symbol=None, token='', version=''):
'''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.
https://iexcloud.io/docs/api/#deep-trades
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
x = trades(symbol, token, version)
data = []
for key in x:
dat = x[key]
for d in dat:
d['symbol'] = key
data.append(d)
df = pd.DataFrame(data)
_toDatetime(df)
return df |
def tradeBreak(symbol=None, token='', version=''):
'''Trade break messages are sent when an execution on IEX is broken on that same trading day. Trade breaks are rare and only affect applications that rely upon IEX execution based data.
https://iexcloud.io/docs/api/#deep-trade-break
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/trade-breaks?symbols=' + symbol, token, version)
return _getJson('deep/trade-breaks', token, version) |
def tradeBreakDF(symbol=None, token='', version=''):
'''Trade break messages are sent when an execution on IEX is broken on that same trading day. Trade breaks are rare and only affect applications that rely upon IEX execution based data.
https://iexcloud.io/docs/api/#deep-trade-break
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.io.json.json_normalize(tradeBreak(symbol, token, version))
_toDatetime(df)
return df |
def tradingStatus(symbol=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons.
For non-IEX-listed securities, IEX abides by any regulatory trading halts and trading pauses instituted by the primary or listing market, as applicable.
IEX disseminates a full pre-market spin of Trading status messages indicating the trading status of all securities.
In the spin, IEX will send out a Trading status message with “T” (Trading) for all securities that are eligible for trading at the start of the Pre-Market Session.
If a security is absent from the dissemination, firms should assume that the security is being treated as operationally halted in the IEX Trading System.
After the pre-market spin, IEX will use the Trading status message to relay changes in trading status for an individual security. Messages will be sent when a security is:
Halted
Paused*
Released into an Order Acceptance Period*
Released for trading
*The paused and released into an Order Acceptance Period status will be disseminated for IEX-listed securities only. Trading pauses on non-IEX-listed securities will be treated simply as a halt.
https://iexcloud.io/docs/api/#deep-trading-status
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
if symbol:
return _getJson('deep/trading-status?symbols=' + symbol, token, version)
return _getJson('deep/trading-status', token, version) |
def tradingStatusDF(symbol=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons.
For non-IEX-listed securities, IEX abides by any regulatory trading halts and trading pauses instituted by the primary or listing market, as applicable.
IEX disseminates a full pre-market spin of Trading status messages indicating the trading status of all securities.
In the spin, IEX will send out a Trading status message with “T” (Trading) for all securities that are eligible for trading at the start of the Pre-Market Session.
If a security is absent from the dissemination, firms should assume that the security is being treated as operationally halted in the IEX Trading System.
After the pre-market spin, IEX will use the Trading status message to relay changes in trading status for an individual security. Messages will be sent when a security is:
Halted
Paused*
Released into an Order Acceptance Period*
Released for trading
*The paused and released into an Order Acceptance Period status will be disseminated for IEX-listed securities only. Trading pauses on non-IEX-listed securities will be treated simply as a halt.
https://iexcloud.io/docs/api/#deep-trading-status
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
x = tradingStatus(symbol, token, version)
data = []
for key in x:
d = x[key]
d['symbol'] = key
data.append(d)
df = pd.DataFrame(data)
_toDatetime(df)
return df |
def histDF(date=None, token='', version=''):
'''https://iextrading.com/developer/docs/#hist'''
x = hist(date, token, version)
data = []
for key in x:
dat = x[key]
for item in dat:
item['date'] = key
data.append(item)
df = pd.DataFrame(data)
_toDatetime(df)
_reindex(df, 'date')
return df |
def look(self, i=0):
""" Look ahead of the iterable by some number of values with advancing
past them.
If the requested look ahead is past the end of the iterable then None is
returned.
"""
length = len(self.look_ahead)
if length <= i:
try:
self.look_ahead.extend([next(self.iterable)
for _ in range(length, i + 1)])
except StopIteration:
return self.default
self.value = self.look_ahead[i]
return self.value |
def pop_marker(self, reset):
""" Pop a marker off of the marker stack. If reset is True then the
iterator will be returned to the state it was in before the
corresponding call to push_marker().
"""
marker = self.markers.pop()
if reset:
# Make the values available to be read again
marker.extend(self.look_ahead)
self.look_ahead = marker
elif self.markers:
# Otherwise, reassign the values to the top marker
self.markers[-1].extend(marker)
else:
# If there are not more markers in the stack then discard the values
pass |
def look(self, i=0):
""" Look ahead of the iterable by some number of values with advancing
past them.
If the requested look ahead is past the end of the iterable then None is
returned.
"""
try:
self.value = self.list[self.marker + i]
except IndexError:
return self.default
return self.value |
def pop_marker(self, reset):
""" Pop a marker off of the marker stack. If reset is True then the
iterator will be returned to the state it was in before the
corresponding call to push_marker().
"""
saved = self.saved_markers.pop()
if reset:
self.marker = saved
elif self.saved_markers:
self.saved_markers[-1] = saved |
def is_annotation(self, i=0):
""" Returns true if the position is the start of an annotation application
(as opposed to an annotation declaration)
"""
return (isinstance(self.tokens.look(i), Annotation)
and not self.tokens.look(i + 1).value == 'interface') |
def is_annotation_declaration(self, i=0):
""" Returns true if the position is the start of an annotation application
(as opposed to an annotation declaration)
"""
return (isinstance(self.tokens.look(i), Annotation)
and self.tokens.look(i + 1).value == 'interface') |
def parse_command_line(self, argv=None):
"""
Overriden to check for conflicting flags
Since notebook version doesn't do it well (or, indeed, at all)
"""
conflicting_flags = set(['--user', '--system', '--sys-prefix'])
if len(conflicting_flags.intersection(set(argv))) > 1:
raise serverextensions.ArgumentConflict(
'cannot specify more than one of user, sys_prefix, or system')
return super(ToggleJupyterTensorboardApp,
self).parse_command_line(argv) |
def start(self):
"""Perform the App's actions as configured."""
if self.extra_args:
sys.exit('{} takes no extra arguments'.format(self.name))
else:
if self._toggle_value:
nbextensions.install_nbextension_python(
_pkg_name, overwrite=True, symlink=False,
user=self.user, sys_prefix=self.sys_prefix, prefix=None,
nbextensions_dir=None, logger=None)
else:
nbextensions.uninstall_nbextension_python(
_pkg_name, user=self.user, sys_prefix=self.sys_prefix,
prefix=None, nbextensions_dir=None, logger=None)
self.toggle_nbextension_python(_pkg_name)
self.toggle_server_extension_python(_pkg_name) |
def start(self):
"""Perform the App's actions as configured"""
super(JupyterTensorboardApp, self).start()
# The above should have called a subcommand and raised NoStart; if we
# get here, it didn't, so we should self.log.info a message.
subcmds = ", ".join(sorted(self.subcommands))
sys.exit("Please supply at least one subcommand: %s" % subcmds) |
def _load_client_secrets(filename):
"""Loads client secrets from the given filename.
Args:
filename: The name of the file containing the JSON secret key.
Returns:
A 2-tuple, the first item containing the client id, and the second
item containing a client secret.
"""
client_type, client_info = clientsecrets.loadfile(filename)
if client_type != clientsecrets.TYPE_WEB:
raise ValueError(
'The flow specified in {} is not supported, only the WEB flow '
'type is supported.'.format(client_type))
return client_info['client_id'], client_info['client_secret'] |
def _get_oauth2_client_id_and_secret(settings_instance):
"""Initializes client id and client secret based on the settings.
Args:
settings_instance: An instance of ``django.conf.settings``.
Returns:
A 2-tuple, the first item is the client id and the second
item is the client secret.
"""
secret_json = getattr(settings_instance,
'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)
if secret_json is not None:
return _load_client_secrets(secret_json)
else:
client_id = getattr(settings_instance, "GOOGLE_OAUTH2_CLIENT_ID",
None)
client_secret = getattr(settings_instance,
"GOOGLE_OAUTH2_CLIENT_SECRET", None)
if client_id is not None and client_secret is not None:
return client_id, client_secret
else:
raise exceptions.ImproperlyConfigured(
"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or "
"both GOOGLE_OAUTH2_CLIENT_ID and "
"GOOGLE_OAUTH2_CLIENT_SECRET in settings.py") |
def _get_storage_model():
"""This configures whether the credentials will be stored in the session
or the Django ORM based on the settings. By default, the credentials
will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`
is found in the settings. Usually, the ORM storage is used to integrate
credentials into an existing Django user system.
Returns:
A tuple containing three strings, or None. If
``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple
will contain the fully qualifed path of the `django.db.model`,
the name of the ``django.contrib.auth.models.User`` field on the
model, and the name of the
:class:`oauth2client.contrib.django_util.models.CredentialsField`
field on the model. If Django ORM storage is not configured,
this function returns None.
"""
storage_model_settings = getattr(django.conf.settings,
'GOOGLE_OAUTH2_STORAGE_MODEL', None)
if storage_model_settings is not None:
return (storage_model_settings['model'],
storage_model_settings['user_property'],
storage_model_settings['credentials_property'])
else:
return None, None, None |
def get_storage(request):
""" Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object.
"""
storage_model = oauth2_settings.storage_model
user_property = oauth2_settings.storage_model_user_property
credentials_property = oauth2_settings.storage_model_credentials_property
if storage_model:
module_name, class_name = storage_model.rsplit('.', 1)
module = importlib.import_module(module_name)
storage_model_class = getattr(module, class_name)
return storage.DjangoORMStorage(storage_model_class,
user_property,
request.user,
credentials_property)
else:
# use session
return dictionary_storage.DictionaryStorage(
request.session, key=_CREDENTIALS_KEY) |
def _redirect_with_params(url_name, *args, **kwargs):
"""Helper method to create a redirect response with URL params.
This builds a redirect string that converts kwargs into a
query string.
Args:
url_name: The name of the url to redirect to.
kwargs: the query string param and their values to build.
Returns:
A properly formatted redirect string.
"""
url = urlresolvers.reverse(url_name, args=args)
params = parse.urlencode(kwargs, True)
return "{0}?{1}".format(url, params) |
def _credentials_from_request(request):
"""Gets the authorized credentials for this flow, if they exist."""
# ORM storage requires a logged in user
if (oauth2_settings.storage_model is None or
request.user.is_authenticated()):
return get_storage(request).get()
else:
return None |
def has_credentials(self):
"""Returns True if there are valid credentials for the current user
and required scopes."""
credentials = _credentials_from_request(self.request)
return (credentials and not credentials.invalid and
credentials.has_scopes(self._get_scopes())) |
def _get_scopes(self):
"""Returns the scopes associated with this object, kept up to
date for incremental auth."""
if _credentials_from_request(self.request):
return (self._scopes |
_credentials_from_request(self.request).scopes)
else:
return self._scopes |
def locked_get(self):
"""Retrieve stored credential.
Returns:
A :class:`oauth2client.Credentials` instance or `None`.
"""
filters = {self.key_name: self.key_value}
query = self.session.query(self.model_class).filter_by(**filters)
entity = query.first()
if entity:
credential = getattr(entity, self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
return credential
else:
return None |
def locked_put(self, credentials):
"""Write a credentials to the SQLAlchemy datastore.
Args:
credentials: :class:`oauth2client.Credentials`
"""
filters = {self.key_name: self.key_value}
query = self.session.query(self.model_class).filter_by(**filters)
entity = query.first()
if not entity:
entity = self.model_class(**filters)
setattr(entity, self.property_name, credentials)
self.session.add(entity) |
def locked_delete(self):
"""Delete credentials from the SQLAlchemy datastore."""
filters = {self.key_name: self.key_value}
self.session.query(self.model_class).filter_by(**filters).delete() |
def _to_json(self, strip, to_serialize=None):
"""Utility function that creates JSON repr. of a credentials object.
Over-ride is needed since PKCS#12 keys will not in general be JSON
serializable.
Args:
strip: array, An array of names of members to exclude from the
JSON.
to_serialize: dict, (Optional) The properties for this object
that will be serialized. This allows callers to
modify before serializing.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
if to_serialize is None:
to_serialize = copy.copy(self.__dict__)
pkcs12_val = to_serialize.get(_PKCS12_KEY)
if pkcs12_val is not None:
to_serialize[_PKCS12_KEY] = base64.b64encode(pkcs12_val)
return super(ServiceAccountCredentials, self)._to_json(
strip, to_serialize=to_serialize) |
def _from_parsed_json_keyfile(cls, keyfile_dict, scopes,
token_uri=None, revoke_uri=None):
"""Helper for factory constructors from JSON keyfile.
Args:
keyfile_dict: dict-like object, The parsed dictionary-like object
containing the contents of the JSON keyfile.
scopes: List or string, Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile contents.
Raises:
ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.
KeyError, if one of the expected keys is not present in
the keyfile.
"""
creds_type = keyfile_dict.get('type')
if creds_type != client.SERVICE_ACCOUNT:
raise ValueError('Unexpected credentials type', creds_type,
'Expected', client.SERVICE_ACCOUNT)
service_account_email = keyfile_dict['client_email']
private_key_pkcs8_pem = keyfile_dict['private_key']
private_key_id = keyfile_dict['private_key_id']
client_id = keyfile_dict['client_id']
if not token_uri:
token_uri = keyfile_dict.get('token_uri',
oauth2client.GOOGLE_TOKEN_URI)
if not revoke_uri:
revoke_uri = keyfile_dict.get('revoke_uri',
oauth2client.GOOGLE_REVOKE_URI)
signer = crypt.Signer.from_string(private_key_pkcs8_pem)
credentials = cls(service_account_email, signer, scopes=scopes,
private_key_id=private_key_id,
client_id=client_id, token_uri=token_uri,
revoke_uri=revoke_uri)
credentials._private_key_pkcs8_pem = private_key_pkcs8_pem
return credentials |
def from_json_keyfile_name(cls, filename, scopes='',
token_uri=None, revoke_uri=None):
"""Factory constructor from JSON keyfile by name.
Args:
filename: string, The location of the keyfile.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in the key file, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in the key file, defaults
to Google's endpoints.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.
Raises:
ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.
KeyError, if one of the expected keys is not present in
the keyfile.
"""
with open(filename, 'r') as file_obj:
client_credentials = json.load(file_obj)
return cls._from_parsed_json_keyfile(client_credentials, scopes,
token_uri=token_uri,
revoke_uri=revoke_uri) |
def from_json_keyfile_dict(cls, keyfile_dict, scopes='',
token_uri=None, revoke_uri=None):
"""Factory constructor from parsed JSON keyfile.
Args:
keyfile_dict: dict-like object, The parsed dictionary-like object
containing the contents of the JSON keyfile.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.
Raises:
ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.
KeyError, if one of the expected keys is not present in
the keyfile.
"""
return cls._from_parsed_json_keyfile(keyfile_dict, scopes,
token_uri=token_uri,
revoke_uri=revoke_uri) |
def _from_p12_keyfile_contents(cls, service_account_email,
private_key_pkcs12,
private_key_password=None, scopes='',
token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile.
Args:
service_account_email: string, The email associated with the
service account.
private_key_pkcs12: string, The contents of a PKCS#12 keyfile.
private_key_password: string, (Optional) Password for PKCS#12
private key. Defaults to ``notasecret``.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for token endpoint. For convenience defaults
to Google's endpoints but any OAuth 2.0 provider can be
used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0
provider can be used.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.
Raises:
NotImplementedError if pyOpenSSL is not installed / not the
active crypto library.
"""
if private_key_password is None:
private_key_password = _PASSWORD_DEFAULT
if crypt.Signer is not crypt.OpenSSLSigner:
raise NotImplementedError(_PKCS12_ERROR)
signer = crypt.Signer.from_string(private_key_pkcs12,
private_key_password)
credentials = cls(service_account_email, signer, scopes=scopes,
token_uri=token_uri, revoke_uri=revoke_uri)
credentials._private_key_pkcs12 = private_key_pkcs12
credentials._private_key_password = private_key_password
return credentials |
def from_p12_keyfile(cls, service_account_email, filename,
private_key_password=None, scopes='',
token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile.
Args:
service_account_email: string, The email associated with the
service account.
filename: string, The location of the PKCS#12 keyfile.
private_key_password: string, (Optional) Password for PKCS#12
private key. Defaults to ``notasecret``.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for token endpoint. For convenience defaults
to Google's endpoints but any OAuth 2.0 provider can be
used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0
provider can be used.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.
Raises:
NotImplementedError if pyOpenSSL is not installed / not the
active crypto library.
"""
with open(filename, 'rb') as file_obj:
private_key_pkcs12 = file_obj.read()
return cls._from_p12_keyfile_contents(
service_account_email, private_key_pkcs12,
private_key_password=private_key_password, scopes=scopes,
token_uri=token_uri, revoke_uri=revoke_uri) |
def from_p12_keyfile_buffer(cls, service_account_email, file_buffer,
private_key_password=None, scopes='',
token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile.
Args:
service_account_email: string, The email associated with the
service account.
file_buffer: stream, A buffer that implements ``read()``
and contains the PKCS#12 key contents.
private_key_password: string, (Optional) Password for PKCS#12
private key. Defaults to ``notasecret``.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for token endpoint. For convenience defaults
to Google's endpoints but any OAuth 2.0 provider can be
used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0
provider can be used.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.
Raises:
NotImplementedError if pyOpenSSL is not installed / not the
active crypto library.
"""
private_key_pkcs12 = file_buffer.read()
return cls._from_p12_keyfile_contents(
service_account_email, private_key_pkcs12,
private_key_password=private_key_password, scopes=scopes,
token_uri=token_uri, revoke_uri=revoke_uri) |
def _generate_assertion(self):
"""Generate the assertion that will be used in the request."""
now = int(time.time())
payload = {
'aud': self.token_uri,
'scope': self._scopes,
'iat': now,
'exp': now + self.MAX_TOKEN_LIFETIME_SECS,
'iss': self._service_account_email,
}
payload.update(self._kwargs)
return crypt.make_signed_jwt(self._signer, payload,
key_id=self._private_key_id) |
def from_json(cls, json_data):
"""Deserialize a JSON-serialized instance.
Inverse to :meth:`to_json`.
Args:
json_data: dict or string, Serialized JSON (as a string or an
already parsed dictionary) representing a credential.
Returns:
ServiceAccountCredentials from the serialized data.
"""
if not isinstance(json_data, dict):
json_data = json.loads(_helpers._from_bytes(json_data))
private_key_pkcs8_pem = None
pkcs12_val = json_data.get(_PKCS12_KEY)
password = None
if pkcs12_val is None:
private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']
signer = crypt.Signer.from_string(private_key_pkcs8_pem)
else:
# NOTE: This assumes that private_key_pkcs8_pem is not also
# in the serialized data. This would be very incorrect
# state.
pkcs12_val = base64.b64decode(pkcs12_val)
password = json_data['_private_key_password']
signer = crypt.Signer.from_string(pkcs12_val, password)
credentials = cls(
json_data['_service_account_email'],
signer,
scopes=json_data['_scopes'],
private_key_id=json_data['_private_key_id'],
client_id=json_data['client_id'],
user_agent=json_data['_user_agent'],
**json_data['_kwargs']
)
if private_key_pkcs8_pem is not None:
credentials._private_key_pkcs8_pem = private_key_pkcs8_pem
if pkcs12_val is not None:
credentials._private_key_pkcs12 = pkcs12_val
if password is not None:
credentials._private_key_password = password
credentials.invalid = json_data['invalid']
credentials.access_token = json_data['access_token']
credentials.token_uri = json_data['token_uri']
credentials.revoke_uri = json_data['revoke_uri']
token_expiry = json_data.get('token_expiry', None)
if token_expiry is not None:
credentials.token_expiry = datetime.datetime.strptime(
token_expiry, client.EXPIRY_FORMAT)
return credentials |
def create_with_claims(self, claims):
"""Create credentials that specify additional claims.
Args:
claims: dict, key-value pairs for claims.
Returns:
ServiceAccountCredentials, a copy of the current service account
credentials with updated claims to use when obtaining access
tokens.
"""
new_kwargs = dict(self._kwargs)
new_kwargs.update(claims)
result = self.__class__(self._service_account_email,
self._signer,
scopes=self._scopes,
private_key_id=self._private_key_id,
client_id=self.client_id,
user_agent=self._user_agent,
**new_kwargs)
result.token_uri = self.token_uri
result.revoke_uri = self.revoke_uri
result._private_key_pkcs8_pem = self._private_key_pkcs8_pem
result._private_key_pkcs12 = self._private_key_pkcs12
result._private_key_password = self._private_key_password
return result |
def get_access_token(self, http=None, additional_claims=None):
"""Create a signed jwt.
Args:
http: unused
additional_claims: dict, additional claims to add to
the payload of the JWT.
Returns:
An AccessTokenInfo with the signed jwt
"""
if additional_claims is None:
if self.access_token is None or self.access_token_expired:
self.refresh(None)
return client.AccessTokenInfo(
access_token=self.access_token, expires_in=self._expires_in())
else:
# Create a 1 time token
token, unused_expiry = self._create_token(additional_claims)
return client.AccessTokenInfo(
access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS) |
def _detect_gce_environment():
"""Determine if the current environment is Compute Engine.
Returns:
Boolean indicating whether or not the current environment is Google
Compute Engine.
"""
# NOTE: The explicit ``timeout`` is a workaround. The underlying
# issue is that resolving an unknown host on some networks will take
# 20-30 seconds; making this timeout short fixes the issue, but
# could lead to false negatives in the event that we are on GCE, but
# the metadata resolution was particularly slow. The latter case is
# "unlikely".
http = transport.get_http_object(timeout=GCE_METADATA_TIMEOUT)
try:
response, _ = transport.request(
http, _GCE_METADATA_URI, headers=_GCE_HEADERS)
return (
response.status == http_client.OK and
response.get(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR)
except socket.error: # socket.timeout or socket.error(64, 'Host is down')
logger.info('Timeout attempting to reach GCE metadata service.')
return False |
def _in_gae_environment():
"""Detects if the code is running in the App Engine environment.
Returns:
True if running in the GAE environment, False otherwise.
"""
if SETTINGS.env_name is not None:
return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL')
try:
import google.appengine # noqa: unused import
except ImportError:
pass
else:
server_software = os.environ.get(_SERVER_SOFTWARE, '')
if server_software.startswith('Google App Engine/'):
SETTINGS.env_name = 'GAE_PRODUCTION'
return True
elif server_software.startswith('Development/'):
SETTINGS.env_name = 'GAE_LOCAL'
return True
return False |
def _in_gce_environment():
"""Detect if the code is running in the Compute Engine environment.
Returns:
True if running in the GCE environment, False otherwise.
"""
if SETTINGS.env_name is not None:
return SETTINGS.env_name == 'GCE_PRODUCTION'
if NO_GCE_CHECK != 'True' and _detect_gce_environment():
SETTINGS.env_name = 'GCE_PRODUCTION'
return True
return False |
def _save_private_file(filename, json_contents):
"""Saves a file with read-write permissions on for the owner.
Args:
filename: String. Absolute path to file.
json_contents: JSON serializable object to be saved.
"""
temp_filename = tempfile.mktemp()
file_desc = os.open(temp_filename, os.O_WRONLY | os.O_CREAT, 0o600)
with os.fdopen(file_desc, 'w') as file_handle:
json.dump(json_contents, file_handle, sort_keys=True,
indent=2, separators=(',', ': '))
shutil.move(temp_filename, filename) |
def save_to_well_known_file(credentials, well_known_file=None):
"""Save the provided GoogleCredentials to the well known file.
Args:
credentials: the credentials to be saved to the well known file;
it should be an instance of GoogleCredentials
well_known_file: the name of the file where the credentials are to be
saved; this parameter is supposed to be used for
testing only
"""
# TODO(orestica): move this method to tools.py
# once the argparse import gets fixed (it is not present in Python 2.6)
if well_known_file is None:
well_known_file = _get_well_known_file()
config_dir = os.path.dirname(well_known_file)
if not os.path.isdir(config_dir):
raise OSError(
'Config directory does not exist: {0}'.format(config_dir))
credentials_data = credentials.serialization_data
_save_private_file(well_known_file, credentials_data) |
def _get_well_known_file():
"""Get the well known file produced by command 'gcloud auth login'."""
# TODO(orestica): Revisit this method once gcloud provides a better way
# of pinpointing the exact location of the file.
default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)
if default_config_dir is None:
if os.name == 'nt':
try:
default_config_dir = os.path.join(os.environ['APPDATA'],
_CLOUDSDK_CONFIG_DIRECTORY)
except KeyError:
# This should never happen unless someone is really
# messing with things.
drive = os.environ.get('SystemDrive', 'C:')
default_config_dir = os.path.join(drive, '\\',
_CLOUDSDK_CONFIG_DIRECTORY)
else:
default_config_dir = os.path.join(os.path.expanduser('~'),
'.config',
_CLOUDSDK_CONFIG_DIRECTORY)
return os.path.join(default_config_dir, _WELL_KNOWN_CREDENTIALS_FILE) |
def _get_application_default_credential_from_file(filename):
"""Build the Application Default Credentials from file."""
# read the credentials from the file
with open(filename) as file_obj:
client_credentials = json.load(file_obj)
credentials_type = client_credentials.get('type')
if credentials_type == AUTHORIZED_USER:
required_fields = set(['client_id', 'client_secret', 'refresh_token'])
elif credentials_type == SERVICE_ACCOUNT:
required_fields = set(['client_id', 'client_email', 'private_key_id',
'private_key'])
else:
raise ApplicationDefaultCredentialsError(
"'type' field should be defined (and have one of the '" +
AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")
missing_fields = required_fields.difference(client_credentials.keys())
if missing_fields:
_raise_exception_for_missing_fields(missing_fields)
if client_credentials['type'] == AUTHORIZED_USER:
return GoogleCredentials(
access_token=None,
client_id=client_credentials['client_id'],
client_secret=client_credentials['client_secret'],
refresh_token=client_credentials['refresh_token'],
token_expiry=None,
token_uri=oauth2client.GOOGLE_TOKEN_URI,
user_agent='Python client library')
else: # client_credentials['type'] == SERVICE_ACCOUNT
from oauth2client import service_account
return service_account._JWTAccessCredentials.from_json_keyfile_dict(
client_credentials) |
def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATION_CERTS):
"""Verifies a signed JWT id_token.
This function requires PyOpenSSL and because of that it does not work on
App Engine.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.
Returns:
The deserialized JSON in the JWT.
Raises:
oauth2client.crypt.AppIdentityError: if the JWT fails to verify.
CryptoUnavailableError: if no crypto library is available.
"""
_require_crypto_or_die()
if http is None:
http = transport.get_cached_http()
resp, content = transport.request(http, cert_uri)
if resp.status == http_client.OK:
certs = json.loads(_helpers._from_bytes(content))
return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: {0}'.format(resp.status)) |
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string or bytestring, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
if type(id_token) == bytes:
segments = id_token.split(b'.')
else:
segments = id_token.split(u'.')
if len(segments) != 3:
raise VerifyJwtTokenError(
'Wrong number of segments in token: {0}'.format(id_token))
return json.loads(
_helpers._from_bytes(_helpers._urlsafe_b64decode(segments[1]))) |
def _parse_exchange_token_response(content):
"""Parses response of an exchange token request.
Most providers return JSON but some (e.g. Facebook) return a
url-encoded string.
Args:
content: The body of a response
Returns:
Content as a dictionary object. Note that the dict could be empty,
i.e. {}. That basically indicates a failure.
"""
resp = {}
content = _helpers._from_bytes(content)
try:
resp = json.loads(content)
except Exception:
# different JSON libs raise different exceptions,
# so we just do a catch-all here
resp = _helpers.parse_unique_urlencoded(content)
# some providers respond with 'expires', others with 'expires_in'
if resp and 'expires' in resp:
resp['expires_in'] = resp.pop('expires')
return resp |
def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri='postmessage', http=None,
user_agent=None,
token_uri=oauth2client.GOOGLE_TOKEN_URI,
auth_uri=oauth2client.GOOGLE_AUTH_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
device_uri=oauth2client.GOOGLE_DEVICE_URI,
token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,
pkce=False,
code_verifier=None):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or iterable of strings, scope(s) to request.
code: string, An authorization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match
the redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience defaults
to Google's endpoints but any OAuth 2.0 provider can be
used.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider
can be used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider
can be used.
device_uri: string, URI for device authorization endpoint. For
convenience defaults to Google's endpoints but any OAuth
2.0 provider can be used.
pkce: boolean, default: False, Generate and include a "Proof Key
for Code Exchange" (PKCE) with your authorization and token
requests. This adds security for installed applications that
cannot protect a client_secret. See RFC 7636 for details.
code_verifier: bytestring or None, default: None, parameter passed
as part of the code exchange when pkce=True. If
None, a code_verifier will automatically be
generated as part of step1_get_authorize_url(). See
RFC 7636 for details.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
"""
flow = OAuth2WebServerFlow(client_id, client_secret, scope,
redirect_uri=redirect_uri,
user_agent=user_agent,
auth_uri=auth_uri,
token_uri=token_uri,
revoke_uri=revoke_uri,
device_uri=device_uri,
token_info_uri=token_info_uri,
pkce=pkce,
code_verifier=code_verifier)
credentials = flow.step2_exchange(code, http=http)
return credentials |
def credentials_from_clientsecrets_and_code(filename, scope, code,
message=None,
redirect_uri='postmessage',
http=None,
cache=None,
device_uri=None):
"""Returns OAuth2Credentials from a clientsecrets file and an auth code.
Will create the right kind of Flow based on the contents of the
clientsecrets file or will raise InvalidClientSecretsError for unknown
types of Flows.
Args:
filename: string, File name of clientsecrets.
scope: string or iterable of strings, scope(s) to request.
code: string, An authorization code, most likely passed down from
the client
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is
provided then sys.exit will be called in the case of an error.
If message in not provided then
clientsecrets.InvalidClientSecretsError will be raised.
redirect_uri: string, this is generally set to 'postmessage' to match
the redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
cache: An optional cache service client that implements get() and set()
methods. See clientsecrets.loadfile() for details.
device_uri: string, OAuth 2.0 device authorization endpoint
pkce: boolean, default: False, Generate and include a "Proof Key
for Code Exchange" (PKCE) with your authorization and token
requests. This adds security for installed applications that
cannot protect a client_secret. See RFC 7636 for details.
code_verifier: bytestring or None, default: None, parameter passed
as part of the code exchange when pkce=True. If
None, a code_verifier will automatically be
generated as part of step1_get_authorize_url(). See
RFC 7636 for details.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError: if the authorization code cannot be exchanged for an
access token
UnknownClientSecretsFlowError: if the file describes an unknown kind
of Flow.
clientsecrets.InvalidClientSecretsError: if the clientsecrets file is
invalid.
"""
flow = flow_from_clientsecrets(filename, scope, message=message,
cache=cache, redirect_uri=redirect_uri,
device_uri=device_uri)
credentials = flow.step2_exchange(code, http=http)
return credentials |
def _oauth2_web_server_flow_params(kwargs):
"""Configures redirect URI parameters for OAuth2WebServerFlow."""
params = {
'access_type': 'offline',
'response_type': 'code',
}
params.update(kwargs)
# Check for the presence of the deprecated approval_prompt param and
# warn appropriately.
approval_prompt = params.get('approval_prompt')
if approval_prompt is not None:
logger.warning(
'The approval_prompt parameter for OAuth2WebServerFlow is '
'deprecated. Please use the prompt parameter instead.')
if approval_prompt == 'force':
logger.warning(
'approval_prompt="force" has been adjusted to '
'prompt="consent"')
params['prompt'] = 'consent'
del params['approval_prompt']
return params |
def flow_from_clientsecrets(filename, scope, redirect_uri=None,
message=None, cache=None, login_hint=None,
device_uri=None, pkce=None, code_verifier=None,
prompt=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the
clientsecrets file or will raise InvalidClientSecretsError for unknown
types of Flows.
Args:
filename: string, File name of client secrets.
scope: string or iterable of strings, scope(s) to request.
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the
callback from the authorization server.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is
provided then sys.exit will be called in the case of an error.
If message in not provided then
clientsecrets.InvalidClientSecretsError will be raised.
cache: An optional cache service client that implements get() and set()
methods. See clientsecrets.loadfile() for details.
login_hint: string, Either an email address or domain. Passing this
hint will either pre-fill the email box on the sign-in form
or select the proper multi-login session, thereby
simplifying the login flow.
device_uri: string, URI for device authorization endpoint. For
convenience defaults to Google's endpoints but any
OAuth 2.0 provider can be used.
Returns:
A Flow object.
Raises:
UnknownClientSecretsFlowError: if the file describes an unknown kind of
Flow.
clientsecrets.InvalidClientSecretsError: if the clientsecrets file is
invalid.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename,
cache=cache)
if client_type in (clientsecrets.TYPE_WEB,
clientsecrets.TYPE_INSTALLED):
constructor_kwargs = {
'redirect_uri': redirect_uri,
'auth_uri': client_info['auth_uri'],
'token_uri': client_info['token_uri'],
'login_hint': login_hint,
}
revoke_uri = client_info.get('revoke_uri')
optional = (
'revoke_uri',
'device_uri',
'pkce',
'code_verifier',
'prompt'
)
for param in optional:
if locals()[param] is not None:
constructor_kwargs[param] = locals()[param]
return OAuth2WebServerFlow(
client_info['client_id'], client_info['client_secret'],
scope, **constructor_kwargs)
except clientsecrets.InvalidClientSecretsError as e:
if message is not None:
if e.args:
message = ('The client secrets were invalid: '
'\n{0}\n{1}'.format(e, message))
sys.exit(message)
else:
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type)) |
def _to_json(self, strip, to_serialize=None):
"""Utility function that creates JSON repr. of a Credentials object.
Args:
strip: array, An array of names of members to exclude from the
JSON.
to_serialize: dict, (Optional) The properties for this object
that will be serialized. This allows callers to
modify before serializing.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
curr_type = self.__class__
if to_serialize is None:
to_serialize = copy.copy(self.__dict__)
else:
# Assumes it is a str->str dictionary, so we don't deep copy.
to_serialize = copy.copy(to_serialize)
for member in strip:
if member in to_serialize:
del to_serialize[member]
to_serialize['token_expiry'] = _parse_expiry(
to_serialize.get('token_expiry'))
# Add in information we will need later to reconstitute this instance.
to_serialize['_class'] = curr_type.__name__
to_serialize['_module'] = curr_type.__module__
for key, val in to_serialize.items():
if isinstance(val, bytes):
to_serialize[key] = val.decode('utf-8')
if isinstance(val, set):
to_serialize[key] = list(val)
return json.dumps(to_serialize) |
def new_from_json(cls, json_data):
"""Utility class method to instantiate a Credentials subclass from JSON.
Expects the JSON string to have been produced by to_json().
Args:
json_data: string or bytes, JSON from to_json().
Returns:
An instance of the subclass of Credentials that was serialized with
to_json().
"""
json_data_as_unicode = _helpers._from_bytes(json_data)
data = json.loads(json_data_as_unicode)
# Find and call the right classmethod from_json() to restore
# the object.
module_name = data['_module']
try:
module_obj = __import__(module_name)
except ImportError:
# In case there's an object from the old package structure,
# update it
module_name = module_name.replace('.googleapiclient', '')
module_obj = __import__(module_name)
module_obj = __import__(module_name,
fromlist=module_name.split('.')[:-1])
kls = getattr(module_obj, data['_class'])
return kls.from_json(json_data_as_unicode) |
def put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self.acquire_lock()
try:
self.locked_put(credentials)
finally:
self.release_lock() |
def has_scopes(self, scopes):
"""Verify that the credentials are authorized for the given scopes.
Returns True if the credentials authorized scopes contain all of the
scopes given.
Args:
scopes: list or string, the scopes to check.
Notes:
There are cases where the credentials are unaware of which scopes
are authorized. Notably, credentials obtained and stored before
this code was added will not have scopes, AccessTokenCredentials do
not have scopes. In both cases, you can use refresh_scopes() to
obtain the canonical set of scopes.
"""
scopes = _helpers.string_to_scopes(scopes)
return set(scopes).issubset(self.scopes) |
def from_json(cls, json_data):
"""Instantiate a Credentials object from a JSON description of it.
The JSON should have been produced by calling .to_json() on the object.
Args:
json_data: string or bytes, JSON to deserialize.
Returns:
An instance of a Credentials subclass.
"""
data = json.loads(_helpers._from_bytes(json_data))
if (data.get('token_expiry') and
not isinstance(data['token_expiry'], datetime.datetime)):
try:
data['token_expiry'] = datetime.datetime.strptime(
data['token_expiry'], EXPIRY_FORMAT)
except ValueError:
data['token_expiry'] = None
retval = cls(
data['access_token'],
data['client_id'],
data['client_secret'],
data['refresh_token'],
data['token_expiry'],
data['token_uri'],
data['user_agent'],
revoke_uri=data.get('revoke_uri', None),
id_token=data.get('id_token', None),
id_token_jwt=data.get('id_token_jwt', None),
token_response=data.get('token_response', None),
scopes=data.get('scopes', None),
token_info_uri=data.get('token_info_uri', None))
retval.invalid = data['invalid']
return retval |
def access_token_expired(self):
"""True if the credential is expired or invalid.
If the token_expiry isn't set, we assume the token doesn't expire.
"""
if self.invalid:
return True
if not self.token_expiry:
return False
now = _UTCNOW()
if now >= self.token_expiry:
logger.info('access_token is expired. Now: %s, token_expiry: %s',
now, self.token_expiry)
return True
return False |
def get_access_token(self, http=None):
"""Return the access token and its expiration information.
If the token does not exist, get one.
If the token expired, refresh it.
"""
if not self.access_token or self.access_token_expired:
if not http:
http = transport.get_http_object()
self.refresh(http)
return AccessTokenInfo(access_token=self.access_token,
expires_in=self._expires_in()) |
def _expires_in(self):
"""Return the number of seconds until this token expires.
If token_expiry is in the past, this method will return 0, meaning the
token has already expired.
If token_expiry is None, this method will return None. Note that
returning 0 in such a case would not be fair: the token may still be
valid; we just don't know anything about it.
"""
if self.token_expiry:
now = _UTCNOW()
if self.token_expiry > now:
time_delta = self.token_expiry - now
# TODO(orestica): return time_delta.total_seconds()
# once dropping support for Python 2.6
return time_delta.days * 86400 + time_delta.seconds
else:
return 0 |
def _generate_refresh_request_body(self):
"""Generate the body that will be used in the refresh request."""
body = urllib.parse.urlencode({
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
})
return body |
def _refresh(self, http):
"""Refreshes the access_token.
This method first checks by reading the Storage object if available.
If a refresh is still needed, it holds the Storage lock until the
refresh is completed.
Args:
http: an object to be used to make HTTP requests.
Raises:
HttpAccessTokenRefreshError: When the refresh fails.
"""
if not self.store:
self._do_refresh_request(http)
else:
self.store.acquire_lock()
try:
new_cred = self.store.locked_get()
if (new_cred and not new_cred.invalid and
new_cred.access_token != self.access_token and
not new_cred.access_token_expired):
logger.info('Updated access_token read from Storage')
self._updateFromCredential(new_cred)
else:
self._do_refresh_request(http)
finally:
self.store.release_lock() |
def _do_refresh_request(self, http):
"""Refresh the access_token using the refresh_token.
Args:
http: an object to be used to make HTTP requests.
Raises:
HttpAccessTokenRefreshError: When the refresh fails.
"""
body = self._generate_refresh_request_body()
headers = self._generate_refresh_request_headers()
logger.info('Refreshing access_token')
resp, content = transport.request(
http, self.token_uri, method='POST',
body=body, headers=headers)
content = _helpers._from_bytes(content)
if resp.status == http_client.OK:
d = json.loads(content)
self.token_response = d
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
delta = datetime.timedelta(seconds=int(d['expires_in']))
self.token_expiry = delta + _UTCNOW()
else:
self.token_expiry = None
if 'id_token' in d:
self.id_token = _extract_id_token(d['id_token'])
self.id_token_jwt = d['id_token']
else:
self.id_token = None
self.id_token_jwt = None
# On temporary refresh errors, the user does not actually have to
# re-authorize, so we unflag here.
self.invalid = False
if self.store:
self.store.locked_put(self)
else:
# An {'error':...} response body means the token is expired or
# revoked, so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s', content)
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(content)
if 'error' in d:
error_msg = d['error']
if 'error_description' in d:
error_msg += ': ' + d['error_description']
self.invalid = True
if self.store is not None:
self.store.locked_put(self)
except (TypeError, ValueError):
pass
raise HttpAccessTokenRefreshError(error_msg, status=resp.status) |
def _revoke(self, http):
"""Revokes this credential and deletes the stored copy (if it exists).
Args:
http: an object to be used to make HTTP requests.
"""
self._do_revoke(http, self.refresh_token or self.access_token) |
def _do_revoke(self, http, token):
"""Revokes this credential and deletes the stored copy (if it exists).
Args:
http: an object to be used to make HTTP requests.
token: A string used as the token to be revoked. Can be either an
access_token or refresh_token.
Raises:
TokenRevokeError: If the revoke request does not return with a
200 OK.
"""
logger.info('Revoking token')
query_params = {'token': token}
token_revoke_uri = _helpers.update_query_params(
self.revoke_uri, query_params)
resp, content = transport.request(http, token_revoke_uri)
if resp.status == http_client.METHOD_NOT_ALLOWED:
body = urllib.parse.urlencode(query_params)
resp, content = transport.request(http, token_revoke_uri,
method='POST', body=body)
if resp.status == http_client.OK:
self.invalid = True
else:
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(_helpers._from_bytes(content))
if 'error' in d:
error_msg = d['error']
except (TypeError, ValueError):
pass
raise TokenRevokeError(error_msg)
if self.store:
self.store.delete() |
def _do_retrieve_scopes(self, http, token):
"""Retrieves the list of authorized scopes from the OAuth2 provider.
Args:
http: an object to be used to make HTTP requests.
token: A string used as the token to identify the credentials to
the provider.
Raises:
Error: When refresh fails, indicating the the access token is
invalid.
"""
logger.info('Refreshing scopes')
query_params = {'access_token': token, 'fields': 'scope'}
token_info_uri = _helpers.update_query_params(
self.token_info_uri, query_params)
resp, content = transport.request(http, token_info_uri)
content = _helpers._from_bytes(content)
if resp.status == http_client.OK:
d = json.loads(content)
self.scopes = set(_helpers.string_to_scopes(d.get('scope', '')))
else:
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(content)
if 'error_description' in d:
error_msg = d['error_description']
except (TypeError, ValueError):
pass
raise Error(error_msg) |
def _implicit_credentials_from_files():
"""Attempts to get implicit credentials from local credential files.
First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS
is set with a filename and then falls back to a configuration file (the
"well known" file) associated with the 'gcloud' command line tool.
Returns:
Credentials object associated with the
GOOGLE_APPLICATION_CREDENTIALS file or the "well known" file if
either exist. If neither file is define, returns None, indicating
no credentials from a file can detected from the current
environment.
"""
credentials_filename = _get_environment_variable_file()
if not credentials_filename:
credentials_filename = _get_well_known_file()
if os.path.isfile(credentials_filename):
extra_help = (' (produced automatically when running'
' "gcloud auth login" command)')
else:
credentials_filename = None
else:
extra_help = (' (pointed to by ' + GOOGLE_APPLICATION_CREDENTIALS +
' environment variable)')
if not credentials_filename:
return
# If we can read the credentials from a file, we don't need to know
# what environment we are in.
SETTINGS.env_name = DEFAULT_ENV_NAME
try:
return _get_application_default_credential_from_file(
credentials_filename)
except (ApplicationDefaultCredentialsError, ValueError) as error:
_raise_exception_for_reading_json(credentials_filename,
extra_help, error) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.