コード例 #1
0
def newboard():
    # If GET, simply render page.
    if request.method == 'GET':
        verify_jwt_in_request_optional()
        username = get_jwt_identity()
        if username and 'current_user' in session:
            return render_template('newboard.html',
                                   current_user=session['current_user']), 200
        else:
            return render_template('newboard.html'), 200
    # If POST, fetch and verify the post data
    post_data = request.form.to_dict()
    board_name = post_data['board_name']
    board_topic = post_data['board_topic']
    # Create a new board
    board_key = generate_board_key()
    message_boards[board_name] = {
        'messages': [],
        'board_topic': [board_topic],
        'key': [board_key],
        'members': [session['current_user']]
    }
    # Add access to user who created the board
    current_user = session['current_user']
    current_user_email = get_email_from_username(current_user)
    user_database[current_user_email]['boards'].append(board_key)
    return redirect(app.config['BASE_URL'] + '/messages', 302)
コード例 #2
0
 def get_identity_if_logedin(self):
     try:
         verify_jwt_in_request_optional()
         return get_jwt_identity()
     except Exception:
         # this handles if the access tocken is wrong or expired, hence have to handle:-
         pass
コード例 #3
0
ファイル: auth_jwt_utils.py プロジェクト: megamcloud/arrplat
 def wrapper(*args, **kwargs):
     verify_jwt_in_request_optional()
     if get_jwt_identity():
         user = User.query.filter_by(id=get_jwt_identity(),
                                     is_able=1).first()
         if not user:
             return {"msg": "无权限访问"}, 403
     return add_old_token_to_blacklist(fn)(*args, **kwargs)
コード例 #4
0
 def func_wrapper(obj, *args, **kwargs):
     verify_jwt_in_request_optional()
     auth = request.authorization
     if get_jwt_identity() or auth and obj.check_auth(
             auth.username, auth.password):
         return func(obj, *args, **kwargs)
     else:
         return jsonify({"error": "Unauthorized"}), 401
コード例 #5
0
def auth_username():
    from flask_jwt_extended import verify_jwt_in_request_optional, \
        get_jwt_identity

    try:
        verify_jwt_in_request_optional()
        username = get_jwt_identity()
        return username
    except Exception:
        return None
コード例 #6
0
 def wrapper(*args, **kwargs):
     verify_jwt_in_request_optional()
     user_id = get_jwt_identity()
     if user_id:
         model = User(g.mongo_cur)
         user_info = model.find_one(user_id)
         if not user_info:
             return {"msg": "Bad Access Token"}, 401
         g.user = user_info
     result = func(*args, **kwargs)
     return result
コード例 #7
0
ファイル: utils.py プロジェクト: xcodinas/covidcore
 def wrapper(*args, **kwargs):
     if (request.headers.get('Authorization')
             and 'Bearer ' in request.headers.get('Authorization')
             and decode_token(
                 request.headers.get('Authorization')[7:]).get('type')
             == 'refresh'):
         return
     verify_jwt_in_request_optional()
     current_user = User.query.filter_by(id=get_jwt_identity()).first()
     if not current_user.is_expert:
         return abort(422, message='Permissions needed')
     return func(*args, **kwargs)
コード例 #8
0
ファイル: utils.py プロジェクト: xcodinas/covidcore
 def wrapper(*args, **kwargs):
     if (request.headers.get('Authorization')
             and 'Bearer ' in request.headers.get('Authorization')
             and decode_token(
                 request.headers.get('Authorization')[7:]).get('type')
             == 'refresh'):
         return
     verify_jwt_in_request_optional()
     current_user = User.query.filter_by(id=get_jwt_identity()).first()
     if not current_user:
         return
     return func(current_user)
