Python flask_login.login_user() Examples

The following are 24 code examples of flask_login.login_user(). 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_login , or try the search function .
Example #1
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 #2
Source File: login_signal.py    From web_develop with GNU General Public License v3.0 7 votes vote down vote up
def login():
    if request.method == 'GET':
        return '''
<form action='login' method='POST'>
    <input type='text' name='name' id='name' placeholder='name'></input>
    <input type='password' name='pw' id='pw' placeholder='password'></input>
    <input type='submit' name='submit'></input>
</form>
               '''

    name = request.form.get('name')
    if request.form.get('pw') == password:
        user = User.query.filter_by(name=name).first()
        if not user:
            user = User(name=name)
            db.session.add(user)
            db.session.commit()
        flask_login.login_user(user)
        return redirect(url_for('protected'))

    return 'Bad login' 
Example #3
Source File: auth.py    From github-stats with MIT License 6 votes vote down vote up
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    if user_db.github:
      return flask.redirect(flask.url_for('gh_account', username=user_db.github))
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash('Sorry, but you could not sign in.', category='danger')
  return flask.redirect(flask.url_for('signin')) 
Example #4
Source File: conftest.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def minimal_app(real_database_name, real_populated_database, user_obj):
    "An app without data"
    app = create_app(
        config=dict(
            TESTING=True,
            DEBUG=True,
            MONGO_DBNAME=real_database_name,
            DEBUG_TB_ENABLED=False,
            LOGIN_DISABLED=True,
        )
    )

    @app.route("/auto_login")
    def auto_login():
        log.debug("Got request for auto login for {}".format(user_obj))
        user_inst = LoginUser(user_obj)
        assert login_user(user_inst, remember=True)
        return "ok"

    return app 
Example #5
Source File: conftest.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def app(real_database_name, real_variant_database, user_obj):

    app = create_app(
        config=dict(
            TESTING=True,
            DEBUG=True,
            MONGO_DBNAME=real_database_name,
            DEBUG_TB_ENABLED=False,
            LOGIN_DISABLED=True,
            WTF_CSRF_ENABLED=False,
        )
    )

    @app.route("/auto_login")
    def auto_login():
        log.debug("Got request for auto login for {}".format(user_obj))
        user_inst = LoginUser(user_obj)
        assert login_user(user_inst, remember=True)
        return "ok"

    return app 
Example #6
Source File: start.py    From flask-sqlalchemy-web with MIT License 6 votes vote down vote up
def login():
    if request.method == 'POST':
        logger.debug("login post method")
        username = request.form['username']
        password = request.form['password']

        if username == 'admin' and password == 'admin123':
            user = User()
            flask_login.login_user(user)
            user.id = "admin"
            user.is_authenticated = True
            flask_login.login_user(user)
            session['username'] = username
            session['password'] = password
            resp = make_response(render_template('index.html', name=username))
            resp.set_cookie('username', username)
            # return resp
            return jsonify({'status': '0', 'errmsg': '登录成功!'})
        else:
            # return redirect(url_for('error'))
            return jsonify({'status': '-1', 'errmsg': '用户名或密码错误!'})

    logger.debug("login get method")
    return render_template('login.html') 
Example #7
Source File: flask_ext.py    From quart with MIT License 6 votes vote down vote up
def login():
    if request.method == 'GET':
        return '''
               <form method='POST'>
                <input type='text' name='username' id='username' placeholder='username'></input>
                <input type='password' name='password' id='password' placeholder='password'></input>
                <input type='submit' name='submit'></input>
               </form>
               '''

    username = (await request.form)['username']
    password = (await request.form)['password']
    if username in users and compare_digest(password, users[username]['password']):
        user = User()
        user.id = username
        flask_login.login_user(user)
        return redirect(url_for('protected'))

    return 'Bad login' 
Example #8
Source File: airflow_login.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def login(self, request):
    engine = create_engine(settings.webserver.paperboy_sql, echo=False)
    sm = sessionmaker(bind=engine)

    with sm() as session:
        user = session.query(UserSQL).filter(UserSQL.name == DEFAULT_USERNAME).first()

        if not user:
            user = UserSQL(name=DEFAULT_USERNAME)
        session.merge(user)
        session.commit()
        flask_login.login_user(DefaultUser(user))
        session.commit()
    return redirect(request.args.get("next") or url_for("index")) 
Example #9
Source File: views.py    From flask-blog with MIT License 5 votes vote down vote up
def login_view(self):
        # handle user login
        form = LoginForm(request.form)
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user is not None and user.verify_password(form.password.data):
                login.login_user(user)
            else:
                flash("密码错误")
        if login.current_user.is_authenticated:
            return redirect(url_for('.index'))
        self._template_args['form'] = form
        # self._template_args['link'] = link
        return super(MyAdminIndexView, self).index() 
