hw_oauth/app.py

73 lines
2.4 KiB
Python

import time
from website import create_app
from flask_script import Manager, Shell
from flask_migrate import MigrateCommand
from werkzeug.security import gen_salt
import os
app = create_app(os.getenv('FLASK_ENV') or 'config.DevelopementConfig')
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def init_db():
from website.models import db
db.create_all()
print("database init")
@manager.command
def test_data():
from website.models import db, User, OAuth2Client
print("add test data")
admin = User()
admin.name = "Admin"
admin.username = "admin"
admin.email = "test@example.com"
admin.set_password("admin")
db.session.add(admin)
db.session.commit()
print('added user: {}'.format(admin))
client_id = gen_salt(24)
client_id_issued_at = int(time.time())
client = OAuth2Client(
client_id=client_id,
client_id_issued_at=client_id_issued_at,
user_id=admin.get_id(),
)
client_metadata = {
"client_name": "Test client",
"client_uri": "https://social.yandex.net",
"grant_types": ['authorization_code', 'refresh_token'],
"redirect_uris": "https://social.yandex.net/broker/redirect",
"response_types": ['code', 'token'],
"scope": 'profile',
"token_endpoint_auth_method": 'client_secret_post'
}
client.set_client_metadata(client_metadata)
client.client_secret = gen_salt(48)
db.session.add(client)
db.session.commit()
print('added client: id:{}, secret:{}'.format(client_id, client.client_secret))
print('test url: http://127.0.0.1:5000/oauth/authorize?scope=profile&response_type=code&client_id={}'.format(client_id))
if __name__ == '__main__':
manager.run()
# http://127.0.0.1:5000/oauth/authorize?scope=profile&response_type=code&client_id=rrC8VDll9RRbBjNLhY4T9jDO
# > curl -XPOST "http://127.0.0.1:5000/oauth/token" -F client_id=rrC8VDll9RRbBjNLhY4T9jDO -F client_secret=CxKyWG8Z972hkLQq7hMblH7BsP4JWtQn7qahqzW15h5ZUUJI -F grant_type=authorization_code -F code=wur5zaxmDfxK9Qsvvebqz1N0XKa7zewSrNYJJAYHlZGfsOJa
# < {"access_token": "LBdvuoKeiY9tHJKMoLdvrG8Zfqs4FbPOz1ze0Ahv96", "expires_in": 864000, "scope": "profile", "token_type": "Bearer"}
# > curl -H "Authorization: Bearer LBdvuoKeiY9tHJKMoLdvrG8Zfqs4FbPOz1ze0Ahv96" "http://127.0.0.1:5000/api/me"
# {
# "id": 1,
# "username": "admin"
# }