Skip to content

Admin

initialize_admin(app)

The initialize_admin function is used to initialize the admin interface. It takes in an app object and initializes the admin interface with a cerulean theme.

Parameters:

Name Type Description Default
app

Access the application instance

required

Returns:

Type Description

The admin object that is created by the init_app function

Source code in admin/admin.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def initialize_admin(app):
    """
    The initialize_admin function is used to initialize the admin interface.
    It takes in an app object and initializes the admin interface with a cerulean theme.

    Args:
        app: Access the application instance

    Returns:
        The admin object that is created by the init_app function

    """
    admin.init_app(app)
    app.config["FLASK_ADMIN_SWATCH"] = "cerulean"

initialize_basicauth(app)

The initialize_basicauth function initializes the Flask app with basic authentication. It sets the username and password from environment variables, which are set in Vercel.

Parameters:

Name Type Description Default
app

Access the flask app instance

required

Returns:

Type Description

The app and the user name and password

Source code in admin/basicauth.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def initialize_basicauth(app):
    """
    The initialize_basicauth function initializes the Flask app with basic authentication.
    It sets the username and password from environment variables, which are set in Vercel.

    Args:
        app: Access the flask app instance

    Returns:
        The app and the user name and password
    """
    basic_auth.init_app(app)
    app.config["BASIC_AUTH_USERNAME"] = os.environ.get("BASIC_AUTH_USERNAME")
    app.config["BASIC_AUTH_PASSWORD"] = os.environ.get("BASIC_AUTH_PASSWORD")

initialize_mail(app)

The initialize_mail function initializes the Flask-Mail extension. It sets up the mail server, port, username and password for sending emails. The default sender is also set to be the email address of MAIL_DEFAULT_SENDER.

Parameters:

Name Type Description Default
app

Access the application instance

required

Returns:

Type Description

A configured flask mail object

Source code in admin/mail.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def initialize_mail(app):
    """
    The initialize_mail function initializes the Flask-Mail extension.
    It sets up the mail server, port, username and password for sending emails.
    The default sender is also set to be the email address of MAIL_DEFAULT_SENDER.

    Args:
        app: Access the application instance

    Returns:
        A configured flask mail object
    """
    mail.init_app(app)
    app.config["MAIL_SERVER"] = os.environ.get("MAIL_SERVER")
    app.config["MAIL_PORT"] = int(os.environ.get("MAIL_PORT"))
    app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
    app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")
    app.config["MAIL_DEFAULT_SENDER"] = os.environ.get("MAIL_DEFAULT_SENDER")
    app.config["MAIL_USE_SSL"] = True

AuthException

Bases: HTTPException

This class inherits from HTTPException and is used to raise an exception when a user is not authenticated.

Source code in admin/mongoview.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class AuthException(HTTPException):
    """This class inherits from HTTPException and is used to raise an exception when a user is not authenticated."""

    def __init__(self, message):
        """
        The __init__ function is the constructor for a class. It is called whenever an instance of a class is created.
        The __init__ function can take arguments, but self (the first one) will always be the instance that has just been created.

        Args:
            self: Represent the instance of the object itself
            message: Display the message to the user

        Returns:
            The response object that is passed into the super function

        """
        super().__init__(
            message,
            Response(
                "You could not be authenticated. Please refresh the page.",
                401,
                {"WWW-Authenticate": 'Basic realm="Login Required"'},
            ),
        )

__init__(message)

The init function is the constructor for a class. It is called whenever an instance of a class is created. The init function can take arguments, but self (the first one) will always be the instance that has just been created.

Parameters:

Name Type Description Default
self

Represent the instance of the object itself

required
message

Display the message to the user

required

Returns:

Type Description

The response object that is passed into the super function

Source code in admin/mongoview.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def __init__(self, message):
    """
    The __init__ function is the constructor for a class. It is called whenever an instance of a class is created.
    The __init__ function can take arguments, but self (the first one) will always be the instance that has just been created.

    Args:
        self: Represent the instance of the object itself
        message: Display the message to the user

    Returns:
        The response object that is passed into the super function

    """
    super().__init__(
        message,
        Response(
            "You could not be authenticated. Please refresh the page.",
            401,
            {"WWW-Authenticate": 'Basic realm="Login Required"'},
        ),
    )

MyAdminIndexView

Bases: AdminIndexView

It's a class that inherits from the AdminIndexView class, and it overrides the index() method

Source code in admin/mongoview.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class MyAdminIndexView(AdminIndexView):
    """It's a class that inherits from the AdminIndexView class, and it overrides the index() method"""

    def is_accessible(self):
        """
        The is_accessible function is used to check if the user has logged in.
        If they have not, then they are redirected to the login page. If they have,
        then we return True and move on.

        Args:
            self: Access the attributes and methods of the class in python

        Returns:
            True if the user is authenticated and false otherwise

        Doc Author:
            Trelent
        """
        if not basic_auth.authenticate():
            raise AuthException("Not authenticated.")
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
        """
        The inaccessible_callback function is called when a user attempts to access an endpoint that requires authentication.
        It redirects the user to the login page, and provides them with a message explaining why they were denied access.

        Args:
            self: Access the class attributes
            name: Set the name of the view that will be called if a user is not logged in
            **kwargs: Pass keyworded variable length of arguments to a function

        Returns:
            A redirect to the login page

        Doc Author:
            Trelent
        """
        return redirect(basic_auth.challenge())

inaccessible_callback(name, **kwargs)

The inaccessible_callback function is called when a user attempts to access an endpoint that requires authentication. It redirects the user to the login page, and provides them with a message explaining why they were denied access.

Parameters:

Name Type Description Default
self

Access the class attributes

required
name

Set the name of the view that will be called if a user is not logged in

required
**kwargs

Pass keyworded variable length of arguments to a function

{}

Returns:

Type Description

A redirect to the login page

Doc Author

Trelent

Source code in admin/mongoview.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def inaccessible_callback(self, name, **kwargs):
    """
    The inaccessible_callback function is called when a user attempts to access an endpoint that requires authentication.
    It redirects the user to the login page, and provides them with a message explaining why they were denied access.

    Args:
        self: Access the class attributes
        name: Set the name of the view that will be called if a user is not logged in
        **kwargs: Pass keyworded variable length of arguments to a function

    Returns:
        A redirect to the login page

    Doc Author:
        Trelent
    """
    return redirect(basic_auth.challenge())

is_accessible()

The is_accessible function is used to check if the user has logged in. If they have not, then they are redirected to the login page. If they have, then we return True and move on.

Parameters:

Name Type Description Default
self

Access the attributes and methods of the class in python

required

Returns:

Type Description

True if the user is authenticated and false otherwise

Doc Author

Trelent

Source code in admin/mongoview.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def is_accessible(self):
    """
    The is_accessible function is used to check if the user has logged in.
    If they have not, then they are redirected to the login page. If they have,
    then we return True and move on.

    Args:
        self: Access the attributes and methods of the class in python

    Returns:
        True if the user is authenticated and false otherwise

    Doc Author:
        Trelent
    """
    if not basic_auth.authenticate():
        raise AuthException("Not authenticated.")
    else:
        return True

MyModelView

Bases: ModelView

This class is a subclass of ModelView that is used to create, read, update, and delete (CRUD) records in the database

Source code in admin/mongoview.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class MyModelView(ModelView):
    """This class is a subclass of `ModelView` that is used to create, read, update, and delete (CRUD) records in the
    database"""

    def is_accessible(self):
        """
        The is_accessible function is used to check if the user has access to a particular view.
        It is called automatically by Flask-Login and will return True if the user can access a page,
        or False otherwise. This function will be passed into every view as an @login_required decorator.

        Args:
            self: Access the attributes and methods of the class in python

        Returns:
            True if the user is authenticated

        Doc Author:
            Trelent
        """
        if not basic_auth.authenticate():
            raise AuthException("Not authenticated.")
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
        """
        The inaccessible_callback function is called when a user attempts to access a resource that they are not authorized for.
        It redirects the user to the login page, and provides them with an error message explaining why they were denied access.

        Args:
            self: Access the class instance
            name: Set the name of the view that is used for authentication
            **kwargs: Pass in any additional keyword arguments that are passed to the callback function

        Returns:
            A redirect to the login page

        Doc Author:
            Trelent
        """
        return redirect(basic_auth.challenge())

inaccessible_callback(name, **kwargs)

The inaccessible_callback function is called when a user attempts to access a resource that they are not authorized for. It redirects the user to the login page, and provides them with an error message explaining why they were denied access.

Parameters:

Name Type Description Default
self

Access the class instance

required
name

Set the name of the view that is used for authentication

required
**kwargs

Pass in any additional keyword arguments that are passed to the callback function

{}

Returns:

Type Description

A redirect to the login page

Doc Author

Trelent

Source code in admin/mongoview.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def inaccessible_callback(self, name, **kwargs):
    """
    The inaccessible_callback function is called when a user attempts to access a resource that they are not authorized for.
    It redirects the user to the login page, and provides them with an error message explaining why they were denied access.

    Args:
        self: Access the class instance
        name: Set the name of the view that is used for authentication
        **kwargs: Pass in any additional keyword arguments that are passed to the callback function

    Returns:
        A redirect to the login page

    Doc Author:
        Trelent
    """
    return redirect(basic_auth.challenge())

is_accessible()

The is_accessible function is used to check if the user has access to a particular view. It is called automatically by Flask-Login and will return True if the user can access a page, or False otherwise. This function will be passed into every view as an @login_required decorator.

Parameters:

Name Type Description Default
self

Access the attributes and methods of the class in python

required

Returns:

Type Description

True if the user is authenticated

Doc Author

Trelent

Source code in admin/mongoview.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def is_accessible(self):
    """
    The is_accessible function is used to check if the user has access to a particular view.
    It is called automatically by Flask-Login and will return True if the user can access a page,
    or False otherwise. This function will be passed into every view as an @login_required decorator.

    Args:
        self: Access the attributes and methods of the class in python

    Returns:
        True if the user is authenticated

    Doc Author:
        Trelent
    """
    if not basic_auth.authenticate():
        raise AuthException("Not authenticated.")
    else:
        return True

initialize_views()

The initialize_views function registers the admin views for the flask-admin extension. It is called in init.py, and therefore runs whenever this package is imported.

Returns:

Type Description

The admin object

Doc Author

Trelent

Source code in admin/views.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def initialize_views():
    """
    The initialize_views function registers the admin views for the flask-admin extension.
    It is called in __init__.py, and therefore runs whenever this package is imported.

    Args:

    Returns:
        The admin object

    Doc Author:
        Trelent
    """
    admin.add_view(MyModelView(User))
    admin.add_view(MyModelView(Snippet))
    admin.add_view(MyModelView(Collection))
    admin.add_view(MyModelView(TokenBlocklist))