Skip to content

Commit

Permalink
rename parameters | Merge pull request #3 from johndou-and-friends/main
Browse files Browse the repository at this point in the history
PR for issue #2
  • Loading branch information
alisharify7 authored Jul 21, 2024
2 parents 160c22b + 9bea2f7 commit 62a1e65
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 32 deletions.
4 changes: 1 addition & 3 deletions flask_captcha2/CaptchaClass.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
# build in
import logging

# lib
from flask import Flask
from markupsafe import Markup

from . import excep as exceptions
# flask-captcha2
from .GoogleCaptcha.captcha2 import FlaskCaptcha2
from .GoogleCaptcha.captcha3 import FlaskCaptcha3
from .Logger import get_logger

from . import excep as exceptions


class FlaskCaptcha:
"""Master FlaskCaptcha Class"""
Expand Down
1 change: 0 additions & 1 deletion flask_captcha2/GoogleCaptcha/captcha2.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# build in
import json
import logging

# lib
import requests
from flask import request, Flask
Expand Down
26 changes: 13 additions & 13 deletions flask_captcha2/GoogleCaptcha/captcha3.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# build in
import json
import logging

# lib
import requests
from flask import request, Flask
Expand All @@ -17,8 +16,8 @@ class BaseCaptcha3(CommonCaptchaUtils):
"""
Base Config for Google Captcha v3 class
"""
PUBLIC_KEY: str = ''
PRIVATE_KEY: str = ''
PUBLIC_KEY: str = ""
PRIVATE_KEY: str = ""
ENABLED: bool = False
SCORE: float = 0.5
MINIMUM_SCORE: float = 0.5 # default minimum score
Expand All @@ -44,7 +43,8 @@ class FlaskCaptcha3(BaseCaptcha3):
"""

def __init__(self, app: Flask = None, CAPTCHA_PUBLIC_KEY: str = None, CAPTCHA_PRIVATE_KEY: str = None, **kwargs):
def __init__(self, app: Flask = None, CAPTCHA_PUBLIC_KEY: str = None, CAPTCHA_PRIVATE_KEY: str = None,
**kwargs) -> None:
if app and isinstance(app, Flask): # app is passed read configs from app.config
self.init_app(app)

Expand All @@ -54,7 +54,7 @@ def __init__(self, app: Flask = None, CAPTCHA_PUBLIC_KEY: str = None, CAPTCHA_PR
kwargs["CAPTCHA_PUBLIC_KEY"] = CAPTCHA_PUBLIC_KEY
self.set_config(kwargs)

def init_app(self, app: Flask = None):
def init_app(self, app: Flask = None) -> None:
if not isinstance(app, Flask):
raise ex.NotFlaskApp(f"{app} object is not a flask instance!")

Expand Down Expand Up @@ -133,25 +133,25 @@ def renderWidget(self, *args, **kwargs) -> Markup:
style: str: style of captcha element
dataset: str: dataset of captcha element
event: str: javascript event of captcha element
BtnText: str: value of input submit button of the form
ParentFormID: str: id of parent for element
hiddenBadge: bool: set visibility of captcha widget in bottom right corner
button_text: str: value of input submit button of the form
parent_form_id: str: id of parent for element
hide_badge: bool: set visibility of captcha widget in bottom right corner
Returns:
captchaFiled: str<Markup>: captcha
captchaFiled: str<Markup>: captcha
"""
arg = ""
arg += f"id=\"{kwargs.get('id')}\" \t" if kwargs.get('id') else '' # id, class internal text
arg += kwargs.get('dataset') + "\t" if kwargs.get('dataset') else '' # dataset
arg += f"style=\"{kwargs.get('style')}\"\t" if kwargs.get('style') else '' # style
arg += f"value=\"{kwargs.get('BtnText', 'Submit')}\"\t" # style
arg += f"value=\"{kwargs.get('button_text', 'Submit')}\"\t" # style
arg += f"{kwargs.get('event', ' ')}" # js event

