Here are the examples of the python api flask.request.authorization taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
50 Examples
4
Example 1
Project: mrq Source File: utils.py
def requires_auth(f):
cfg = get_current_config()
if not cfg["dashboard_httpauth"]:
return f
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 2
def auth_func(*args, **kw):
if request.authorization:
ucontr = UserController()
try:
user = ucontr.get(nickname=request.authorization.username)
except NotFound:
raise ProcessingException("Couldn't authenticate your user",
code=401)
if not ucontr.check_password(user, request.authorization.password):
raise ProcessingException("Couldn't authenticate your user",
code=401)
if not user.is_active:
raise ProcessingException("User is desactivated", code=401)
login_user_bundle(user)
if not current_user.is_authenticated:
raise ProcessingException(description='Not authenticated!', code=401)
3
Example 3
Project: dpxdt Source File: auth.py
def _get_api_key_ops():
"""Gets the operations.ApiKeyOps instance for the current request."""
auth_header = request.authorization
if not auth_header:
logging.debug('API request lacks authorization header')
abort(flask.Response(
'API key required', 401,
{'WWW-Authenticate': 'Basic realm="API key required"'}))
return operations.ApiKeyOps(auth_header.username, auth_header.password)
3
Example 4
Project: flask-sentinel Source File: basicauth.py
def requires_basicauth(f):
@wraps(f)
def decorated(*args, **kwargs):
user = current_app.config.get('SENTINEL_MANAGEMENT_USERNAME')
pw = current_app.config.get('SENTINEL_MANAGEMENT_PASSWORD')
auth = request.authorization
if user and pw:
if not auth or \
not check_auth(auth.username, auth.password, user, pw):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 5
def requires_auth(f):
"""Decorator to require basic authentication for route."""
@wraps(f)
def decorated(*args, **kwargs):
"""This docstring intentionally left blank."""
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 6
def requires_auth(f):
""" Ensures that any NSA official trying to gain access to
the panel is using a valid username and password.
This is a decorator, so it's fairly simple to use:
@app.route("/")
@requires_auth
def index():
# ...
:param f: the function to wrap.
"""
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return basic_authenticate()
return f(*args, **kwargs)
return decorated
3
Example 7
def authenticate(func):
@wraps(func)
def wrapper(*args, **kwargs):
if request.authorization:
ucontr = UserController()
try:
user = ucontr.get(nickname=request.authorization.username)
except NotFound:
raise Forbidden("Couldn't authenticate your user")
if not ucontr.check_password(user, request.authorization.password):
raise Forbidden("Couldn't authenticate your user")
if not user.is_active:
raise Forbidden("User is desactivated")
login_user_bundle(user)
if current_user.is_authenticated:
return func(*args, **kwargs)
raise Unauthorized()
return wrapper
3
Example 8
def __call__(self, f):
@wraps(f)
def decorated(*args, **kwargs):
# If the user didn't provide a user database file we won't ask for
# authentication here
if not self.db.enabled():
return f(*args, **kwargs)
# Let's just authenticate the user, returning the actual view on
# success or the `self.authenticate()` result otherwise
auth = request.authorization
if not auth or not self.db.auth(auth.username, auth.password):
return self.authenticate()
return f(*args, **kwargs)
return decorated
3
Example 9
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 10
Project: maproulette Source File: helpers.py
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
app.logger.debug(request.url)
if not is_localhost(request.url) and (not auth or not check_auth(auth.username, auth.password)):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 11
Project: bepasty-server Source File: permissions.py
def get_permissions():
"""
get the permissions for the current user (if logged in)
or the default permissions (if not logged in).
"""
auth = request.authorization
if auth:
# http basic auth header present
permissions = lookup_permissions(auth.password)
elif 'token' in request.values:
# token present in query args or post form (can be used by cli clients)
permissions = lookup_permissions(request.values['token'])
else:
# look into session, login might have put something there
permissions = session.get(PERMISSIONS)
if permissions is None:
permissions = current_app.config['DEFAULT_PERMISSIONS']
permissions = set(permissions.split(','))
return permissions
3
Example 12
def requires_auth(f):
"""Decorator for methods that require authentication."""
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 13
Project: DockCI Source File: handlers.py
def try_basic_auth(idents_set):
"""
Use ``try_all_auth`` to attempt authorization from HTTP basic auth. Only
the password is used for API key
"""
auth = request.authorization
if not auth:
return None
return try_all_auth(
auth.password,
auth.password,
auth.username,
idents_set,
)
3
Example 14
Project: kalliope Source File: utils.py
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
settings = SettingLoader.get_settings()
if settings.rest_api.password_protected:
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 15
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
resp = jsonify({"message": "Please authenticate."})
resp.status_code = 401
resp.headers['WWW-Authenticate'] = 'Basic realm="Example"'
return resp
kwargs['user'] = User.get(User.email == auth.username)
return f(*args, **kwargs)
return decorated
3
Example 16
Project: a2billing-flask-api Source File: views.py
def custom_login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
basic_auth = request.authorization
if not basic_auth:
return response_auth_failed()
g.user = auth.authenticate(basic_auth.username, basic_auth.password)
if not g.user:
return response_auth_failed()
return f(*args, **kwargs)
return decorated_function
3
Example 17
Project: maraschino Source File: tools.py
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if maraschino.AUTH['username'] != None and maraschino.AUTH['password'] != None:
creds = maraschino.AUTH
else:
return f(*args, **kwargs)
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 18
def authorized(self, allowed_roles, resource, method):
""" Validates the the current request is allowed to pass through.
:param allowed_roles: allowed roles for the current request, can be a
string or a list of roles.
:param resource: resource being requested.
"""
auth = request.authorization
if auth:
self.set_user_or_token(auth.username)
return auth and self.check_auth(auth.username, auth.password,
allowed_roles, resource, method)
3
Example 19
def authorized(self, allowed_roles, resource, method):
authorized = False
if request.authorization:
auth = request.authorization
authorized = self.check_auth(auth.username, auth.password,
allowed_roles, resource, method)
elif request.args.get('access_token'):
access_token = request.args.get('access_token')
authorized = self.check_token(access_token, allowed_roles, resource, method)
else:
try:
access_token = request.headers.get('Authorization').split(' ')[1]
authorized = self.check_token(access_token, allowed_roles, resource, method)
except:
pass
return authorized
3
Example 20
def requires_auth(self, func):
'''
Decorator to prompt for user name and password. Useful for data dumps,
etc. That you don't want to be public.
'''
@wraps(func)
def decorated(*args, **kwargs):
''' Wrapper '''
auth = request.authorization
if not auth or not self.check_auth(auth.username, auth.password):
return self.authenticate()
return func(*args, **kwargs)
return decorated
3
Example 21
Project: WAPT Source File: decorators.py
def _check_http_auth():
auth = request.authorization or BasicAuth(username=None, password=None)
user = _security.datastore.find_user(email=auth.username)
if user and utils.verify_and_update_password(auth.password, user):
_security.datastore.commit()
app = current_app._get_current_object()
_request_ctx_stack.top.user = user
identity_changed.send(app, identity=Identity(user.id))
return True
return False
3
Example 22
@plugin.before_request
def check_credentials():
UNAUTHORIZED = Response(response="Could not verify your credentials", status=401, headers = {'WWW-Authenticate':'Basic realm="Login Required"'})
auth = request.authorization
if not auth:
return UNAUTHORIZED
if auth.username != PLUGIN_USERNAME or auth.password != PLUGIN_PASSWORD:
return UNAUTHORIZED
# It's valid
return None
3
Example 23
def requires_auth(f):
@wraps(f)
def decorated():
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(auth.username)
return decorated
3
Example 24
Project: open-event-orga-server Source File: helpers.py
def auth_basic():
"""
Check for basic auth in header. Return a tuple as result
The second value of tuple is set only when user tried basic_auth
"""
auth = request.authorization # only works in Basic auth
if not auth:
return (False, '')
user = UserModel.query.filter_by(email=auth.username).first()
auth_ok = False
if user is not None:
auth_ok = check_password_hash(
auth.password.encode('utf-8'),
user.password.encode('utf-8'),
user.salt)
if not auth_ok:
return (False, 'Authentication failed. Wrong username or password')
g.user = user
return (True, '')
3
Example 25
Project: weblabdeusto Source File: sample.py
def check_http_credentials(testing=False):
auth = request.authorization
if auth:
username = auth.username
password = auth.password
else:
username = password = "No credentials"
weblab_username = app.config['WEBLAB_USERNAME']
weblab_password = app.config['WEBLAB_PASSWORD']
if username != weblab_username or password != weblab_password:
if testing:
return Response(json.dumps(dict(valid=False, error_messages=["Invalid credentials"])), status=401, headers = {'WWW-Authenticate':'Basic realm="Login Required"', 'Content-Type': 'application/json'})
print("In theory this is weblab. However, it provided as credentials: {} : {}".format(username, password))
return Response(response=("You don't seem to be a WebLab-Instance"), status=401, headers = {'WWW-Authenticate':'Basic realm="Login Required"'})
return None
3
Example 26
Project: lastuser Source File: helpers.py
def _client_login_inner():
if request.authorization is None or not request.authorization.username:
return Response('Client credentials required', 401,
{'WWW-Authenticate': 'Basic realm="Client credentials"'})
credential = ClientCredential.get(name=request.authorization.username)
if credential is None or not credential.secret_is(request.authorization.password):
return Response('Invalid client credentials', 401,
{'WWW-Authenticate': 'Basic realm="Client credentials"'})
if credential:
credential.accessed_at = db.func.utcnow()
db.session.commit()
g.client = credential.client
3
Example 27
Project: JARR Source File: common.py
def authenticate(func):
@wraps(func)
def wrapper(*args, **kwargs):
if request.authorization:
ucontr = UserController()
try:
user = ucontr.get(login=request.authorization.username)
except NotFound:
raise Forbidden("Couldn't authenticate your user")
if not ucontr.check_password(user, request.authorization.password):
raise Forbidden("Couldn't authenticate your user")
if not user.is_active:
raise Forbidden("User is desactivated")
login_user_bundle(user)
if current_user.is_authenticated:
return func(*args, **kwargs)
raise Unauthorized()
return wrapper
3
Example 28
Project: blaze Source File: server.py
def authorization(f):
@functools.wraps(f)
def authorized(*args, **kwargs):
if not _get_auth()(flask.request.authorization):
return Response('bad auth token',
RC.UNAUTHORIZED,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
return f(*args, **kwargs)
return authorized
3
Example 29
def rate():
"""Set rate limits for authenticated and nonauthenticated users."""
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return "60/minute"
else:
return "600/minute"
3
Example 30
def requires_admin(f): # pragma: no cover
"""Decorator to define endpoints that requires Basic Auth.
Args:
f (func): An route function.
Returns:
response (object): 401 if unauthorized.
f (func): The route to call.
"""
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
3
Example 31
def authenticate(self):
"""
Check the request for HTTP basic access authentication header and try
to authenticate the user.
:returns: `True` if the user is authorized, or `False` otherwise.
"""
auth = request.authorization
return (
auth and auth.type == 'basic' and
self.check_credentials(auth.username, auth.password)
)
3
Example 32
Project: cloudify-manager Source File: secured_resource.py
def authenticate_and_authorize(func):
@wraps(func)
def wrapper(*args, **kwargs):
auth = request.authorization
user, hashed_pass = get_user_and_hashed_pass(request)
user = authenticator.authenticate(user, hashed_pass, auth)
role_authorizer.authorize(user, request)
tenant_authorizer.authorize(user, request)
# Passed authentication and authorization
return func(*args, **kwargs)
return wrapper
3
Example 33
def required(fn):
@functools.wraps(fn)
def decorated(*args, **kwargs):
auth = flask.request.authorization
if not check_auth(auth):
return "you do not have access to this resource", 401
return fn(*args, **kwargs)
return decorated
3
Example 34
def requires_auth(view):
"""Require basic authentication on requests to this view.
Also only accept requests from localhost.
"""
@wraps(view)
def decorated(*args, **kwargs):
"""Decorated version of view that checks authentication."""
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
if request.remote_addr != "127.0.0.1":
return Response("Access outside 127.0.0.1 forbidden", 403)
return view(*args, **kwargs)
return decorated
3
Example 35
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
0
Example 36
@app.route('/v1/users/<username>/update', methods=['POST'])
@parameters_required(['profile', 'owner_pubkey'])
@crossdomain(origin='*')
def update_user(username):
reply = {}
try:
user = get_authenticated_user(request.authorization)
except Exception as e:
raise GenericError(str(e))
try:
hex_privkey = aes_decrypt(user.encrypted_privkey, SECRET_KEY)
except Exception as e:
raise GenericError(str(e))
wallet = HDWallet(hex_privkey)
data = json.loads(request.data)
fqu = username + "." + DEFAULT_NAMESPACE
profile = data['profile']
profile_hash = get_hash(profile)
owner_pubkey = data['owner_pubkey']
try:
blockchain_record = bs_client.get_name_blockchain_record(fqu)
except Exception as e:
raise GenericError(str(e))
if 'value_hash' not in blockchain_record:
raise GenericError("Not yet registered %s" % fqu)
owner_address = blockchain_record['address']
check_address = get_address_from_pubkey(str(owner_pubkey))
if check_address != owner_address:
raise GenericError("Given pubkey/address doesn't own this name.")
if USE_DEFAULT_PAYMENT and PAYMENT_PRIVKEY is not None:
payment_privkey = BitcoinPrivateKey(PAYMENT_PRIVKEY)
payment_privkey = payment_privkey.to_hex()
else:
pubkey, payment_privkey = wallet.get_next_keypair()
if payment_privkey is None:
raise PaymentError(addresses=wallet.get_keypairs(DEFAULT_CHILD_ADDRESSES))
resp = {}
try:
resp = bs_client.update_subsidized(fqu, profile_hash,
public_key=owner_pubkey,
subsidy_key=payment_privkey)
except Exception as e:
reply['error'] = str(e)
return jsonify(reply), 200
if 'subsidized_tx' in resp:
reply['unsigned_tx'] = resp['subsidized_tx']
else:
if 'error' in resp:
reply['error'] = resp['error']
else:
reply['error'] = resp
return jsonify(reply), 200
0
Example 37
@app.route('/v1/users/<username>/transfer', methods=['POST'])
@parameters_required(['transfer_address', 'owner_pubkey'])
@crossdomain(origin='*')
def transfer_user(username):
reply = {}
try:
user = get_authenticated_user(request.authorization)
except Exception as e:
raise GenericError(str(e))
try:
hex_privkey = aes_decrypt(user.encrypted_privkey, SECRET_KEY)
except Exception as e:
raise GenericError(str(e))
wallet = HDWallet(hex_privkey)
data = json.loads(request.data)
fqu = username + "." + DEFAULT_NAMESPACE
transfer_address = data['transfer_address']
owner_pubkey = data['owner_pubkey']
try:
blockchain_record = bs_client.get_name_blockchain_record(fqu)
except Exception as e:
raise GenericError(str(e))
if 'value_hash' not in blockchain_record:
raise GenericError("Not yet registered %s" % fqu)
owner_address = blockchain_record['address']
check_address = get_address_from_pubkey(str(owner_pubkey))
if check_address != owner_address:
raise GenericError("Given pubkey/address doesn't own this name.")
if not is_b58check_address(transfer_address):
raise InvalidAddressError(transfer_address)
if USE_DEFAULT_PAYMENT and PAYMENT_PRIVKEY is not None:
payment_privkey = BitcoinPrivateKey(PAYMENT_PRIVKEY)
payment_privkey = payment_privkey.to_hex()
else:
pubkey, payment_privkey = wallet.get_next_keypair()
if payment_privkey is None:
raise PaymentError(addresses=wallet.get_keypairs(DEFAULT_CHILD_ADDRESSES))
resp = {}
try:
resp = bs_client.transfer_subsidized(fqu, transfer_address,
keep_data=True,
public_key=owner_pubkey,
subsidy_key=payment_privkey)
except Exception as e:
reply['error'] = str(e)
return jsonify(reply), 200
if 'subsidized_tx' in resp:
reply['unsigned_tx'] = resp['subsidized_tx']
else:
if 'error' in resp:
reply['error'] = resp['error']
else:
reply['error'] = resp
return jsonify(reply), 200
0
Example 38
def login_required(self, f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if auth is None and 'Authorization' in request.headers:
# Flask/Werkzeug do not recognize any authentication types
# other than Basic or Digest, so here we parse the header by
# hand
try:
auth_type, token = request.headers['Authorization'].split(
None, 1)
auth = Authorization(auth_type, {'token': token})
except ValueError:
# The Authorization header is either empty or has no token
pass
# if the auth type does not match, we act as if there is no auth
# this is better than failing directly, as it allows the callback
# to handle special cases, like supporting multiple auth types
if auth is not None and auth.type.lower() != self.scheme.lower():
auth = None
# Flask normally handles OPTIONS requests on its own, but in the
# case it is configured to forward those to the application, we
# need to ignore authentication headers and let the request through
# to avoid unwanted interactions with CORS.
if request.method != 'OPTIONS': # pragma: no cover
if auth and auth.username:
password = self.get_password_callback(auth.username)
else:
password = None
if not self.authenticate(auth, password):
# Clear TCP receive buffer of any pending data
request.data
return self.auth_error_callback()
return f(*args, **kwargs)
return decorated
0
Example 39
Project: flask-simpleldap Source File: __init__.py
def basic_auth_required(self, func):
"""When applied to a view function, any unauthenticated requests are
asked to authenticate via HTTP's standard Basic Authentication system.
Requests with credentials are checked with :meth:`.bind_user()`.
The user's browser will typically show them the contents of
LDAP_REALM_NAME as a prompt for which username and password to enter.
If the request's credentials are accepted by the LDAP server, the
username is stored in ``flask.g.ldap_username`` and the password in
``flask.g.ldap_password``.
:param func: The view function to decorate.
"""
def make_auth_required_response():
response = make_response('Unauthorized', 401)
response.www_authenticate.set_basic(
current_app.config['LDAP_REALM_NAME'])
return response
@wraps(func)
def wrapped(*args, **kwargs):
if request.authorization is None:
req_username = None
req_password = None
else:
req_username = request.authorization.username
req_password = request.authorization.password
# Many LDAP servers will grant you anonymous access if you log in
# with an empty password, even if you supply a non-anonymous user
# ID, causing .bind_user() to return True. Therefore, only accept
# non-empty passwords.
if req_username in ['', None] or req_password in ['', None]:
current_app.logger.debug('Got a request without auth data')
return make_auth_required_response()
if not self.bind_user(req_username, req_password):
current_app.logger.debug('User {0!r} gave wrong '
'password'.format(req_username))
return make_auth_required_response()
g.ldap_username = req_username
g.ldap_password = req_password
return func(*args, **kwargs)
return wrapped
0
Example 40
def username(self):
if not request.authorization:
return ""
return request.authorization.username
0
Example 41
def require_login(self, f):
@wraps(f)
def decorated(*args, **kwargs):
auth = flask.request.authorization
# We need to ignore authentication headers for OPTIONS to avoid
# unwanted interactions with CORS.
# Chrome and Firefox issue a preflight OPTIONS request to check
# Access-Control-* headers, and will fail if it returns 401.
if flask.request.method != 'OPTIONS':
if not auth:
return self.auth_error_callback()
username = self.username(**self.settings)
self.printdebug("Obtained username: " + username)
try:
password = self.get_password(username, **self.settings)
if not password:
self.printdebug("Unable to obtain password for user " + username)
return self.auth_error_callback()
except KeyError:
self.printdebug("No such user")
return self.auth_error_callback()
if not self.authenticate(auth, password):
return self.auth_error_callback()
#add username as parameter to the wrapped function
kwargs['credentials'] = username
else:
#add username as parameter to the wrapped function
kwargs['credentials'] = 'anonymous'
return f(*args,**kwargs)
return decorated
0
Example 42
def check_basic_auth(user, passwd):
"""Checks user authentication using HTTP Basic Auth."""
auth = request.authorization
return auth and auth.username == user and auth.password == passwd
0
Example 43
def authorized(self, allowed_roles, resource, method):
""" Validates the the current request is allowed to pass through.
:param allowed_roles: allowed roles for the current request, can be a
string or a list of roles.
:param resource: resource being requested.
"""
auth = None
if hasattr(request.authorization, 'username'):
auth = request.authorization.username
# Werkzeug parse_authorization does not handle
# "Authorization: <token>" or
# "Authorization: Token <token>" or
# "Authorization: Bearer <token>"
# headers, therefore they should be explicitly handled
if not auth and request.headers.get('Authorization'):
auth = request.headers.get('Authorization').strip()
if auth.lower().startswith(('token', 'bearer')):
auth = auth.split(' ')[1]
if auth:
self.set_user_or_token(auth)
return auth and self.check_auth(auth, allowed_roles, resource,
method)
0
Example 44
def requires_auth(f):
"""
"""
with open(os.path.expanduser("~/config/.note.conf")) as fd:
config = json.loads(fd.read())
try:
login = config['server']['login']
if 'username' in login.keys() and 'password' in login.keys():
authOn = True
else:
authOn = False
except KeyError:
authOn = False
if authOn:
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
else:
@wraps(f)
def decorated(*args, **kwargs):
return f(*args, **kwargs)
return decorated
0
Example 45
@app.route('/')
def home():
'''Serve the status page of the capture agent.
'''
# Check credentials:
if config['ui']['password'] and not request.authorization \
or request.authorization.username != config['ui']['username'] \
or request.authorization.password != config['ui']['password']:
return Response('pyCA', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
# Get IDs of existing preview images
preview = config['capture']['preview']
previewdir = config['capture']['preview_dir']
preview = [p.replace('{{previewdir}}', previewdir) for p in preview]
preview = zip(preview, range(len(preview)))
preview = [p[1] for p in preview if os.path.isfile(p[0])]
template = Template(__SITE)
return template.render(preview=preview,
refresh=config['ui']['refresh_rate'])
0
Example 46
Project: labmanager Source File: basic_http.py
@basic_http_blueprint.before_request
def requires_lms_auth():
UNAUTHORIZED = Response(response=gettext("Could not verify your credentials for that URL"), status=401, headers = {'WWW-Authenticate':'Basic realm="Login Required"'})
auth = request.authorization
if not auth:
json_data = get_json()
if json_data is None:
return UNAUTHORIZED
username = json_data.get('lms_username','')
password = json_data.get('lms_password','')
else:
username = auth.username
password = auth.password
password = unicode(password)
hash_password = hashlib.new('sha', password.encode('utf8')).hexdigest()
# TODO: check if there could be a conflict between two LTs with same key??
credential = db.session.query(BasicHttpCredentials).filter_by(lt_login = username, lt_password = hash_password).first()
if credential is None:
return UNAUTHORIZED
g.lt = credential.lt.name
0
Example 47
Project: labmanager Source File: fake_lms.py
@app.route("/fake_list_courses/gateway4labs/list", methods = ['GET','POST'])
def fake_list_courses():
# return """{"start":"2","number":3,"per-page":2,"courses":[{"id":"4","name":"example3"}]}"""
auth = request.authorization
if auth is None or auth.username not in ('test','labmanager') or auth.password not in ('test','password'):
return Response(gettext('You have to login with proper credentials'), 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
q = request.args.get('q','')
start_str = request.args.get('start','0')
try:
start = int(start_str)
except:
return gettext("Invalid start")
fake_data = []
for pos in xrange(10000):
if pos % 3 == 0:
fake_data.append((str(pos), gettext("Fake electronics course %(coursepos)s", coursepos=pos)))
elif pos % 3 == 1:
fake_data.append((str(pos), gettext("Fake physics course %(coursepos)s", coursepos=pos)))
else:
fake_data.append((str(pos), gettext("Fake robotics course %(coursepos)s", coursepos=pos)))
fake_return_data = []
for key, value in fake_data:
if q in value:
fake_return_data.append({
'id' : key,
'name' : value,
})
N = 10
view = {
'start' : start,
'number' : len(fake_return_data),
'per-page' : N,
'courses' : fake_return_data[start:start+N],
}
return json.dumps(view, indent = 4)
0
Example 48
def require_login(self, f):
@wraps(f)
def decorated(*args, **kwargs):
auth = flask.request.authorization
# We need to ignore authentication headers for OPTIONS to avoid
# unwanted interactions with CORS.
# Chrome and Firefox issue a preflight OPTIONS request to check
# Access-Control-* headers, and will fail if it returns 401.
if flask.request.method != 'OPTIONS':
if not auth:
return self.auth_error_callback()
try:
username = self.username(**self.settings)
except KeyError:
return self.auth_error_callback()
#add username as parameter to the wrapped function
kwargs['credentials'] = username
else:
kwargs['credentials'] = 'anonymous'
return f(*args, **kwargs)
return decorated
0
Example 49
Project: NIPAP Source File: xmlrpc.py
def requires_auth(f):
""" Class decorator for XML-RPC functions that requires auth
"""
@wraps(f)
def decorated(self, *args, **kwargs):
"""
"""
# Fetch auth options from args
auth_options = {}
nipap_args = {}
# validate function arguments
if len(args) == 1:
nipap_args = args[0]
else:
self.logger.debug("Malformed request: got %d parameters" % len(args))
raise Fault(1000, ("NIPAP API functions take exactly 1 argument (%d given)") % len(args))
if type(nipap_args) != dict:
self.logger.debug("Function argument is not struct")
raise Fault(1000, ("Function argument must be XML-RPC struct/Python dict (Python %s given)." %
type(nipap_args).__name__ ))
# fetch auth options
try:
auth_options = nipap_args['auth']
if type(auth_options) is not dict:
raise ValueError()
except (KeyError, ValueError):
self.logger.debug("Missing/invalid authentication options in request.")
raise Fault(1000, ("Missing/invalid authentication options in request."))
# fetch authoritative source
try:
auth_source = auth_options['authoritative_source']
except KeyError:
self.logger.debug("Missing authoritative source in auth options.")
raise Fault(1000, ("Missing authoritative source in auth options."))
if not request.authorization:
return authenticate()
# init AuthFacory()
af = AuthFactory()
auth = af.get_auth(request.authorization.username,
request.authorization.password, auth_source, auth_options or {})
# authenticated?
if not auth.authenticate():
self.logger.debug("Incorrect username or password.")
raise Fault(1510, ("Incorrect username or password."))
# Replace auth options in API call arguments with auth object
new_args = dict(args[0])
new_args['auth'] = auth
return f(self, *(new_args,), **kwargs)
return decorated
0
Example 50
def login_handler(self, config=None, prefix=None, **args):
"""HTTP Basic login handler.
Respond with 401 and WWW-Authenticate header if there are no credentials
or bad credentials. If there are credentials then simply check for username
equal to password for validity.
"""
headers = {}
headers['Access-control-allow-origin'] = '*'
headers['Content-type'] = 'text/html'
auth = request.authorization
if (auth and auth.username == auth.password):
html = "<html><script>window.close();</script></html>"
response = make_response(html, 200, headers)
response.set_cookie(self.auth_cookie_name,
"valid-http-basic-login", expires=3600)
return response
else:
headers[
'WWW-Authenticate'] = 'Basic realm="HTTP-Basic-Auth at %s (u=p to login)"' % (self.name)
return make_response("", 401, headers)