Reenabled multiple oauth provider

deleted duplicate download counting function
pull/976/head
Ozzieisaacs 5 years ago
parent c6542fdec6
commit 38f3c2d5b9

@ -344,18 +344,27 @@ def _configuration_update_helper():
_config_int("config_updatechannel")
# GitHub OAuth configuration
if config.config_login_type == constants.LOGIN_OAUTH_GITHUB:
_config_string("config_github_oauth_client_id")
_config_string("config_github_oauth_client_secret")
if not config.config_github_oauth_client_id or not config.config_github_oauth_client_secret:
return _configuration_result('Please enter Github oauth credentials', gdriveError)
# Google OAuth configuration
if config.config_login_type == constants.LOGIN_OAUTH_GOOGLE:
_config_string("config_google_oauth_client_id")
_config_string("config_google_oauth_client_secret")
if not config.config_google_oauth_client_id or not config.config_google_oauth_client_secret:
return _configuration_result('Please enter Google oauth credentials', gdriveError)
if config.config_login_type == constants.LOGIN_OAUTH:
active_oauths = 0
for element in oauthblueprints:
if to_save["config_"+str(element['id'])+"_oauth_client_id"] \
and to_save["config_"+str(element['id'])+"_oauth_client_secret"]:
active_oauths += 1
element["active"] = 1
ub.session.query(ub.OAuthProvider).filter(ub.OAuthProvider.id == element['id']).update(
{"oauth_client_id":to_save["config_"+str(element['id'])+"_oauth_client_id"],
"oauth_client_secret":to_save["config_"+str(element['id'])+"_oauth_client_secret"],
"active":1})
if to_save["config_" + str(element['id']) + "_oauth_client_id"] != element['oauth_client_id'] \
or to_save["config_" + str(element['id']) + "_oauth_client_secret"] != element['oauth_client_secret']:
reboot_required = True
element['oauth_client_id'] = to_save["config_"+str(element['id'])+"_oauth_client_id"]
element['oauth_client_secret'] = to_save["config_"+str(element['id'])+"_oauth_client_secret"]
else:
ub.session.query(ub.OAuthProvider).filter(ub.OAuthProvider.id == element['id']).update(
{"active":0})
element["active"] = 0
_config_int("config_log_level")
_config_string("config_logfile")

@ -31,7 +31,7 @@ try:
from comicapi.comicarchive import ComicArchive, MetaDataStyle
use_comic_meta = True
except ImportError as e:
log.warning('cannot import comicapi, extracting comic metadata will not work: %s', e)
log.debug('cannot import comicapi, extracting comic metadata will not work: %s', e)
import zipfile
import tarfile
use_comic_meta = False

@ -84,11 +84,7 @@ class _Settings(_Base):
config_login_type = Column(Integer, default=0)
config_oauth_provider = Column(Integer)
#config_github_oauth_client_id = Column(String)
#config_github_oauth_client_secret = Column(String)
#config_google_oauth_client_id = Column(String)
#config_google_oauth_client_secret = Column(String)
# config_oauth_provider = Column(Integer)
config_ldap_provider_url = Column(String, default='localhost')
config_ldap_port = Column(SmallInteger, default=389)
@ -310,12 +306,3 @@ def load_configuration(session):
session.commit()
return _ConfigSQL(session)
def load_oauth(session):
#_migrate_database(session)
if not session.query(OAuthProvider).count():
session.add(_Settings())
session.commit()
return _ConfigSQL(session)

@ -91,8 +91,8 @@ AUTO_UPDATE_NIGHTLY = 1 << 2
LOGIN_STANDARD = 0
LOGIN_LDAP = 1
LOGIN_OAUTH_GITHUB = 2
LOGIN_OAUTH_GOOGLE = 3
LOGIN_OAUTH = 2
# LOGIN_OAUTH_GOOGLE = 3
DEFAULT_PASSWORD = "admin123"

@ -71,15 +71,6 @@ from .worker import TASK_EMAIL, TASK_CONVERT, TASK_UPLOAD, TASK_CONVERT_ANY
log = logger.create()
# ToDo delete duplicate
def update_download(book_id, user_id):
check = ub.session.query(ub.Downloads).filter(ub.Downloads.user_id == user_id).filter(ub.Downloads.book_id ==
book_id).first()
if not check:
new_download = ub.Downloads(user_id=user_id, book_id=book_id)
ub.session.add(new_download)
ub.session.commit()
# Convert existing book entry to new format
def convert_book_format(book_id, calibrepath, old_book_format, new_book_format, user_id, kindle_mail=None):
book = db.session.query(db.Books).filter(db.Books.id == book_id).first()