captchaField = (f"""
{'<style>.grecaptcha-badge {visibility: hidden;}</style>' if kwargs.get("hiddenBadge", "") == True else ''}
{'<style>.grecaptcha-badge {visibility: hidden;}</style>' if kwargs.get("hide_badge", "") == True else ''}
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>function onSubmit(token) {{document.getElementById('{kwargs.get('ParentFormID', '')}').submit();}}</script>
<script>function onSubmit(token) {{document.getElementById('{kwargs.get('parent_form_id', '')}').submit();}}</script>
<input type='submit' class="g-recaptcha {kwargs.get('class', '')}" {arg}
data-sitekey="{self.PUBLIC_KEY}" data-action="submit" data-callback="onSubmit"> </input>
""").strip()
Expand Down
5 changes: 2 additions & 3 deletions flask_captcha2/LocalCaptcha/Image/img.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
import logging
import secrets
import string
from random import SystemRandom

from captcha.image import ImageCaptcha
# libs
from flask import Flask, session
from markupsafe import Markup
from captcha.image import ImageCaptcha
from random import SystemRandom

# flask-captcha2
from flask_captcha2 import excep as ex
Expand Down
18 changes: 14 additions & 4 deletions flask_captcha2/excep.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
class NotFlaskApp(Exception):
"""Custom exception class"""
class BaseFlaskCaptchaException(Exception):
"""Base FlaskCaptcha Exception """
...


class CaptchaNameNotExists(Exception):
"""Custom exception class"""
class NotFlaskApp(BaseFlaskCaptchaException):
"""Custom exception class
this exception raise when an invalid or wrong
app passed in __init__ or init_app function
"""
...


class CaptchaNameNotExists(BaseFlaskCaptchaException):
"""Custom exception class
this exception raise when render_captcha func get wrong model name
"""
...
8 changes: 4 additions & 4 deletions tests/captchaV3/test_google_captcha3.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,25 @@ def test_load_captcha_in_html(client, googlecaptcha3, app, captcha3_template_con
assert f"class=\"g-recaptcha {captcha3_template_conf['class']}\"" in captcha
assert f"{captcha3_template_conf['dataset']}" in captcha
assert f"id=\"{captcha3_template_conf['id']}\"" in captcha
assert f"{captcha3_template_conf['BtnText']}" in captcha
assert f"{captcha3_template_conf['button_text']}" in captcha

# check captcha badge in the eight bottom os the screen in hidden or not
captcha3_template_conf['hiddenBadge'] = True
captcha3_template_conf['hide_badge'] = True
captcha = app.template_context_processors[None][-1]()['captcha'].render_captcha(model_name='flask-captcha-v3',
**captcha3_template_conf)
hidden_badge_style = Markup("<style>.grecaptcha-badge {visibility: hidden;}</style>")
assert hidden_badge_style in captcha


def test_captcha_enable_on(app, googlecaptcha3, client, captcha3_template_conf):
"""if enable is false render_captcha always return " " and
"""if enable is set to false render_captcha always return an empty string " " and
is_verify method always return True
"""

googlecaptcha3.ENABLED = False
captcha = app.template_context_processors[None][-1]()['captcha'].render_captcha(model_name='flask-captcha-v3',
conf=captcha3_template_conf)
assert captcha != Markup(" ") # return default input-type submit
assert captcha != Markup(" ") # return default input-type submit

@app.post("/test-invalid-post/")
def post_invalid():
Expand Down
9 changes: 5 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

"""By default captcha log is False"""


@pytest.fixture()
def app():
"""Main Flask Application fixture"""
Expand Down Expand Up @@ -50,7 +51,6 @@ def googlecaptcha3(app):
'CAPTCHA_ENABLED': True, # captcha enable status
"CAPTCHA_SCORE": 0.5, #
"CAPTCHA_LOG": False,

}
)
Master_captcha = FlaskCaptcha(app=app)
Expand All @@ -69,11 +69,12 @@ def client(app):
def captcha3_template_conf():
"""captcha version3 render_captcha config"""
conf = {
'ParentFormID': 'id-of-parent-form',
'BtnText': 'submit form',
'parent_form_id': 'id-of-parent-form',
'button_text': 'submit form',
'dataset': ' data-check="True" data-another="Checked" ',
'style': 'background-color:"red"',
'id': 'id-of-submit-form',
'class': 'class-of-submit-form'
'class': 'class-of-submit-form',
"CAPTCHA_LOG": False
}
yield conf

0 comments on commit 62a1e65

Please sign in to comment.