Python flask.session.permanent() Examples

The following are 30 code examples of flask.session.permanent(). 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.session , or try the search function .
Example #1
Source File: dashboard.py    From PowerDNS-Admin with MIT License 17 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #2
Source File: account.py    From restpie3 with MIT License 14 votes vote down vote up
def build_session(user_obj, is_permanent=True):
    """On login+signup, builds the server-side session dict with the data we
    need. userid being the most important."""

    assert user_obj
    assert user_obj.id

    # make sure session is empty
    session.clear()

    # fill with relevant data
    session['userid'] = user_obj.id
    session['role'] = user_obj.role # if you update user.role, update this too

    # remember session even over browser restarts?
    session.permanent = is_permanent

    # could also store ip + browser-agent to verify freshness
    # of the session: only allow most critical operations with a fresh
    # session 
Example #3
Source File: index.py    From PowerDNS-Admin with MIT License 12 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #4
Source File: login.py    From easywall with GNU General Public License v3.0 11 votes vote down vote up
def login_post():
    """
    the function handles the login post request and if all information are correct
    a session variable is set to store the login information
    """
    utils = Webutils()
    hostname = platform.node().encode("utf-8")
    salt = hashlib.sha512(hostname).hexdigest()
    pw_hash = hashlib.sha512(
        str(salt + request.form['password']).encode("utf-8")).hexdigest()
    if request.form['username'] == utils.cfg.get_value(
            "WEB", "username") and pw_hash == utils.cfg.get_value(
                "WEB", "password"):
        session.clear()
        session['logged_in'] = True
        session['ip_address'] = request.remote_addr
        session.permanent = True
        return redirect("/")
    return login("Incorrect username or password.", "danger") 
Example #5
Source File: oauth.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 10 votes vote down vote up
def setup_session(url: str) -> None:
    discord = make_session(state=session.get('oauth2_state'))
    token = discord.fetch_token(
        TOKEN_URL,
        client_secret=OAUTH2_CLIENT_SECRET,
        authorization_response=url)
    session.permanent = True
    session['oauth2_token'] = token
    discord = make_session(token=session.get('oauth2_token'))
    user = discord.get(API_BASE_URL + '/users/@me').json()
    session['id'] = user['id']
    session['discord_id'] = user['id']
    session['discord_locale'] = user['locale']
    guilds = discord.get(API_BASE_URL + '/users/@me/guilds').json()
    wrong_guilds = False # protect against an unexpected response from discord
    session['in_guild'] = False
    session['admin'] = False
    session['demimod'] = False
    for guild in guilds:
        if isinstance(guild, dict) and 'id' in guild:
            if guild['id'] == configuration.get('guild_id'):
                session['admin'] = (guild['permissions'] & 0x10000000) != 0 # Check for the MANAGE_ROLES permissions on Discord as a proxy for "is admin".
                session['demimod'] = (guild['permissions'] & 0x20000) != 0 # Check for the "Mention @everyone" permissions on Discord as a proxy for "is demimod".
                session['in_guild'] = True
        else:
            wrong_guilds = True
    if wrong_guilds:
        logger.warning('auth.py: unexpected discord response. Guilds: {g}'.format(g=guilds)) 
Example #6
Source File: domain.py    From PowerDNS-Admin with MIT License 10 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #7
Source File: common.py    From quay with Apache License 2.0 10 votes vote down vote up
def common_login(user_uuid, permanent_session=True):
    """
    Performs login of the given user, with optional non-permanence on the session.

    Returns a tuple with (success, headers to set on success).
    """
    user = model.get_user(user_uuid)
    if user is None:
        return (False, None)

    if login_user(LoginWrappedDBUser(user_uuid)):
        logger.debug("Successfully signed in as user %s with uuid %s", user.username, user_uuid)
        new_identity = QuayDeferredPermissionUser.for_id(user_uuid)
        identity_changed.send(app, identity=new_identity)
        session["login_time"] = datetime.datetime.now()

        if permanent_session and features.PERMANENT_SESSIONS:
            session_timeout_str = app.config.get("SESSION_TIMEOUT", "31d")
            session.permanent = True
            session.permanent_session_lifetime = convert_to_timedelta(session_timeout_str)

        # Force a new CSRF token.
        headers = {}
        headers[QUAY_CSRF_UPDATED_HEADER_NAME] = generate_csrf_token(force=True)
        return (True, headers)

    logger.debug("User could not be logged in, inactive?")
    return (False, None) 
