Skip to content

Instantly share code, notes, and snippets.

@YuzuRyo61
Last active February 23, 2018 13:03
Show Gist options
  • Save YuzuRyo61/878849ae889788cb2ead0854d9e5bca0 to your computer and use it in GitHub Desktop.
Save YuzuRyo61/878849ae889788cb2ead0854d9e5bca0 to your computer and use it in GitHub Desktop.
Mastodon.pyにはOAuth機能が搭載されていないので自作。一部拝借したところもあり。
"""
もしかしたらいらないライブラリがあるかもしれません。その場合は適宜外してもらっても構いません。
参考文献:
- https://qiita.com/civic/items/7358dc1c54ff8e71c326
- https://github.com/civic/mastodon-auth-example/blob/master/mastodon_auth_example.py
"""
from urllib.parse import urlencode
import requests,json,os,re
class mstdnoauth:
def getauthurl(self, address, client, scope_i):
"""
クライアントキーを使い、認証URLを返す
address = インスタンスアドレス
client = クライアントキー
scope_i = スコープもとい権限。read=読み,write=書き込み,follow=ユーザーフォローなど。複数指定の場合はスペースで区切る。(例: "read write follow")
:return: url
"""
client = re.sub('\n', '', client)
params = urlencode(dict(
client_id=client,
response_type="code",
redirect_uri="urn:ietf:wg:oauth:2.0:oob",
scope=scope_i
))
return 'https://'+address+'/oauth/authorize?'+params
def authorize(self, address, client, secret, authkey):
"""
クライアントキー、クライアントシークレットを使用して認証済みキーを検証し、アクセストークンを発行する
address = インスタンスアドレス
client = クライアントキー
secret = クライアントシークレット
authkey = 認証済みキー(Webから発行されたもの)
:return: accesstoken
"""
client = re.sub('\n', '', client)
secret = re.sub('\n', '', secret)
res = requests.post('https://'+address+'/oauth/token', dict(
grant_type="authorization_code",
redirect_uri="urn:ietf:wg:oauth:2.0:oob",
client_id=client,
client_secret=secret,
code=authkey
)).json()
return res["access_token"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment