Python flask.current_app.secret_key() Examples

The following are 15 code examples of flask.current_app.secret_key(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.current_app , or try the search function .
Example #1
Source File: webui.py    From MPContribs with MIT License 6 votes vote down vote up
def reset_session():
    global session, processes
    current_app.config["JSON_SORT_KEYS"] = False
    current_app.secret_key = "xxxrrr"
    session.clear()
    session["projects"] = projects
    session["options"] = ["archieml"]
    session["contribute"] = {}
    sbx_content = current_app.config.get("SANDBOX_CONTENT")
    if sbx_content is not None:
        session["sbx_content"] = sbx_content
    session["jupyter_url"] = current_app.config.get("JUPYTER_URL")
    if not current_app.config.get("START_JUPYTER") and "NotebookProcess" in processes:
        processes.pop("NotebookProcess")
    if not current_app.config.get("START_MONGODB") and "MongodProcess" in processes:
        processes.pop("MongodProcess")
    stop_processes()
    start_processes()
    for suffix in ["_in.txt", "_out.txt"]:
        filepath = default_mpfile_path.replace(".txt", suffix)
        if os.path.exists(filepath):
            os.remove(filepath) 
Example #2
Source File: api.py    From golem with MIT License 6 votes vote down vote up
def auth_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated:
            token = request.headers.get('token', None)
            if token:
                try:
                    user = Users.verify_auth_token(current_app.secret_key, token)
                    request.api_user = user
                except SignatureExpired:
                    abort(401, 'Signature Expired')
                except BadSignature:
                    abort(401, 'Token did not match')
                except Exception:
                    abort(401, 'Unknown error')
            else:
                abort(400, 'Missing token')
        return func(*args, **kwargs)
    return decorated_view 
Example #3
Source File: context.py    From Flask-Large-Application-Example with MIT License 5 votes vote down vote up
def secret_key(self) -> str:
        return current_app.secret_key

    # - request payload - 
Example #4
Source File: csrf.py    From jbox with MIT License 5 votes vote down vote up
def generate_csrf(secret_key=None, time_limit=None):
    """Generate csrf token code.

    :param secret_key: A secret key for mixing in the token,
                       default is Flask.secret_key.
    :param time_limit: Token valid in the time limit,
                       default is 3600s.
    """
    if not secret_key:
        secret_key = current_app.config.get(
            'WTF_CSRF_SECRET_KEY', current_app.secret_key
        )

    if not secret_key:
        raise Exception('Must provide secret_key to use csrf.')

    if time_limit is None:
        time_limit = current_app.config.get('WTF_CSRF_TIME_LIMIT', 3600)

    if 'csrf_token' not in session:
        session['csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()

    if time_limit:
        expires = int(time.time() + time_limit)
        csrf_build = '%s%s' % (session['csrf_token'], expires)
    else:
        expires = ''
        csrf_build = session['csrf_token']

    hmac_csrf = hmac.new(
        to_bytes(secret_key),
        to_bytes(csrf_build),
        digestmod=hashlib.sha1
    ).hexdigest()
    return '%s##%s' % (expires, hmac_csrf) 
Example #5
Source File: prepolicy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def api_key_required(request=None, action=None):
    """
    This is a decorator for check_user_pass and check_serial_pass.
    It checks, if a policy scope=auth, action=apikeyrequired is set.
    If so, the validate request will only performed, if a JWT token is passed
    with role=validate.
    """
    user_object = request.User

    # Get the policies
    action = Match.user(g, scope=SCOPE.AUTHZ, action=ACTION.APIKEY, user_object=user_object).policies()
    # Do we have a policy?
    if action:
        # check if we were passed a correct JWT
        # Get the Authorization token from the header
        auth_token = request.headers.get('PI-Authorization')
        if not auth_token:
            auth_token = request.headers.get('Authorization')
        try:
            r = jwt.decode(auth_token, current_app.secret_key, algorithms=['HS256'])
            g.logged_in_user = {"username": r.get("username", ""),
                                "realm": r.get("realm", ""),
                                "role": r.get("role", "")}
        except (AttributeError, jwt.DecodeError):
            # PyJWT 1.3.0 raises AttributeError, PyJWT 1.6.4 raises DecodeError.
            raise PolicyError("No valid API key was passed.")

        role = g.logged_in_user.get("role")
        if role != ROLE.VALIDATE:
            raise PolicyError("A correct JWT was passed, but it was no API "
                              "key.")

    # If everything went fine, we call the original function
    return True 
Example #6
Source File: form.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def csrf_secret(self):
            return current_app.config.get(
                'WTF_CSRF_SECRET_KEY', current_app.secret_key
            ) 
Example #7
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def generate_csrf(secret_key=None, token_key=None):
    """Generate a CSRF token. The token is cached for a request, so multiple
    calls to this function will generate the same token.

    During testing, it might be useful to access the signed token in
    ``g.csrf_token`` and the raw token in ``session['csrf_token']``.

    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param token_key: Key where token is stored in session for comparision.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
    """

    secret_key = _get_config(
        secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
        message='A secret key is required to use CSRF.'
    )
    field_name = _get_config(
        token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
        message='A field name is required to use CSRF.'
    )

    if field_name not in g:
        if field_name not in session:
            session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()

        s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')
        setattr(g, field_name, s.dumps(session[field_name]))

    return g.get(field_name) 
Example #8
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def generate_csrf_token(self, csrf_token_field):
        return generate_csrf(
            secret_key=self.meta.csrf_secret,
            token_key=self.meta.csrf_field_name
        ) 
Example #9
Source File: auth.py    From zeus with Apache License 2.0 5 votes vote down vote up
def generate_token(tenant: Tenant) -> bytes:
    s = JSONWebSignatureSerializer(current_app.secret_key, salt="auth")
    payload: Dict[str, Any] = {
        "access": {str(k): int(v) if v else None for k, v in tenant.access.items()}
    }
    if getattr(tenant, "user_id", None):
        payload["uid"] = str(tenant.user_id)
    return s.dumps(payload) 
Example #10
Source File: auth.py    From zeus with Apache License 2.0 5 votes vote down vote up
def parse_token(token: str) -> Optional[Any]:
    s = JSONWebSignatureSerializer(current_app.secret_key, salt="auth")
    try:
        return s.loads(token)

    except BadSignature:
        return None 
Example #11
Source File: auth.py    From flask-restaction with MIT License 5 votes vote down vote up
def decode_token(self, token):
        """Decode Authorization token, return None if token invalid"""
        key = current_app.secret_key
        if key is None:
            if current_app.debug:
                current_app.logger.debug("app.secret_key not set")
            return None
        try:
            return jwt.decode(
                token, key,
                algorithms=[self.config["algorithm"]],
                options={'require_exp': True}
            )
        except jwt.InvalidTokenError:
            return None 
Example #12
Source File: auth.py    From flask-restaction with MIT License 5 votes vote down vote up
def encode_token(self, token):
        """Encode Authorization token, return bytes token"""
        key = current_app.secret_key
        if key is None:
            raise RuntimeError(
                "please set app.secret_key before generate token")
        return jwt.encode(token, key, algorithm=self.config["algorithm"]) 
Example #13
Source File: api.py    From golem with MIT License 5 votes vote down vote up
def auth_token():
    username = request.json['username']
    password = request.json['password']
    user = Users.get_user_by_username(username=username)
    if user is None:
        abort(401, 'User does not exist')
    elif not user.verify_password(password):
        abort(401, 'Incorrect password')
    else:
        token = user.generate_auth_token(current_app.secret_key, expiration=3600)
        return jsonify(token.decode()) 
Example #14
Source File: csrf.py    From jbox with MIT License 4 votes vote down vote up
def validate_csrf(data, secret_key=None, time_limit=None):
    """Check if the given data is a valid csrf token.

    :param data: The csrf token value to be checked.
    :param secret_key: A secret key for mixing in the token,
                       default is Flask.secret_key.
    :param time_limit: Check if the csrf token is expired.
                       default is True.
    """
    if not data or '##' not in data:
        return False

    try:
        expires, hmac_csrf = data.split('##', 1)
    except ValueError:
        return False  # unpack error

    if time_limit is None:
        time_limit = current_app.config.get('WTF_CSRF_TIME_LIMIT', 3600)

    if time_limit:
        try:
            expires = int(expires)
        except ValueError:
            return False

        now = int(time.time())
        if now > expires:
            return False

    if not secret_key:
        secret_key = current_app.config.get(
            'WTF_CSRF_SECRET_KEY', current_app.secret_key
        )

    if 'csrf_token' not in session:
        return False

    csrf_build = '%s%s' % (session['csrf_token'], expires)
    hmac_compare = hmac.new(
        to_bytes(secret_key),
        to_bytes(csrf_build),
        digestmod=hashlib.sha1
    ).hexdigest()

    return safe_str_cmp(hmac_compare, hmac_csrf) 
Example #15
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 4 votes vote down vote up
def validate_csrf(data, secret_key=None, time_limit=None, token_key=None):
    """Check if the given data is a valid CSRF token. This compares the given
    signed token to the one stored in the session.

    :param data: The signed CSRF token to be checked.
    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param time_limit: Number of seconds that the token is valid. Default is
        ``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes).
    :param token_key: Key where token is stored in session for comparision.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.

    :raises ValidationError: Contains the reason that validation failed.

    .. versionchanged:: 0.14
        Raises ``ValidationError`` with a specific error message rather than
        returning ``True`` or ``False``.
    """

    secret_key = _get_config(
        secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
        message='A secret key is required to use CSRF.'
    )
    field_name = _get_config(
        token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
        message='A field name is required to use CSRF.'
    )
    time_limit = _get_config(
        time_limit, 'WTF_CSRF_TIME_LIMIT', 3600, required=False
    )

    if not data:
        raise ValidationError('The CSRF token is missing.')

    if field_name not in session:
        raise ValidationError('The CSRF session token is missing.')

    s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')

    try:
        token = s.loads(data, max_age=time_limit)
    except SignatureExpired:
        raise ValidationError('The CSRF token has expired.')
    except BadData:
        raise ValidationError('The CSRF token is invalid.')

    if not safe_str_cmp(session[field_name], token):
        raise ValidationError('The CSRF tokens do not match.')