# Functions for checking authantication for API clients. import base64 import scrypt def get_credentials(request): '''Return username, password of API client. They're assumed to be conveyed in an Authorization header using Basic Auth. ''' header = request.get_header('Authorization') if header is None: raise AuthenticationError('No Authorization header') words = header.split() if len(words) == 0: raise AuthenticationError('Authorization header has no value') if len(words) != 2 or words[0].lower() != 'basic': raise AuthenticationError('Authorization header is not for Basic Auth') decoded = base64.b64decode(words[1]) return decoded.split(':', 1) class AuthenticationError(Exception): pass def encrypt_password(salt, password): return scrypt.hash(password, salt).encode('hex') def get_scopes(users, request): username, password = get_credentials(request) if username not in users['users']: raise AuthenticationError('Error authenticating') user = users['users'][username] encrypted = encrypt_password(user['salt'], password) if encrypted != user['password']: raise AuthenticationError('Error authenticating') return user['scopes']