File size: 2,014 Bytes
8f181ec
2920ac3
af56c3a
8f181ec
af56c3a
3f2b61a
8f181ec
 
2920ac3
 
8f181ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2920ac3
 
 
 
 
 
 
 
 
 
24df65d
2920ac3
 
 
 
af56c3a
24df65d
 
 
 
 
 
 
 
 
 
 
f18f04b
2920ac3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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)))