コード例 #9
0
ファイル: my_app.py プロジェクト: britaxx/sample_flask_app
def protected():
    verify_jwt_in_request_optional()
    if get_jwt_identity():
        raw_jwt = get_raw_jwt()
        # print ("raw_jwt {}".format(json.dumps(raw_jwt)))
        ## Upload New Images
        form = PhotoForm()
        if form.validate_on_submit():
            # note for futur to transform .gif into .mov or mp4
            file = form.photo.data
            if allowed_file(file.filename,
                            current_app.config['ALLOWED_EXTENSIONS']):
                output = upload_file_to_s3(file,
                                           current_app.config["S3_BUCKET"])
            else:
                form.photo.errors.append(
                    'File is not supported, only {}'.format(
                        current_app.config['ALLOWED_EXTENSIONS']))
        ## Get photos
        photos = get_photos(current_app.config['S3_BUCKET'])
        # print ("Photos {}".format(json.dumps(photos)))
        return render_template("protected.html",
                               user=raw_jwt['username'],
                               photos=photos,
                               form=form)
    else:
        return redirect(aws_auth.get_sign_in_url())


# def login_required(f):
#     @wraps(f)
#     def wrap(*args, **kwargs):
#         # if user is not logged in, redirect to login page
#         if not request.headers["authorization"]:
#             return redirect("login page")
#         # get user via some ORM system
#         user = User.get(request.headers["authorization"])
#         # make user available down the pipeline via flask.g
#         g.user = user
#         # finally call f. f() now haves access to g.user
#         return f(*args, **kwargs)

#     return wrap

# @api.route("/secret")
# @jwt_required
# def protected():
#     return "Secret Info", 200
コード例 #10
0
def get_current_user():
    from app.models import AnonymousUser, User
    from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request_optional

    try:
        verify_jwt_in_request_optional()
    except Exception as e:
        print(e)
        return AnonymousUser()

    identity = get_jwt_identity()
    if identity is None:
        user = AnonymousUser()
    else:
        user = User.query.filter(User.email == identity).first()
        if user is None:
            user = AnonymousUser()

    return user
コード例 #11
0
ファイル: __init__.py プロジェクト: Boccca2014/CodeGra.de
def _create_logger(set_user: bool) -> None:
    g.request_start_time = DatetimeWithTimezone.utcnow()

    g.request_id = uuid.uuid4()
    log = logger.new(
        request_id=str(g.request_id),
        path=request.path,
        view=getattr(request.url_rule, 'rule', None),
        base_url=flask.current_app.config.get('EXTERNAL_URL'),
    )

    if set_user:
        flask_jwt.verify_jwt_in_request_optional()
        log.bind(current_user=flask_jwt.current_user
                 and flask_jwt.current_user.username)

    func = log.info
    try:
        start = DatetimeWithTimezone.utcfromtimestamp(
            float(request.headers['X-Request-Start-Time']))
        wait_time = (g.request_start_time - start).total_seconds()
        if wait_time > 5:
            func = log.error
        if wait_time > 1:
            func = log.warning
        log.bind(time_spend_in_queue=wait_time)
    except:  # pylint: disable=bare-except
        pass

    try:
        func(
            "Request started",
            host=request.host_url,
            method=request.method,
            query_args={
                k: '<PASSWORD>' if k == 'password' else v
                for k, v in request.args.items()
            },
        )
    finally:
        log.try_unbind('time_spend_in_queue')
コード例 #12
0
def get_platform_user():
    """this allows us to have the correct type of user methods
    available here in the main controller"""
    g.user = None
    try:
        user = None    
        verify_jwt_in_request_optional()
        user = get_current_user()
        if not user:
            raise Exception('JWT missing from request')

        # this requires all authenticated requests
        # come from the browser and not from nuxt server
        if str(user.id) != session.get('user_id'):
            raise Exception('XSS Protection session missing')

        g.user = user
    except Exception as e:
        if request.method != 'OPTIONS':
            current_app.logger.error('ERROR on Before Request: {} {} {}'.format(
                request.method, request.path, e))
