DEV Community

Cover image for (2) oAuth with Github & Python
schBenedikt
schBenedikt

Posted on

(2) oAuth with Github & Python

Hello and welcome to my 🥈 second part of oAuthentification with Github and Python. Please don't forget to like and comment this post! I would also appreciate a Star on Github.

GitHub logo SchBenedikt / oAuth-with-Github-Python

A easy python code how to generate a oAuthentifcation application with Github & Python

Flask GitHub Login

This is a Flask web application that allows users to log in with their GitHub account and view their GitHub projects. It utilizes OAuth authentication with GitHub and retrieves the user's projects using the GitHub API.

Images

image

Features

User Authentication

The application uses the GitHub OAuth flow to authenticate users. Here's how the authentication process works:

  1. When the user accesses the application, they are redirected to the GitHub login page.
  2. After the user logs in with their GitHub account, they are redirected back to the application with an authorization code.
  3. The application exchanges the authorization code for an access token by making a request to GitHub's access token endpoint.
  4. The access token is saved in the user's session for future API requests.

Project Listing

Once the user is authenticated, they can view a list of their GitHub projects. The project listing feature works as follows:

  1. The application…

NEW

There are other new features in this new code.
All project names from Github are saved in a new "projects.txt" file. If this does not exist, the system creates a new one.


HOW TO USE

To use this code, you must change CLIENT_ID and CLIENT_SECRET to your own CLIENT_ID code and CLIENT_SECRET code. For more information on this, see our first part or below:


CODE

from flask import Flask, redirect, request, session, url_for
import requests
from authlib.integrations.flask_client import OAuth
import os
import sys
import threading
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt


app = Flask(__name__)
app.secret_key = "some_random_string"  # Replace with your secret key

oauth = OAuth(app)
github = oauth.register(
    name="github",
    client_id="CLIENT_ID",
    client_secret="CLIENT_SECRET",
    access_token_url="https://github.com/login/oauth/access_token",
    access_token_params=None,
    authorize_url="https://github.com/login/oauth/authorize",
    authorize_params=None,
    api_base_url="https://api.github.com/",
    client_kwargs={"scope": "user:email"},
)

@app.route("/")
def index():
    username = session.get("username")
    if username:
        projects = get_projects()
        save_projects(projects)
        return f"Hello {username}! You're now logged in. Projects: {', '.join(projects)}"
    else:
        return redirect(url_for("login"))


@app.route("/login")
def login():
    if "access_token" in session:
        return redirect(url_for("index"))
    return github.authorize_redirect(url_for("callback", _external=True))


@app.route("/callback")
def callback():
    if "access_token" in session:
        return redirect(url_for("index"))
    code = request.args.get("code")
    access_token = get_access_token(code)
    session["access_token"] = access_token
    username = get_username()
    session["username"] = username
    return redirect(url_for("index"))


def get_access_token(code):
    payload = {
        "client_id": "CLIENT_ID",
        "client_secret": "CLIENT_SECRET",
        "code": code,
    }
    headers = {
        "Accept": "application/json",
    }
    response = requests.post(
        "https://github.com/login/oauth/access_token", json=payload, headers=headers
    )
    if response.status_code == 200:
        access_token = response.json()["access_token"]
        return access_token
    return None


def get_username():
    access_token = session.get("access_token")
    if access_token:
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Accept": "application/vnd.github.v3+json",
        }
        response = requests.get("https://api.github.com/user", headers=headers)
        if response.status_code == 200:
            username = response.json()["login"]
            return username
    return None


def get_projects():
    access_token = session.get("access_token")
    if access_token:
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Accept": "application/vnd.github.v3+json",
        }
        response = requests.get("https://api.github.com/user/repos", headers=headers)
        if response.status_code == 200:
            projects = [project["name"] for project in response.json()]
            return projects
    return []


def save_projects(projects):
    with open("projects.txt", "w") as file:
        file.write("\n".join(projects))


if not os.path.exists("projects.txt"):
    with open("projects.txt", "w"):
        pass


if __name__ == "__main__":
    app_thread = threading.Thread(target=app.run, kwargs={"host": "localhost", "port": 5000})
    app_thread.daemon = True
    app_thread.start()

    app_pyqt = QApplication(sys.argv)

    sys.exit(app_pyqt.exec_())

Enter fullscreen mode Exit fullscreen mode

How to generate an oAuth Application with Github

Image description

How to generate client secret

Image description
Tip on "generate a new client secret"

Top comments (0)