Example #8
Source File: init_session.py    From airflow with Apache License 2.0 9 votes vote down vote up
def init_logout_timeout(app):
    """Add logout user after timeout"""

    def before_request():
        _force_log_out_after = conf.getint('webserver', 'FORCE_LOG_OUT_AFTER', fallback=0)
        if _force_log_out_after > 0:
            flask.session.permanent = True
            app.permanent_session_lifetime = datetime.timedelta(minutes=_force_log_out_after)
            flask.session.modified = True
            flask.g.user = flask_login.current_user

    app.before_request(before_request) 
Example #9
Source File: init_session.py    From airflow with Apache License 2.0 8 votes vote down vote up
def init_permanent_session(app):
    """Make session permanent to allows us to store data"""

    def make_session_permanent():
        flask_session.permanent = True

    app.before_request(make_session_permanent) 
Example #10
Source File: account.py    From Flask-Boost with MIT License 8 votes vote down vote up
def signin_user(user, permenent=True):
    """Sign in user."""
    session.permanent = permenent
    session['user_id'] = user.id 
Example #11
Source File: app.py    From the-example-app.py with MIT License 8 votes vote down vote up
def set_session_permanency():
    session.permanent = True


# Register Markdown engine 
Example #12
Source File: account.py    From learning-python with MIT License 8 votes vote down vote up
def signin_user(user, permenent=True):
    """Sign in user."""
    session.permanent = permenent
    session['user_id'] = user.id 
Example #13
Source File: auth.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 8 votes vote down vote up
def login(p: person.Person) -> None:
    session['logged_person_id'] = p.id
    session['person_id'] = p.id
    session['mtgo_username'] = p.name
    session.permanent = True
    if p.locale != session.get('discord_locale'):
        person.set_locale(p.id, session.get('discord_locale')) 
Example #14
Source File: user_oauth.py    From gitmostwanted.com with MIT License 8 votes vote down vote up
def authorized():
    next_url = url_next() or url_for('/')

    resp = oauth.github.authorize_access_token()
    if resp is None or 'access_token' not in resp:
        return redirect(next_url)

    session.permanent = True
    session['oauth_access_token'] = (resp['access_token'], resp['scope'].split(','))

    result = oauth.github.get('user')
    if result:
        json = result.json()
        user = user_get_or_create(json['id'], json['email'], json['login'])
        session['user_id'] = user.id

    return redirect(next_url) 
Example #15
Source File: views.py    From helix-sandbox with GNU Affero General Public License v3.0 8 votes vote down vote up
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user,remember=True)
            session.permanent = True
            if user.is_admin:
                return redirect(url_for('home.admin_dashboard'))
            else:
                return redirect(url_for('home.dashboard'))
        else:
            flash('Invalid username or password.')
    return render_template('auth/login.html', form=form, title='Login') 
Example #16
Source File: user.py    From picoCTF with MIT License 7 votes vote down vote up
def login(username, password):
    """Authenticate a user."""
    user = get_user(name=username, include_pw_hash=True)
    if user is None:
        raise PicoException("Incorrect username.", 401)

    if user["disabled"]:
        raise PicoException("This account has been deleted.", 403)

    if not user["verified"]:
        api.email.send_user_verification_email(username)
        raise PicoException(
            "This account has not been verified yet. An additional email has been sent to {}.".format(
                user["email"]
            ),
            403,
        )

    if confirm_password(password, user["password_hash"]):
        session["uid"] = user["uid"]
        session.permanent = True
    else:
        raise PicoException("Incorrect password", 401) 
