Last active
December 23, 2019 09:31
-
-
Save wilhelmklopp/43cd18d5b991b8f5e288 to your computer and use it in GitHub Desktop.
Example of how do to a basic Slack OAuth implementation in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# urls.py | |
from django.conf.urls import url | |
from main import views | |
urlpatterns = [ | |
url(r'^oauthcallback/', views.oauthcallback) | |
] | |
# models.py | |
from django.db import models | |
class Teams(models.Model): | |
team_id = models.CharField(primary_key=True, max_length=1000) | |
access_token = models.CharField(max_length=1000) | |
created = models.DateTimeField(auto_now=False, auto_now_add=True, editable=False) | |
# views.py | |
from django.http import HttpResponse | |
import requests | |
from main.models import Teams | |
from django.core.exceptions import ObjectDoesNotExist | |
from django.utils import timezone | |
client_id = "" # YOUR CLIENT ID HERE | |
client_secret = "" # YOUR CLIENT SECRET HERE | |
def oauthcallback(request): | |
if "error" in request.GET: | |
status = "Oauth authentication failed. You aborted the Authentication process." | |
return HttpResponse(status) | |
code = request.GET["code"] | |
url = "https://slack.com/api/oauth.access" | |
data = { | |
"client_id": client_id, | |
"client_secret": client_secret, | |
"code": code, | |
} | |
r = requests.get(url, params=data) | |
query_result = r.json() | |
if query_result["ok"]: | |
access_token = query_result["access_token"] | |
team_name = query_result["team_name"] | |
team_id = query_result["team_id"] | |
try: | |
team = Teams.objects.get(team_id=team_id) | |
except ObjectDoesNotExist: | |
# new Team (yay!) | |
new_team = Teams(access_token=access_token, team_name=team_name, team_id=team_id, last_changed=timezone.now()) | |
new_team.save() | |
else: | |
team.access_token = access_token | |
team.team_name = team_name | |
team.save() | |
else: | |
status = "Oauth authentication failed." | |
return HttpResponse(status) | |
status = "Oauth authentication successful!" | |
return HttpResponse(status) |
Just found this for a new side project of mine and I check the creator and it's you haha
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much for this!