Example #10
Source File: user_manager__views.py    From Flask-User with MIT License 5 votes vote down vote up
def _do_login_user(self, user, safe_next_url, remember_me=False):
        # User must have been authenticated
        if not user: return self.unauthenticated()

        # Check if user account has been disabled
        if not user.active:
            flash(_('Your account has not been enabled.'), 'error')
            return redirect(url_for('user.login'))

        # Check if user has a confirmed email address
        if self.USER_ENABLE_EMAIL \
                and self.USER_ENABLE_CONFIRM_EMAIL \
                and not current_app.user_manager.USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL \
                and not self.db_manager.user_has_confirmed_email(user):
            url = url_for('user.resend_email_confirmation')
            flash(_('Your email address has not yet been confirmed. Check your email Inbox and Spam folders for the confirmation email or <a href="%(url)s">Re-send confirmation email</a>.', url=url), 'error')
            return redirect(url_for('user.login'))

        # Use Flask-Login to sign in user
        # print('login_user: remember_me=', remember_me)
        login_user(user, remember=remember_me)

        # Send user_logged_in signal
        signals.user_logged_in.send(current_app._get_current_object(), user=user)

        # Flash a system message
        flash(_('You have signed in successfully.'), 'success')

        # Redirect to 'next' URL
        return redirect(safe_next_url)


    # Returns safe URL from query param ``param_name`` if query param exists.
    # Returns url_for(default_endpoint) otherwise. 
Example #11
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def login():
    """Log in an existing user."""
    badge_list = []
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.password_hash is not None and \
                user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            flash('You are now logged in. Welcome back!', 'success')
            return redirect(request.args.get('next') or url_for('main.index'))
        else:
            flash('Invalid email or password.', 'form-error')
    return render_template(
        'account/login.html', form=form, badge_list=badge_list) 
Example #12
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def facebook_authorized():
    resp = facebook.authorized_response()
    if resp is None:
        flash("Failed to log in with facebook.", category="error")
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    session['facebook_token'] = (resp['access_token'], '')
    user_facebook = facebook.get('/me?fields=name,email,id').data

    # Check if user already exists, else update
    user = User.query.filter_by(email=user_facebook["email"]).first()

    if user:
        login_user(user, True)
        flash('You are now logged in. Welcome back!', 'success')
        return redirect(request.args.get('next') or url_for('main.index'))

    else:
        # Create a new local user account for this user
        max_id = db.session.query(db.func.max(User.id)).scalar()
        user = User(
            id=max_id + 1,
            email=user_facebook["email"],
            social_id=user_facebook["id"],
            social_provider="facebook",
            first_name=user_facebook["name"],
            confirmed=True)

        # Save and commit our database models
        db.session.add(user)
        db.session.commit()

        session['user_id'] = user.id
        login_user(user, True)
        flash('You are now logged in. Welcome!', 'success')
        return redirect(request.args.get('next') or url_for('main.index'))

    return False 
Example #13
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def github_authorized():
    resp = github.authorized_response()
    if resp is None or resp.get('access_token') is None:
        flash("Failed to log in with github.", category="error")
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    current_app.logger.info(resp)
    session['github_token'] = (resp['access_token'], '')
    user_github = github.get('user').data

    # Check if user already exists, else update
    user = User.query.filter_by(email=user_github["email"]).first()

    if user:
        login_user(user, True)
        flash('You are now logged in. Welcome back!', 'success')
        return redirect(request.args.get('next') or url_for('main.index'))

    else:
        # Create a new local user account for this user
        max_id = db.session.query(db.func.max(User.id)).scalar()
        user = User(
            id=max_id + 1,
            email=user_github["email"],
            social_id=user_github["id"],
            social_provider="github",
            username=user_github["login"],
            first_name=user_github["name"],
            confirmed=True)

        # Save and commit our database models
        db.session.add(user)
        db.session.commit()

        # session['user_id'] = user.id
        login_user(user, True)
        flash('You are now logged in. Welcome!', 'success')
        return redirect(request.args.get('next') or url_for('main.index')) 
Example #14
Source File: views.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def perform_login(user_dict):
    if login_user(user_dict, remember=True):
        flash("you logged in as: {}".format(user_dict.name), "success")
        next_url = session.pop("next_url", None)
        return redirect(request.args.get("next") or next_url or url_for("cases.index"))
    flash("sorry, you could not log in", "warning")
    return redirect(url_for("public.index")) 