Example #17
Source File: web.py    From svviz with MIT License 7 votes vote down vote up
def index():
    if not "last_format" in session:
        session["last_format"] = "svg"
        session.permanent = True

    try:
        variantDescription = str(dataHub.variant).replace("::", " ").replace("-", "–")
        return render_template('index.html',
            samples=list(dataHub.samples.keys()), 
            annotations=dataHub.annotationSets,
            results_table=dataHub.getCounts(),
            insertSizeDistributions=[sample.name for sample in dataHub if sample.insertSizePlot], 
            dotplots=dataHub.dotplots,
            variantDescription=variantDescription)
    except Exception as e:
        logging.error("ERROR:{}".format(e))
        raise 
Example #18
Source File: user.py    From PowerDNS-Admin with MIT License 7 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #19
Source File: user.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def login(self, user):
        session.permanent = True
        session['auth'] = user.uid 
Example #20
Source File: admin.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def before_request():
    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #21
Source File: userauth.py    From confidant with Apache License 2.0 5 votes vote down vote up
def set_expiration(self):
        if settings.PERMANENT_SESSION_LIFETIME:
            session.permanent = True
            now = datetime.datetime.utcnow()
            lifetime = settings.PERMANENT_SESSION_LIFETIME
            expiration = now + datetime.timedelta(seconds=lifetime)
            session['expiration'] = expiration
            # We want the max_expiration initially set, but we don't want it to
            # be extended.
            if not session.get('max_expiration'):
                max_lifetime = settings.MAX_PERMANENT_SESSION_LIFETIME
                if not max_lifetime:
                    max_lifetime = lifetime
                max_expiration = now + datetime.timedelta(seconds=max_lifetime)
                session['max_expiration'] = max_expiration 
Example #22
Source File: app.py    From flask-react-spa with MIT License 5 votes vote down vote up
def configure_app(app, config_object):
    """General application configuration:

    - register the app's config
    - register Jinja extensions
    - register functions to run on before/after request
    """
    # automatically configure a migrations folder for each bundle
    config_object.ALEMBIC['version_locations'] = [
        (bundle._name, os.path.join(PROJECT_ROOT,
                                    bundle.module_name.replace('.', os.sep),
                                    'migrations'))
        for bundle in app.bundles if bundle.has_models
    ]
    app.config.from_object(config_object)

    app.jinja_env.add_extension('jinja2_time.TimeExtension')

    @app.before_request
    def enable_session_timeout():
        session.permanent = True  # set session to use PERMANENT_SESSION_LIFETIME
        session.modified = True   # reset the session timer on every request

    @app.after_request
    def set_csrf_cookie(response):
        if response:
            response.set_cookie('csrf_token', generate_csrf())
        return response 
Example #23
Source File: user.py    From analytics-quarry-web with MIT License 5 votes vote down vote up
def get_user():
    if 'user_id' in session:
        if not hasattr(g, '_user'):
            session.permanent = True
            g._user = g.conn.session.query(User).filter(User.id == session['user_id']).one()
        return g._user
    return None 
Example #24
Source File: app.py    From freshonions-torscraper with GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_session():

    session.permanent = True
    app.permanent_session_lifetime = timedelta(days=365*30)
    if not 'uuid' in session:
    	session['uuid'] = str(uuid.uuid4())
    	g.uuid_is_fresh = True
    else:
    	g.uuid_is_fresh = False
    now = datetime.now()
    
    referrer  = request.headers.get('Referer', '')
    path      = request.path
    full_path = request.full_path
    agent     = request.headers.get('User-Agent', '')

    if agent in BLACKLIST_AGENT or len(agent) < 15:
        g.request_log_id = 0
        return render_template('error.html',code=200,message="Layer 8 error. If you want my data, DON'T SCRAPE (too much cpu load), contact me and I will give it to you"), 200

    with db_session:
    	req_log   = RequestLog( uuid=session['uuid'], 
    							uuid_is_fresh=g.uuid_is_fresh, 
    							created_at=now, 
    							agent=agent,
    							referrer=referrer,
    							path=path,
    							full_path=full_path)
    	flush()
    	g.request_log_id = req_log.id 