コード例 #13
0
    def start_session(self):

        # we add a unique request id to the request enviroment
        # so we can trace individual requests in the logging

        request.environ["REQUEST_ID"] = str(uuid4())
        request.environ["REQUEST_START_TIMESTAMP"] = datetime.now()

        # extract the username if request is authorized
        try:
            verify_jwt_in_request_optional()
            identity = get_jwt_identity()
            if identity:
                log.debug(
                    "start_session: request session identity is %r",
                    identity["username"],
                )
        except (
            NoAuthorizationError,
            ExpiredSignatureError,
            InvalidSignatureError,
            CSRFError,
        ) as e:
            # We do not need to do anything, authorization is checked in BaseController::jwt_check
            log.debug(
                "start_session: Unauthorized request, "
                "no request session identity set %r",
                e,
            )
        except RevokedTokenError as e:
            log.error(
                "%r : \n"
                "An already revoked jwt token was used to access a jwt protected method.\n"
                "This can be a user who saved a token and reused it, or an attacker "
                "using a stolen jwt token",
                e,
            )

        self.create_context(request, request.environ)
コード例 #14
0
    def get(self):
        import pdb
        pdb.set_trace()
        current_user = get_jwt_identity()
        jwt_data = _decode_jwt_from_request(request_type='access')

        cookies = ""  #_decode_jwt_from_request(request_type='cookies')
        query_string = ""  # _decode_jwt_from_request(request_type='query_string')
        headers = ""  #_decode_jwt_from_request(request_type='headers')
        json = ""  #_decode_jwt_from_request(request_type='json')

        test = verify_jwt_in_request()
        test2 = verify_jwt_in_request_optional()
        # test3 = _encode_key_loader()
        return {
            'Welcome': jwt_data,
            'verify_jwt_in_request': test,
            'verify_jwt_in_request_optional': test2,
            'cookies': cookies,
            'query_string': query_string,
            'headers': headers,
            'json': json,
            'username': username,
            'password': json,
        }


# def custom_validator(view_function):
#     @wraps(view_function)
#     def wrapper(*args, **kwargs):
#         jwt_data = _decode_jwt_from_request(request_type='access')

#         # Do your custom validation here.
#         if (True):
#             authorized = True
#         else:
#             authorized = False

#         if not authorized:
#             raise NoAuthorizationError("Explanation goes here")

#         return view_function(*args, **kwargs)

#     return jwt_required(wrapper)
コード例 #15
0
ファイル: client.py プロジェクト: mateosierens/LVL-site
def get_identity_if_login():
    try:
        verify_jwt_in_request_optional()
        return get_jwt_identity()
    except Exception:
        pass
コード例 #16
0
 def wrapped(*args, **kwargs):
     if not verify_jwt_in_request_optional():
         disconnect()
     else:
         return f(*args, **kwargs)
コード例 #17
0
 def wrapper(*args, **kwargs):
     verify_jwt_in_request_optional()
     current_user = User.query.filter_by(id=get_jwt_identity()).first()
     if not current_user:
         return
     return func(current_user)
コード例 #18
0
def protected():
    verify_jwt_in_request_optional()
    if get_jwt_identity():
        return render_template("secret.html")
    else:
        return redirect(aws_auth.get_sign_in_url())
コード例 #19
0
ファイル: middlewares.py プロジェクト: agasca94/flask-blog
 def inner(*args, **kwargs):
     try:
         verify_jwt_in_request_optional()
     except Exception:
         pass  # Ignore if the request contains an invalid or expired token
     return fn(*args, **kwargs)
コード例 #20
0
 def wrapper(*args, **kwargs):
     flask_jwt_extended.verify_jwt_in_request_optional()
     return fn(*args, **kwargs)
コード例 #21
0
 def wrapped(*args, **kwargs):
     verify_jwt_in_request_optional()
     if current_user is None:
         disconnect()
         return
     return f(*args, **kwargs)
コード例 #22
0
 def wrapper(*args, **kwargs):
     verify_jwt_in_request_optional()
     user_id = get_jwt_identity()
     g.user_id = user_id
     result = func(*args, **kwargs)
     return result
コード例 #23
0
 def wrapper(*args, **kwargs):
     verify_jwt_in_request_optional()
     claims = get_jwt_claims()
     if kwargs.get(url_param) != claims[claim_key]:
         raise UrlJwtMismatch('Route requires access token match url')
     return fnc(*args, **kwargs)