# LoginManager

## Setup

```python
from flask_login import LoginManager`

login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    user = db_get_user(user_id)
    if not user:
        print("Invalid user id in request. Has this user id been deleted?")
        # returning None deletes the session
        return None

    print("LOAD USER", user.get_id())
    return user

```

User object should implement some functions or inherit from `UserMixin`

## Usage

#### Make Login Required For Routes

`@login_required` decorator will make route reroute to route set by `login_manager.login_view = "users.login"`

### Login

```python
from flask_login import login_user`

login_user(user)
login_user(user, remember=True)#store cookie to remember me
```

#### Logout

```python
@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(somewhere)
```

#### Use current\_user to access

```python
@bp.route("/me", methods=["POST"])
def guess_user():
    if current_user.is_authenticated:
        return jsonify(current_user.as_dict())
```

#### Templates

Make current\_user available in every template

```html

<div data-gb-custom-block data-tag="if">

  Hi {{ current_user.name }}!

</div>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://openai.gitbook.io/code-cheatsheets/all/python/flask/login.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
