A Python library to simplify Discord OAuth2 authentication with Flask applications
Project description
FlaskDiscordAuth
Read this in English | Читайте на русском
English Documentation
Overview
FlaskDiscordAuth is a Python library designed to simplify Discord OAuth2 authentication integration with Flask applications. It provides an easy way to authenticate users via Discord, obtain their basic information, and protect routes that require authentication.
Installation
pip install FlaskDiscordAuth
Requirements
- Flask
- requests
Basic Usage
Here's a simple example of how to use FlaskDiscordAuth:
from flask import Flask, redirect, url_for, session, request
from FlaskDiscordAuth.discord_auth import DiscordAuth
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Discord configuration settings
CLIENT_ID = 'your_client_id'
CLIENT_SECRET = 'your_client_secret'
REDIRECT_URI = 'http://127.0.0.1:5000/callback'
# Initialize Discord authentication object
discord_auth = DiscordAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
@app.route('/')
def home():
if 'user' in session:
user = session['user']
return f"Hello, {user['username']}!"
return 'Welcome! <a href="/login">Login with Discord</a>'
@app.route('/login')
def login():
return redirect(discord_auth.get_login_url())
@app.route('/callback')
def callback():
code = request.args.get('code')
token_data = discord_auth.get_token(code)
access_token = token_data['access_token']
user_info = discord_auth.get_user_info(access_token)
session['user'] = user_info
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)
Protecting Routes
You can use the provided decorator to protect routes that require authentication:
@app.route('/profile')
@discord_auth.login_required
def profile():
user = session['user']
return f"Profile of {user['username']}"
API Reference
DiscordAuth
DiscordAuth(client_id, client_secret, redirect_uri, scope='identify email')
Creates a new Discord authentication instance.
Parameters:
client_id(str): Your Discord application client IDclient_secret(str): Your Discord application client secretredirect_uri(str): The URI Discord will redirect to after authenticationscope(str, optional): Space-separated list of OAuth2 scopes. Default is 'identify email'
Methods
get_login_url()
Generates the OAuth2 authorization URL for Discord.
Returns:
str: The complete Discord authorization URL
get_token(code)
Exchanges an authorization code for an access token.
Parameters:
code(str): The authorization code received from Discord
Returns:
dict: Token data including access_token, token_type, expires_in, etc.
get_user_info(access_token)
Retrieves Discord user information using the provided access token.
Parameters:
access_token(str): The Discord access token
Returns:
dict: User information including id, username, avatar, email, etc.
login_required(func)
A decorator to protect routes that require Discord authentication.
Parameters:
func: The route function to protect
Returns:
function: A wrapper function that checks if the user is authenticated
Complete Example
For a complete example, see the app_example.py file included with the library.
Русская документация
Обзор
FlaskDiscordAuth - это Python-библиотека, разработанная для упрощения интеграции аутентификации Discord OAuth2 с приложениями Flask. Она предоставляет простой способ аутентификации пользователей через Discord, получения их основной информации и защиты маршрутов, требующих аутентификации.
Установка
pip install FlaskDiscordAuth
Требования
- Flask
- requests
Базовое использование
Вот простой пример использования FlaskDiscordAuth:
from flask import Flask, redirect, url_for, session, request
from FlaskDiscordAuth.discord_auth import DiscordAuth
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Настройки Discord
CLIENT_ID = 'your_client_id'
CLIENT_SECRET = 'your_client_secret'
REDIRECT_URI = 'http://127.0.0.1:5000/callback'
# Инициализируем объект аутентификации Discord
discord_auth = DiscordAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
@app.route('/')
def home():
if 'user' in session:
user = session['user']
return f"Привет, {user['username']}!"
return 'Добро пожаловать! <a href="/login">Войти через Discord</a>'
@app.route('/login')
def login():
return redirect(discord_auth.get_login_url())
@app.route('/callback')
def callback():
code = request.args.get('code')
token_data = discord_auth.get_token(code)
access_token = token_data['access_token']
user_info = discord_auth.get_user_info(access_token)
session['user'] = user_info
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)
Защита маршрутов
Вы можете использовать предоставленный декоратор для защиты маршрутов, требующих аутентификации:
@app.route('/profile')
@discord_auth.login_required
def profile():
user = session['user']
return f"Профиль пользователя {user['username']}"
Справочник по API
DiscordAuth
DiscordAuth(client_id, client_secret, redirect_uri, scope='identify email')
Создает новый экземпляр аутентификации Discord.
Параметры:
client_id(str): ID клиента вашего приложения Discordclient_secret(str): Секретный ключ вашего приложения Discordredirect_uri(str): URI, на который Discord перенаправит после аутентификацииscope(str, опционально): Список областей OAuth2, разделенных пробелами. По умолчанию 'identify email'
Методы
get_login_url()
Генерирует URL авторизации OAuth2 для Discord.
Возвращает:
str: Полный URL для авторизации Discord
get_token(code)
Обменивает код авторизации на токен доступа.
Параметры:
code(str): Код авторизации, полученный от Discord
Возвращает:
dict: Данные токена, включая access_token, token_type, expires_in и т.д.
get_user_info(access_token)
Получает информацию о пользователе Discord, используя предоставленный токен доступа.
Параметры:
access_token(str): Токен доступа Discord
Возвращает:
dict: Информация о пользователе, включая id, username, avatar, email и т.д.
login_required(func)
Декоратор для защиты маршрутов, требующих аутентификации Discord.
Параметры:
func: Функция маршрута для защиты
Возвращает:
function: Функция-обертка, которая проверяет, аутентифицирован ли пользователь
Полный пример
Полный пример использования можно найти в файле app_example.py, включенном в библиотеку.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flaskdiscordauth-0.1.0.tar.gz.
File metadata
- Download URL: flaskdiscordauth-0.1.0.tar.gz
- Upload date:
- Size: 7.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2403167634c633814fbd9a4d523719ac3dd9fb7db567f480cf6c86ff517be6c1
|
|
| MD5 |
f3011bcaf3b0d10923cf95838e391dee
|
|
| BLAKE2b-256 |
fea71893c05d9620853b1824499a7e56b21e4fedd955134612585aa2b275fdcc
|
File details
Details for the file flaskdiscordauth-0.1.0-py3-none-any.whl.
File metadata
- Download URL: flaskdiscordauth-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
50ef4f62e1bc39b0882079045cc07448c7e484f6f9457b880769aca68a07e30c
|
|
| MD5 |
1332af8351783b16270b154a8a053730
|
|
| BLAKE2b-256 |
2982ef4111fd791ccf053652d92c0e69432a8be0626f23bb7bd711dd6cde2c84
|