web_avt / app.py
DmitrMakeev's picture
Update app.py
8f181ec verified
from flask import Flask, request, redirect, session, url_for, abort
import requests
import os
import logging
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
logging.basicConfig(level=logging.INFO)
def get_access_token(code):
try:
client_id = os.getenv('APP_ID')
client_secret = os.getenv('APP_SECRET')
redirect_uri = os.getenv('red_uri')
url = f'https://oauth.vk.com/access_token?client_id={client_id}&client_secret={client_secret}&redirect_uri={redirect_uri}&code={code}'
response = requests.get(url)
response.raise_for_status()
data = response.json()
if 'access_token' in data:
access_token = data['access_token']
user_id = data['user_id']
return access_token, user_id
else:
logging.error("Ошибка при получении access_token: %s", data)
return None, None
except requests.RequestException as e:
logging.error("Ошибка при запросе access_token: %s", e)
return None, None
@app.route('/login')
def login():
code = request.args.get('code')
if code:
access_token, user_id = get_access_token(code)
if access_token and user_id:
session['access_token'] = access_token
session['user_id'] = user_id
return redirect(url_for('protected_route'))
else:
return "Ошибка при получении access_token", 400
else:
return "Код авторизации не найден", 400
def is_authenticated():
return 'access_token' in session and 'user_id' in session
@app.route('/protected')
def protected_route():
if is_authenticated():
user_id = session['user_id']
return f"Добро пожаловать, пользователь с ID {user_id}!"
else:
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))