Example #15
Source File: monitor_main.py    From flask-sqlalchemy-web with MIT License 5 votes vote down vote up
def login():
    if request.method == 'POST':
        logger.debug("login post method")
        username = request.form['username']
        password = request.form['password']

        user = monitor_db.get_user_session(username)
        logger.debug('db user id is %s, detail is %s' % (user.username, user))

        next_url = request.args.get("next")
        logger.debug('next is %s' % next_url)

        if password == 'admin123' and username == user.username:
            # set login user
            user = User()
            user.id = username
            flask_login.login_user(user)

            resp = make_response(render_template('index.html', name=username))
            resp.set_cookie('username', username)
            if not is_safe_url(next_url):
                return abort(400)
            return redirect(next_url or url_for('index'))
        else:
            return abort(401)

    logger.debug("login get method")
    return render_template('login.html') 
Example #16
Source File: view.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def dev_login():
    if app.env != 'development':
        abort(403)
    dest = request.form.get('next') or url_for('index')
    user_id = request.form['user_id']
    user = User.query.filter_by(id=user_id).one_or_none()

    flask_login.login_user(user)

    return redirect(dest) 
Example #17
Source File: Role_Manager.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def login_user(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated:
            return login_manager.unauthorized()
        elif (not current_user.is_in_role('user')):
            return login_manager.unauthorized()
        return func(*args, **kwargs)
    return decorated_view 
Example #18
Source File: auth.py    From gae-angular-material-starter with MIT License 5 votes vote down vote up
def signin_user_db(user_db, remember=False):
    """Signs in given user"""
    flask_user_db = FlaskUser(user_db)
    auth_params = flask.session.get('auth-params', {
        'remember': remember,
    })
    flask.session.pop('auth-params', None)
    return login.login_user(flask_user_db, remember=auth_params['remember']) 
Example #19
Source File: views.py    From mini-key-server with MIT License 5 votes vote down vote up
def index():

    form = LoginForm(request.form)

    if request.method == "POST" and form.validate():
        current_app.logger.debug("login form was submitted")
        user = Users.query.filter_by(username=form.username.data).first()
        if user and user.check_password(form.password.data):
            if login_user(user):
                current_app.logger.debug(f"login for {user}")
        else:
            flash("Invalid username or password.", "error")
        return redirect(url_for("frontend.index"))

    return render_template("index.html", form=form, current_user=current_user) 
Example #20
Source File: __init__.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def login_user(user):
        """Signal to the authentication systems that a new user has logged in.

        Handles calling :py:func:`flask_login.login_user` and any other
        related housekeeping functions for you.

        :param user: The user that has been authenticated and is logging in.
        :type user: :py:class:`~models.User`
        """
        flask_login.login_user(user) 
Example #21
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 4 votes vote down vote up
def google_authorized():
    resp = google.authorized_response()
    if resp is None:
        flash("Failed to log in with Google.", category="error")
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    session['google_token'] = (resp['access_token'], '')
    user_google = google.get('userinfo').data

    # Check if user already exists, else update
    user = User.query.filter_by(email=user_google["email"]).first()

    session['google_token'] = (resp['access_token'], '')
    user_google = google.get('userinfo').data

    # Check if user already exists, else update
    user = User.query.filter_by(email=user_google["email"]).first()

    if user:
        login_user(user, True)
        flash('You are now logged in. Welcome back!', 'success')
        return redirect(request.args.get('next') or url_for('main.index'))

    else:
        # Create a new local user account for this user
        max_id = db.session.query(db.func.max(User.id)).scalar()
        user = User(
            id=max_id + 1,
            email=user_google["email"],
            social_id=user_google["id"],
            social_provider="google",
            first_name=user_google["name"],
            confirmed=True)

        # Save and commit our database models
        db.session.add(user)
        db.session.commit()

        session['user_id'] = user.id
        login_user(user, True)
        flash('You are now logged in. Welcome!', 'success')
        return redirect(request.args.get('next') or url_for('main.index'))

    return False 
Example #22
Source File: utils.py    From flask-security with MIT License 4 votes vote down vote up
def login_user(user, remember=None, authn_via=None):
    """Perform the login routine.

    If *SECURITY_TRACKABLE* is used, make sure you commit changes after this
    request (i.e. ``app.security.datastore.commit()``).

    :param user: The user to login
    :param remember: Flag specifying if the remember cookie should be set.
                     Defaults to ``False``
    :param authn_via: A list of strings denoting which mechanism(s) the user
        authenticated with.
        These should be one or more of ["password", "sms", "authenticator", "email"] or
        other 'auto-login' mechanisms.
    """

    if remember is None:
        remember = config_value("DEFAULT_REMEMBER_ME")

    if not _login_user(user, remember):  # pragma: no cover
        return False

    if _security.trackable:
        remote_addr = request.remote_addr or None  # make sure it is None

        old_current_login, new_current_login = (
            user.current_login_at,
            _security.datetime_factory(),
        )
        old_current_ip, new_current_ip = user.current_login_ip, remote_addr

        user.last_login_at = old_current_login or new_current_login
        user.current_login_at = new_current_login
        user.last_login_ip = old_current_ip
        user.current_login_ip = new_current_ip
        user.login_count = user.login_count + 1 if user.login_count else 1

        _datastore.put(user)

    session["fs_cc"] = "set"  # CSRF cookie
    session["fs_paa"] = time.time()  # Primary authentication at - timestamp

    identity_changed.send(
        current_app._get_current_object(), identity=Identity(user.fs_uniquifier)
    )

    user_authenticated.send(
        current_app._get_current_object(), user=user, authn_via=authn_via
    )
    return True 
Example #23
Source File: util.py    From AstroBox with GNU Affero General Public License v3.0 4 votes vote down vote up
def restricted_access(func, apiEnabled=True):
	"""
	If you decorate a view with this, it will ensure that first setup has been
	done for AstroBox's Access Control plus that any conditions of the
	login_required decorator are met. It also allows to login using the masterkey or any
	of the user's apikeys if API access is enabled globally and for the decorated view.

	If AstroBox's Access Control has not been setup yet (indicated by the "firstRun"
	flag from the settings being set to True and the userManager not indicating
	that it's user database has been customized from default), the decorator
	will cause a HTTP 403 status code to be returned by the decorated resource.

	If an API key is provided and it matches a known key, the user will be logged in and
	the view will be called directly. If the provided key doesn't match any known key,
	a HTTP 403 status code will be returned by the decorated resource.

	Otherwise the result of calling login_required will be returned.
	"""
	@wraps(func)
	def decorated_view(*args, **kwargs):
		# if AstroBox hasn't been set up yet, abort
		if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
			return make_response("AstroBox isn't setup yet", 403)

		# if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that
		apikey = getApiKey(request)

		if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None:
			if apikey != octoprint.server.UI_API_KEY:
				if apikey == settings().get(["api", "key"]):
					# master key was used
					user = ApiUser()
				else:
					# user key might have been used
					user = octoprint.server.userManager.findUser(apikey=apikey)

				if user is None:
					return make_response("Invalid API key", 401)

				if login_user(user, remember=False):
					identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
					return func(*args, **kwargs)

			else:
				return func(*args, **kwargs)

		return make_response("Invalid Api Key or API Disabled", 401)

	return decorated_view 
Example #24
Source File: view.py    From osm-wikidata with GNU General Public License v3.0 4 votes vote down vote up
def oauth_callback():
    client_key = app.config['CLIENT_KEY']
    client_secret = app.config['CLIENT_SECRET']

    oauth = OAuth1Session(client_key,
                          client_secret=client_secret,
                          resource_owner_key=session['owner_key'],
                          resource_owner_secret=session['owner_secret'])

    oauth_response = oauth.parse_authorization_response(request.url)
    verifier = oauth_response.get('oauth_verifier')
    access_token_url = 'https://www.openstreetmap.org/oauth/access_token'
    oauth = OAuth1Session(client_key,
                          client_secret=client_secret,
                          resource_owner_key=session['owner_key'],
                          resource_owner_secret=session['owner_secret'],
                          verifier=verifier)

    oauth_tokens = oauth.fetch_access_token(access_token_url)
    session['owner_key'] = oauth_tokens.get('oauth_token')
    session['owner_secret'] = oauth_tokens.get('oauth_token_secret')

    r = oauth.get(osm_api_base + '/user/details')
    info = osm_oauth.parse_userinfo_call(r.content)

    user = User.query.filter_by(osm_id=info['id']).one_or_none()

    if user:
        user.osm_oauth_token = oauth_tokens.get('oauth_token')
        user.osm_oauth_token_secret = oauth_tokens.get('oauth_token_secret')
    else:
        user = User(
            username=info['username'],
            description=info['description'],
            img=info['img'],
            osm_id=info['id'],
            osm_account_created=info['account_created'],
        )
        database.session.add(user)
    database.session.commit()
    flask_login.login_user(user)

    next_page = session.get('next') or url_for('index')
    return redirect(next_page)