2023-07-30 19:18:11 -07:00
#!/usr/bin/env python
2023-01-26 19:40:26 -08:00
import os
import requests
import json
from urllib . parse import urlencode
def generate_config ( app_name , scopes ) :
2023-10-06 12:02:22 -07:00
#Define Session
session = requests . Session ( )
2023-01-26 19:40:26 -08:00
#Ensure Credentials
parent = os . path . dirname ( os . path . realpath ( __file__ ) )
with open ( os . path . join ( parent , ' config_template.json ' ) , ' r ' ) as template :
config = json . load ( template )
#Create app
instance = input ( ' Please enter your instance: ' )
if not instance [ : 4 ] == ' http ' :
instance = ' https:// ' + instance
2023-10-06 12:02:22 -07:00
response = session . post ( instance + ' /api/v1/apps ' , data = { ' client_name ' : app_name , ' scopes ' : scopes , ' redirect_uris ' : ' urn:ietf:wg:oauth:2.0:oob ' } ) . json ( )
2023-01-26 19:40:26 -08:00
client_id = config [ ' client_id ' ] = response [ ' client_id ' ]
client_secret = config [ ' client_secret ' ] = response [ ' client_secret ' ]
config [ ' instance ' ] = instance
#Log in to user account
print ( instance + ' /oauth/authorize? ' , urlencode ( { ' response_type ' : ' code ' , ' client_id ' : client_id , ' redirect_uri ' : ' urn:ietf:wg:oauth:2.0:oob ' , ' scope ' : scopes } ) )
code = input ( " To generate a token to access your account, " + app_name + " needs an authorization code. Please authorize using the link above and enter the code it provides you \n Code: " )
2023-10-06 12:02:22 -07:00
response = session . post ( instance + ' /oauth/token ' , data = { ' grant_type ' : ' authorization_code ' , ' code ' : code , ' client_id ' : client_id , ' client_secret ' : client_secret , ' redirect_uri ' : ' urn:ietf:wg:oauth:2.0:oob ' , ' scope ' : scopes } )
2023-01-26 19:40:26 -08:00
config [ ' user_token ' ] = response . json ( ) [ ' access_token ' ]
with open ( os . path . join ( parent , ' config.json ' ) , ' w ' ) as config_file :
config_file . write ( json . dumps ( config ) )
if __name__ == " __main__ " :
2023-10-06 12:02:22 -07:00
generate_config ( " test_app " , " read write follow push " )