@ -32,13 +32,14 @@ try:
.. _SQLAlchemy: http://www.sqlalchemy.org/
"""
def __init__(self, model, session,
def __init__(self, model, session, provider_id,
user=None, user_id=None, user_required=None, anon_user=None,
cache=None):
self.provider_id = provider_id
super(OAuthBackend, self).__init__(model, session, user, user_id, user_required, anon_user, cache)
def get(self, blueprint, user=None, user_id=None):
if blueprint.name + '_oauth_token' in session and session[blueprint.name + '_oauth_token'] != '':
if self.provider_id + '_oauth_token' in session and session[self.provider_id + '_oauth_token'] != '':
return session[blueprint.name + '_oauth_token']
# check cache
cache_key = self.make_cache_key(blueprint=blueprint, user=user, user_id=user_id)
@ -49,15 +50,15 @@ try:
# if not cached, make database queries
query = (
self.session.query(self.model)
.filter_by(provider=blueprint.name)
.filter_by(provider=self.provider_id)
)
uid = first([user_id, self.user_id, blueprint.config.get("user_id")])
u = first(_get_real_user(ref, self.anon_user)
for ref in (user, self.user, blueprint.config.get("user")))
use_provider_user_id = False
if blueprint.name + '_oauth_user_id' in session and session[blueprint.name + '_oauth_user_id'] != '':
query = query.filter_by(provider_user_id=session[blueprint.name + '_oauth_user_id'])
if self.provider_id + '_oauth_user_id' in session and session[self.provider_id + '_oauth_user_id'] != '':
query = query.filter_by(provider_user_id=session[self.provider_id + '_oauth_user_id'])
use_provider_user_id = True
if self.user_required and not u and not uid and not use_provider_user_id:
@ -94,7 +95,7 @@ try:
# if there was an existing model, delete it
existing_query = (
self.session.query(self.model)
.filter_by(provider=blueprint.name)
.filter_by(provider=self.provider_id)
)
# check for user ID
has_user_id = hasattr(self.model, "user_id")
@ -108,7 +109,7 @@ try:
existing_query.delete()
# create a new model for this token
kwargs = {
"provider": blueprint.name,
"provider": self.provider_id,
"token": token,
}
if has_user_id and uid:
@ -126,7 +127,7 @@ try:
def delete(self, blueprint, user=None, user_id=None):
query = (
self.session.query(self.model)
.filter_by(provider=blueprint.name)
.filter_by(provider=self.provider_id)
)
uid = first([user_id, self.user_id, blueprint.config.get("user_id")])
u = first(_get_real_user(ref, self.anon_user)

@ -45,40 +45,10 @@ oauth = Blueprint('oauth', __name__)
log = logger.create()
'''def github_oauth_required(f):
@wraps(f)
def inner(*args, **kwargs):
if config.config_login_type == constants.LOGIN_OAUTH_GITHUB:
return f(*args, **kwargs)
if request.is_xhr:
data = {'status': 'error', 'message': 'Not Found'}
response = make_response(json.dumps(data, ensure_ascii=False))
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response, 404
abort(404)
return inner
def google_oauth_required(f):
@wraps(f)
def inner(*args, **kwargs):
if config.config_use_google_oauth == constants.LOGIN_OAUTH_GOOGLE:
return f(*args, **kwargs)
if request.is_xhr:
data = {'status': 'error', 'message': 'Not Found'}
response = make_response(json.dumps(data, ensure_ascii=False))
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response, 404
abort(404)
return inner'''
def oauth_required(f):
@wraps(f)
def inner(*args, **kwargs):
if config.config_oauth_provider:
if config.config_login_type == constants.LOGIN_OAUTH:
return f(*args, **kwargs)
if request.is_xhr:
data = {'status': 'error', 'message': 'Not Found'}
@ -90,15 +60,14 @@ def oauth_required(f):
return inner
def register_oauth_blueprint(blueprint, show_name):
if blueprint.name != "":
oauth_check[blueprint.name] = show_name
def register_oauth_blueprint(id, show_name):
oauth_check[id] = show_name
def register_user_with_oauth(user=None):
all_oauth = {}
for oauth in oauth_check.keys():
if oauth + '_oauth_user_id' in session and session[oauth + '_oauth_user_id'] != '':
if str(oauth) + '_oauth_user_id' in session and session[str(oauth) + '_oauth_user_id'] != '':
all_oauth[oauth] = oauth_check[oauth]
if len(all_oauth.keys()) == 0:
return
@ -109,7 +78,7 @@ def register_user_with_oauth(user=None):
# Find this OAuth token in the database, or create it
query = ub.session.query(ub.OAuth).filter_by(
provider=oauth,
provider_user_id=session[oauth + "_oauth_user_id"],
provider_user_id=session[str(oauth) + "_oauth_user_id"],
)
try:
oauth = query.one()
@ -126,8 +95,8 @@ def register_user_with_oauth(user=None):
def logout_oauth_user():
for oauth in oauth_check.keys():
if oauth + '_oauth_user_id' in session:
session.pop(oauth + '_oauth_user_id')
if str(oauth) + '_oauth_user_id' in session:
session.pop(str(oauth) + '_oauth_user_id')
if ub.oauth_support:
oauthblueprints =[]
@ -142,30 +111,27 @@ if ub.oauth_support:
oauth.active = False
ub.session.add(oauth)
ub.session.commit()
'''new_scope = ub.OAuthScope(provider_id=oauth.id, scope="https://www.googleapis.com/auth/plus.me")
ub.session.add(new_scope)
ub.session.commit()
new_scope = ub.OAuthScope(provider_id=oauth.id, scope="https://www.googleapis.com/auth/userinfo.email")
ub.session.add(new_scope)
ub.session.commit()'''
ele1=dict(provider_name='Github',
active=False,
oauth_client_id=None,
oauth_ids = ub.session.query(ub.OAuthProvider).all()
ele1=dict(provider_name='github',
id=oauth_ids[0].id,
active=oauth_ids[0].active,
oauth_client_id=oauth_ids[0].oauth_client_id,
scope=None,
oauth_client_secret=None,
oauth_client_secret=oauth_ids[0].oauth_client_secret,
obtain_link='https://github.com/settings/developers')
ele2=dict(provider_name='Google',
active=False,
ele2=dict(provider_name='google',
id=oauth_ids[1].id,
active=oauth_ids[1].active,
scope=["https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email"],
oauth_client_id=None,
oauth_client_secret=None,
oauth_client_id=oauth_ids[1].oauth_client_id,
oauth_client_secret=oauth_ids[1].oauth_client_secret,
obtain_link='https://github.com/settings/developers')
oauthblueprints.append(ele1)
oauthblueprints.append(ele2)
for element in oauthblueprints:
if element['provider_name'] == 'Github':
if element['provider_name'] == 'github':
blueprint_func = make_github_blueprint
else:
blueprint_func = make_google_blueprint
@ -177,36 +143,10 @@ if ub.oauth_support:
)
element['blueprint']=blueprint
app.register_blueprint(blueprint, url_prefix="/login")
element['blueprint'].backend = OAuthBackend(ub.OAuth, ub.session, user=current_user, user_required=True)
element['blueprint'].backend = OAuthBackend(ub.OAuth, ub.session, str(element['id']),
user=current_user, user_required=True)
if element['active']:
register_oauth_blueprint(element['blueprint'], element['provider_name'])
'''github_blueprint = make_github_blueprint(
client_id=config.config_github_oauth_client_id,
client_secret=config.config_github_oauth_client_secret,
redirect_to="oauth.github_login")
google_blueprint = make_google_blueprint(
client_id=config.config_google_oauth_client_id,
client_secret=config.config_google_oauth_client_secret,
redirect_to="oauth.google_login",
scope=[
"https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/userinfo.email",
]
)
app.register_blueprint(google_blueprint, url_prefix="/login")
app.register_blueprint(github_blueprint, url_prefix='/login')
github_blueprint.backend = OAuthBackend(ub.OAuth, ub.session, user=current_user, user_required=True)
google_blueprint.backend = OAuthBackend(ub.OAuth, ub.session, user=current_user, user_required=True)'''
'''if config.config_login_type == constants.LOGIN_OAUTH_GITHUB:
register_oauth_blueprint(github_blueprint, 'GitHub')
if config.config_login_type == constants.LOGIN_OAUTH_GOOGLE:
register_oauth_blueprint(google_blueprint, 'Google')'''
register_oauth_blueprint(element['id'], element['provider_name'])
@oauth_authorized.connect_via(oauthblueprints[0]['blueprint'])
@ -222,7 +162,7 @@ if ub.oauth_support:
github_info = resp.json()
github_user_id = str(github_info["id"])
return oauth_update_token(blueprint, token, github_user_id)
return oauth_update_token(str(oauthblueprints[0]['id']), token, github_user_id)
@oauth_authorized.connect_via(oauthblueprints[1]['blueprint'])
@ -238,17 +178,16 @@ if ub.oauth_support:
google_info = resp.json()
google_user_id = str(google_info["id"])
return oauth_update_token(str(oauthblueprints[1]['id']), token, google_user_id)
return oauth_update_token(blueprint, token, google_user_id)
def oauth_update_token(blueprint, token, provider_user_id):
session[blueprint.name + "_oauth_user_id"] = provider_user_id
session[blueprint.name + "_oauth_token"] = token
def oauth_update_token(provider_id, token, provider_user_id):
session[provider_id + "_oauth_user_id"] = provider_user_id
session[provider_id + "_oauth_token"] = token
# Find this OAuth token in the database, or create it
query = ub.session.query(ub.OAuth).filter_by(
provider=blueprint.name,
provider=provider_id,
provider_user_id=provider_user_id,
)
try:
@ -257,7 +196,7 @@ if ub.oauth_support:
oauth.token = token
except NoResultFound:
oauth = ub.OAuth(
provider=blueprint.name,
provider=provider_id,
provider_user_id=provider_user_id,
token=token,
)
@ -272,9 +211,9 @@ if ub.oauth_support:
return False
def bind_oauth_or_register(provider, provider_user_id, redirect_url):
def bind_oauth_or_register(provider_id, provider_user_id, redirect_url):
query = ub.session.query(ub.OAuth).filter_by(
provider=provider,
provider=provider_id,
provider_user_id=provider_user_id,
)
try:
@ -311,7 +250,7 @@ if ub.oauth_support:
try:
oauths = query.all()
for oauth in oauths:
status.append(oauth.provider)
status.append(int(oauth.provider))
return status
except NoResultFound:
return None
@ -366,7 +305,7 @@ if ub.oauth_support:
account_info = github.get('/user')
if account_info.ok:
account_info_json = account_info.json()
return bind_oauth_or_register(oauthblueprints[0]['blueprint'].name, account_info_json['id'], 'github.login')
return bind_oauth_or_register(oauthblueprints[0]['id'], account_info_json['id'], 'github.login')
flash(_(u"GitHub Oauth error, please retry later."), category="error")
return redirect(url_for('web.login'))
@ -374,7 +313,7 @@ if ub.oauth_support:
@oauth.route('/unlink/github', methods=["GET"])
@login_required
def github_login_unlink():
return unlink_oauth(oauthblueprints[0]['blueprint'].name)
return unlink_oauth(oauthblueprints[0]['id'])
@oauth.route('/login/google')
@ -385,7 +324,7 @@ if ub.oauth_support:
resp = google.get("/oauth2/v2/userinfo")
if resp.ok:
account_info_json = resp.json()
return bind_oauth_or_register(oauthblueprints[1]['blueprint'].name, account_info_json['id'], 'google.login')
return bind_oauth_or_register(oauthblueprints[1]['id'], account_info_json['id'], 'google.login')
flash(_(u"Google Oauth error, please retry later."), category="error")
return redirect(url_for('web.login'))

@ -260,12 +260,12 @@
<a href="{{prov['obtain_link']}}" target="_blank">{{_('Obtain %(provider)s OAuth Credential', provider=prov['provider_name'])}}</a>
</div>
<div class="form-group">
<label for="config_{{ prov['provider_name'] }}_oauth_client_id">{{_('%(provider)s OAuth Client Id', provider=prov['provider_name'])}}</label>
<input type="text" class="form-control" id="config_{{ prov['provider_name'] }}_oauth_client_id" name="config_{{ prov['provider_name'] }}_oauth_client_id" value="{% if prov['active'] %}{{ prov['oauth_client_id'] }}{% endif %}" autocomplete="off">
<label for="config_{{ prov['id'] }}_oauth_client_id">{{_('%(provider)s OAuth Client Id', provider=prov['provider_name'])}}</label>
<input type="text" class="form-control" id="config_{{ prov['id'] }}_oauth_client_id" name="config_{{ prov['id'] }}_oauth_client_id" value="{% if prov['oauth_client_id']%}{{ prov['oauth_client_id'] }}{% endif %}" autocomplete="off">
</div>
<div class="form-group">
<label for="config_{{ prov['provider_name'] }}_oauth_client_secret">{{_('%(provider)s OAuth Client Secret', provider=prov['provider_name'])}}</label>
<input type="text" class="form-control" id="config_{{ prov['provider_name'] }}_oauth_client_secret" name="config_{{ prov['provider_name'] }}_oauth_client_secret" value="{% if prov['active'] %}{{ prov['oauth_client_id'] }}{% endif %}" autocomplete="off">
<label for="config_{{ prov['id'] }}_oauth_client_secret">{{_('%(provider)s OAuth Client Secret', provider=prov['provider_name'])}}</label>
<input type="text" class="form-control" id="config_{{ prov['id'] }}_oauth_client_secret" name="config_{{ prov['id'] }}_oauth_client_secret" value="{% if prov['oauth_client_secret']%}{{ prov['oauth_client_secret'] }}{% endif %}" autocomplete="off">
</div>
{% endfor %}
</div>

@ -47,13 +47,13 @@
</div>
{% if registered_oauth.keys()| length > 0 %}
{% for oauth, name in registered_oauth.iteritems() %}
{% for id, name in registered_oauth.items() %}
<div class="form-group">
<label>{{ name }} {{_('OAuth Settings')}}</label>
{% if oauth not in oauth_status %}
<div><a href="{{ url_for(oauth +'.login') }}" id="config_{{ oauth }}_oauth" class="btn btn-primary">{{_('Link')}}</a></div>
{% if id not in oauth_status %}
<div><a href="{{ url_for('oauth.'+ name +'_login') }}" id="config_{{ id }}_oauth" class="btn btn-primary">{{_('Link')}}</a></div>
{% else %}
<div><a href="{{ url_for('oauth.'+ oauth +'_login_unlink') }}" id="config_{{ oauth }}_oauth" class="btn btn-primary">{{_('Unlink')}}</a></div>
<div><a href="{{ url_for('oauth.'+ name +'_login_unlink') }}" id="config_{{ id }}_oauth" class="btn btn-primary">{{_('Unlink')}}</a></div>
{% endif %}
{% endfor %}
</div>

@ -180,12 +180,14 @@ class User(UserBase, Base):
default_language = Column(String(3), default="all")
mature_content = Column(Boolean, default=True)
if oauth_support:
class OAuth(OAuthConsumerMixin, Base):
provider_user_id = Column(String(256))
user_id = Column(Integer, ForeignKey(User.id))
user = relationship(User)
class OAuthProvider(Base):
__tablename__ = 'oauthProvider'
@ -194,17 +196,6 @@ class OAuthProvider(Base):
oauth_client_id = Column(String)
oauth_client_secret = Column(String)
active = Column(Boolean)
# scope = relationship('OAuthScope', backref='oauthProvider')
'''class OAuthScope(Base):
__tablename__ = 'oauthScope'
id = Column(Integer, primary_key=True)
scope = Column(String, unique=True)
provider_id = Column(Integer, ForeignKey('oauthProvider.id'))
def __repr__(self):
return u"{0}".format(self.scope)'''
# Class for anonymous user is derived from User base and completly overrides methods and properties for the

@ -42,7 +42,7 @@ try:
from wand.exceptions import PolicyError
use_generic_pdf_cover = False
except (ImportError, RuntimeError) as e:
log.warning('cannot import Image, generating pdf covers for pdf uploads will not work: %s', e)
log.debug('cannot import Image, generating pdf covers for pdf uploads will not work: %s', e)
use_generic_pdf_cover = True
try:
@ -50,21 +50,21 @@ try:
from PyPDF2 import __version__ as PyPdfVersion
use_pdf_meta = True
except ImportError as e:
log.warning('cannot import PyPDF2, extracting pdf metadata will not work: %s', e)
log.debug('cannot import PyPDF2, extracting pdf metadata will not work: %s', e)
use_pdf_meta = False
try:
from . import epub
use_epub_meta = True
except ImportError as e:
log.warning('cannot import epub, extracting epub metadata will not work: %s', e)
log.debug('cannot import epub, extracting epub metadata will not work: %s', e)
use_epub_meta = False
try:
from . import fb2
use_fb2_meta = True
except ImportError as e:
log.warning('cannot import fb2, extracting fb2 metadata will not work: %s', e)
log.debug('cannot import fb2, extracting fb2 metadata will not work: %s', e)
use_fb2_meta = False
try:
@ -72,7 +72,7 @@ try:
from PIL import __version__ as PILversion
use_PIL = True
except ImportError as e:
log.warning('cannot import Pillow, using png and webp images as cover will not work: %s', e)
log.debug('cannot import Pillow, using png and webp images as cover will not work: %s', e)
use_generic_pdf_cover = True
use_PIL = False

Loading…
Cancel
Save