Guest User

prawAuth.py

a guest
Jan 23rd, 2021
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. import random
  2. import socket
  3. import sys
  4. import webbrowser
  5.  
  6. import praw
  7.  
  8.  
  9. def receive_connection():
  10.     """Wait for and then return a connected socket..
  11.  
  12.    Opens a TCP connection on port 8080, and waits for a single client.
  13.  
  14.    """
  15.     server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  16.     server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  17.     server.bind(("localhost", 8080))
  18.     server.listen(1)
  19.     client = server.accept()[0]
  20.     server.close()
  21.     return client
  22.  
  23.  
  24. def send_message(client, message):
  25.     """Send message to client and close the connection."""
  26.     print(message)
  27.     client.send(f"HTTP/1.1 200 OK\r\n\r\n{message}".encode("utf-8"))
  28.     client.close()
  29.  
  30.  
  31. def main():
  32.     """Provide the program's entry point when directly executed."""
  33.     commaScopes = input(
  34.         "Now enter a comma separated list of scopes, or all for all tokens: "
  35.     )
  36.  
  37.     if commaScopes.lower() == "all":
  38.         scopes = ["*"]
  39.     else:
  40.         scopes = commaScopes.strip().split(",")
  41.  
  42.     reddit = praw.Reddit(
  43.         client_id='BGLk80bE3REJAw',
  44.         client_secret=None,
  45.         redirect_uri="http://localhost:8080",
  46.         user_agent="Reddit CLI by /u/Gaffclant v1.0",
  47.     )
  48.     state = str(random.randint(0, 65000))
  49.     url = reddit.auth.url(scopes, state, implicit=True)
  50.     webbrowser.open(url)
  51.     sys.stdout.flush()
  52.  
  53.     client = receive_connection()
  54.     data = client.recv(1024).decode("utf-8")
  55.     print(data)
  56.     param_tokens = data.split(" ", 2)[1]
  57.     print(param_tokens)
  58.     param_tokens = param_tokens.split("#", 2)[0]
  59.     print(param_tokens)
  60.     param_tokens=param_tokens.split("&")
  61.     params = {
  62.         key: value for (key, value) in [token.split("=") for token in param_tokens]
  63.     }
  64.  
  65.     if state != params["state"]:
  66.         send_message(
  67.             client,
  68.             f"State mismatch. Expected: {state} Received: {params['state']}",
  69.         )
  70.         return 1
  71.     elif "error" in params:
  72.         send_message(client, params["error"])
  73.         return 1
  74.  
  75.     refresh_token = reddit.auth.authorize(params["access_token"])
  76.     send_message(client, f"Access Token: {access_token}")
  77.     return 0
  78.  
  79.  
  80. if __name__ == "__main__":
  81.     sys.exit(main())
  82.  
Advertisement
Add Comment
Please, Sign In to add comment