1 Setup a Password Hash
The solution is to use a Password Hash. Let us see what a hash is, so go to the python shell in the terminal and run the command
We will get a long random string as shown below:
Hence even if the hacker gets access to them, he won’t be able to decrypt. Also, we have another function to compare the Hash with a password, called check_password_hash.
It works as below:
Now hit enter, it will return True if matched and False if unmatched.
2 Adding Hashed Passwords to Your Database
Also if you don’t have FlaskSQLAlchemy, simply install it using the pip command:
Okay, now that SQLAlchemy is in place, create a file models.py and add the code:
Here:
3. Setting the Flask_login Extension
Also, we need to create and initialize the Flask_login extension. We do it using the code:
4. Complete Code
That’s it with the models.py part. Let us just look at the whole code once:
Do check out our SQLAlchemy Article if you are unfamiliar with Flask SQLAlchemy.
Coding our main Flask application file
Now let’s code our main Flask Application File.
1 Linking Database to our Flask File
Okay now we need to link our SQLite database with SQLALchemy. So for that add the code:
Just replace <db_name> with whatever name you want. Also, we need to link our SQLAlchemy DB instance (present in models.py file) with the main app. For that, add:
3 Coding a Simple View
Hence add a simple view:
Note how we have used the @login_required decorator. The blog.html template would be:
Do checkout our Flask Templates article to know more about Templates.
3 Coding the Log-in View
The Login view would be simple. It should do the following:
So add the code:
And the login.html template:
4 Coding the Register View
The Register View should be able to do the following:
So the code will be:
Therefore the register.html page will be:
Basic application structure
For this application, we’ll have a virtual environment in its own directory, as well as a folder containing the main application files. Here’s an overview of the app’s structure:
.├── auth-app│ ├── app.py │ ├── database.db │ ├── forms.py │ ├── manage.py │ ├── migrations│ ├── models.py │ ├── requirements.txt │ ├── routes.py │ ├── run│ ├── static│ └── templates│ ├── auth.html │ ├── base.html │ └── index.html └── venv
Example code
The code discussed in the following sections is available for you to try and hack. You can find it on GitHub: REST-auth. Note that the GitHub repository likely has code that is newer than what I’m going to show in this article. If you want to see the version of the code featured in this article use this link.
Forms.py
a). Registration form
Oauth authentication
When talking about RESTful authentication the OAuth protocol is usually mentioned.
So what is OAuth?
Password hashing
To create the password hashes I’m going to use PassLib, a package dedicated to password hashing.
PassLib provides several hashing algorithms to choose from. The custom_app_context object is an easy to use option based on the sha256_crypt hashing algorithm.
Базовая структура приложения
Для нашего приложения у нас будет виртуальная среда в его собственном каталоге, а также папка, содержащая основные файлы приложения. Структура приложения будет выглядеть следующим образом:
Как изменить routes.py
В Flask добавлять новых пользователей в базу данных очень просто. Чтобы завершить сегодняшнее руководство, нам нужно зарегистрироваться, войти в систему и выйти из нее, то есть управлять сеансами.
Маршрут регистрации
Прежде всего, внимательно изучите приведенный ниже фрагмент кода для регистрации новых пользователей. Тут мы подтверждаем, что форма, отправляющая данные, прошла все проверки. Итак, если form.validate_on_submit():
Настройка и установка приложения
Исчерпывающее руководство по настройке и установке проекта можно найти в репозитории на GitHub.
Создание приложения
Для начала мы создадим функцию — фабрику приложений внутри файла app.py и назовем ее create_app. Это жизненно важно для любого приложения Flask.
Кроме того, нам нужно импортировать некоторые библиотеки для использования в нашем проекте:
Заключение
Вот и все! Мы создали наше приложение с аутентификацией пользователя.
Спасибо за чтение! Мы надеемся, что эта статья была вам полезна.