Example #25
Source File: auth.py    From zeus with Apache License 2.0 5 votes vote down vote up
def login_user(user_id: str, session=session, current_datetime=None):
    session["uid"] = str(user_id)
    session["expire"] = int(
        (
            (current_datetime or timezone.now())
            + current_app.config["PERMANENT_SESSION_LIFETIME"]
        ).strftime("%s")
    )
    session.permanent = True
    with sentry_sdk.configure_scope() as scope:
        scope.user = {"id": str(user_id)} 
Example #26
Source File: auth.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_user_login(user_info):
    """
    设置用户登录状态
    TODO: 单点登录限制

    :param user_info: dict, 用户资料
    :return:
    """
    # 根据工号获取用户资料, 工号不存在时新增用户(表字段默认值确定新用户状态)
    user = TBUser().replace(
        {'job_number': user_info['job_number'], 'realname': user_info['realname']},
        filter_by={'job_number': user_info['job_number']},
        skip=True
    )
    if user:
        if user.status != 1 or user.role_id <= 0:
            raise MsgException('账号未激活', code=401)

        # 用户权限列表
        role = TBRole.query.get(user.role_id)
        if not role or not role.role_allow:
            raise MsgException('账号未授权', code=401)

        # 登录成功
        login_user(user)
        session['load_user'] = pickle.dumps(user)
        session['role_allow'] = role.role_allow.split(',')
        session['role_deny'] = role.role_deny.split(',')
        session.permanent = True

        event_user_logined.send(log_status=1)

        return True

    raise MsgException('登录失败, 请重试', code=401) 
Example #27
Source File: api.py    From Titan with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_unauthenticated_user():
    session['unauthenticated'] = True
    username = request.form['username']
    guild_id = request.form['guild_id']
    ip_address = get_client_ipaddr()
    username = username.strip()
    if len(username) < 2 or len(username) > 32:
        abort(406)
    if not all(x.isalnum() or x.isspace() or "-" == x or "_" == x for x in username):
        abort(406)
    if not check_guild_existance(guild_id):
        abort(404)
    if not guild_query_unauth_users_bool(guild_id):
        abort(401)
    if guild_unauthcaptcha_enabled(guild_id):
        captcha_response = request.form['captcha_response']
        if not verify_captcha_request(captcha_response, request.remote_addr):
            abort(412)
    final_response = None
    if not checkUserBanned(guild_id, ip_address):
        session['username'] = username
        if 'user_id' not in session or len(str(session["user_id"])) > 4:
            session['user_id'] = random.randint(0,9999)
        user = UnauthenticatedUsers(guild_id, username, session['user_id'], ip_address)
        db.session.add(user)
        key = user.user_key
        if 'user_keys' not in session:
            session['user_keys'] = {guild_id: key}
        else:
            session['user_keys'][guild_id] = key
        session.permanent = False
        status = update_user_status(guild_id, username, key)
        final_response = jsonify(status=status)
    else:
        status = {'banned': True}
        response = jsonify(status=status)
        response.status_code = 403
        final_response = response
    db.session.commit()
    return final_response 
Example #28
Source File: user.py    From Titan with GNU Affero General Public License v3.0 5 votes vote down vote up
def callback():
    state = session.get('oauth2_state')
    if not state or request.values.get('error'):
        return redirect(url_for('user.logout'))
    discord = make_authenticated_session(state=state)
    discord_token = discord.fetch_token(
        token_url,
        client_secret=config['client-secret'],
        authorization_response=request.url)
    if not discord_token:
        return redirect(url_for('user.logout'))
    session['user_keys'] = discord_token
    session['unauthenticated'] = False
    session.permanent = True
    user = get_current_authenticated_user()
    session['user_id'] = int(user['id'])
    session['username'] = user['username']
    session['discriminator'] = user['discriminator']
    session['avatar'] = generate_avatar_url(user['id'], user['avatar'], user['discriminator'])
    session["tokens"] = get_titan_token(session["user_id"])
    if session["tokens"] == -1:
        session["tokens"] = 0
    if session["redirect"]:
        redir = session["redirect"]
        session['redirect'] = None
        return redirect(redir)
    return redirect(url_for("user.dashboard")) 
Example #29
Source File: admin.py    From microblog.pub with GNU Affero General Public License v3.0 4 votes vote down vote up
def admin_login() -> _Response:
    if session.get("logged_in") is True:
        return redirect(url_for("admin.admin_notifications"))

    devices = [doc["device"] for doc in DB.u2f.find()]
    u2f_enabled = True if devices else False
    if request.method == "POST":
        csrf.protect()
        # 1. Check regular password login flow
        pwd = request.form.get("pass")
        if pwd:
            if verify_pass(pwd):
                session.permanent = True
                session["logged_in"] = True
                return redirect(
                    request.args.get("redirect") or url_for("admin.admin_notifications")
                )
            else:
                abort(403)
        # 2. Check for U2F payload, if any
        elif devices:
            resp = json.loads(request.form.get("resp"))  # type: ignore
            try:
                u2f.complete_authentication(session["challenge"], resp)
            except ValueError as exc:
                print("failed", exc)
                abort(403)
                return
            finally:
                session["challenge"] = None

            session.permanent = True
            session["logged_in"] = True
            return redirect(
                request.args.get("redirect") or url_for("admin.admin_notifications")
            )
        else:
            abort(401)

    payload = None
    if devices:
        payload = u2f.begin_authentication(ID, devices)
        session["challenge"] = payload

    return htmlify(
        render_template("login.html", u2f_enabled=u2f_enabled, payload=payload)
    ) 
Example #30
Source File: routing.py    From cmdb with GNU General Public License v2.0 4 votes vote down vote up
def login():
    """
    This route has two purposes. First, it is used by the user
    to login. Second, it is used by the CAS to respond with the
    `ticket` after the user logs in successfully.

    When the user accesses this url, they are redirected to the CAS
    to login. If the login was successful, the CAS will respond to this
    route with the ticket in the url. The ticket is then validated.
    If validation was successful the logged in username is saved in
    the user's session under the key `CAS_USERNAME_SESSION_KEY`.
    """

    cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
    if request.values.get("next"):
        session["next"] = request.values.get("next")

    _service = url_for('cas.login', _external=True, next=session["next"]) \
        if session.get("next") else url_for('cas.login', _external=True)
    redirect_url = create_cas_login_url(
        current_app.config['CAS_SERVER'],
        current_app.config['CAS_LOGIN_ROUTE'],
        _service)

    if 'ticket' in request.args:
        session[cas_token_session_key] = request.args.get('ticket')

    if request.args.get('ticket'):

        if validate(request.args['ticket']):
            redirect_url = session.get("next") or \
                           current_app.config.get("CAS_AFTER_LOGIN")
            username = session.get("CAS_USERNAME")
            user = UserCache.get(username)
            login_user(user)

            session.permanent = True

        else:
            del session[cas_token_session_key]
            redirect_url = create_cas_login_url(
                current_app.config['CAS_SERVER'],
                current_app.config['CAS_LOGIN_ROUTE'],
                url_for('cas.login', _external=True),
                renew=True)
    current_app.logger.info("redirect to: {0}".format(redirect_url))
    return redirect(redirect_url)