'''
    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
from ..database.Model import ApiKey, User

def auth_basic(username, password, required_scopes=None):
	user = User.query.filter_by(username=username).all()
	if len(user) != 1:
		return None
	if user[0].password_verify(password):
		return {'sub': user[0].username}
	return None

def auth_api(apikey, required_scopes=None):
	keys = ApiKey.query.filter_by(key=apikey).all()
	if len(keys) != 1:
		return None
	
	key_db = keys[0]
	if apikey == key_db.key:
		return {'sub': key_db.user.username }

	# optional: raise exception for custom error response
	return None
