Skip to content

Instantly share code, notes, and snippets.

@arivictor
Last active February 6, 2021 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arivictor/f28f5842c2fbd7a9b34e1ba02cfc343e to your computer and use it in GitHub Desktop.
Save arivictor/f28f5842c2fbd7a9b34e1ba02cfc343e to your computer and use it in GitHub Desktop.
This is the completed project for the reddit oauth project
from flask import Flask, redirect, url_for, request, session
import praw
import uuid
app = Flask(__name__)
# The secret key is used to sign/secure the session data
app.secret_key = "my-secret-flask-key"
# The reddit instance, fill in your details
reddit = praw.Reddit(
client_id="CLIENT ID",
client_secret="CLIENT SECRET",
redirect_uri="http://localhost:8080/callback", # Must match your Reddit App details
user_agent="MyApp v1",
)
@app.route('/')
def main():
if session.get("authenticated", False):
return f"Hello, {str(reddit.user.me())} | <a href='/clear'>Clear</a>"
return "<h1>My App</h1>" \
"<a href='/authorize'>Authenticate</a>"
@app.route("/authorize")
def authorize():
# Generates an authorization URL
scopes = [
"identity",
"edit",
"history"
]
session["state_code"] = str(uuid.uuid4())
return redirect(reddit.auth.url(scopes, session.get("state_code"), 'permanent'))
@app.route("/clear")
def clear():
""" Clears the session data """
session.clear()
return redirect(url_for("main"))
@app.route("/callback")
def callback():
""" After authorizing, Reddit will redirect to here with data """
# retrieve the state and code from reddit
state = request.args.get("state", None)
code = request.args.get("code", None)
error = request.args.get("error", None)
# Handle errors
if error is not None:
return error
# if the state codes do not match, the request was not by us, ...hackers :O
if state != session.get("state_code"):
return "Unauthorised"
if code is None:
return "No code!"
# Use the code to authenticate the Reddit instance
reddit.auth.authorize(code)
# Let the server know we've authenticated
session["authenticated"] = True
# Now that we have the users permission, go back to the start
return redirect(url_for("main"))
if __name__ == '__main__':
app.run(host="localhost", port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment