77 lines
3.0 KiB
Python
77 lines
3.0 KiB
Python
from django.shortcuts import render
|
|
from rest_framework import status, viewsets
|
|
from rest_framework.response import Response
|
|
from .models import Connection, ConnectionType
|
|
from .serializers import ConnectionSerializer
|
|
from rest_framework.decorators import action
|
|
from rest_framework.decorators import permission_classes
|
|
from qrtr_account.models import Account
|
|
from rest_framework.permissions import IsAuthenticated
|
|
import importlib
|
|
import json
|
|
|
|
# Create your views here.
|
|
|
|
|
|
class ConnectionViewSet(viewsets.ModelViewSet):
|
|
"""API endpoint that allows connections to be seen or created
|
|
"""
|
|
permission_classes = [IsAuthenticated]
|
|
queryset = Connection.objects.all()
|
|
serializer_class = ConnectionSerializer
|
|
# Make connections somewhat immutable from the users perspective
|
|
http_method_names = [
|
|
'get',
|
|
'post',
|
|
'delete',
|
|
'options']
|
|
|
|
@action(detail=False, methods=['post'], url_path='plaid')
|
|
def authenticate(self, request):
|
|
print(request.data)
|
|
print(request.data.keys())
|
|
public_token = request.data.get("public_token")
|
|
name = request.data.get("name", "dummyName")
|
|
account_id = request.data.get("account")
|
|
if public_token is None:
|
|
return Response(
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
data="ERROR: missing public_token")
|
|
if account_id is None:
|
|
return Response(
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
data="ERROR: missing account_id")
|
|
accounts = Account.objects.filter(pk=account_id)
|
|
if not accounts:
|
|
return Response(
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
data="ERROR: invalid account_id")
|
|
else:
|
|
account = accounts[0]
|
|
print(request)
|
|
plaid = importlib.import_module(f"connection.connections.plaid_client")
|
|
conn_type = ConnectionType.objects.get(name="Plaid")
|
|
conn, created = Connection.objects \
|
|
.get_or_create(name=name, type=conn_type,
|
|
defaults={
|
|
"credentials": request.data,
|
|
"account": account
|
|
})
|
|
plaid_client = plaid.Connection(request.data)
|
|
conn.credentials = plaid_client.credentials
|
|
conn.save()
|
|
return Response(plaid_client.get_accounts())
|
|
|
|
@action(detail=False, methods=['get'], url_path='accounts')
|
|
def get_accounts(self,request):
|
|
print("GETTING ACCOUNTS!")
|
|
print(request.user)
|
|
connections = []
|
|
user_qrtr_accounts = request.user.owned_accounts.all() | \
|
|
request.user.admin_accounts.all() | \
|
|
request.user.view_accounts.all()
|
|
for qrtr_account in user_qrtr_accounts:
|
|
connections = qrtr_account.connection__set.all()
|
|
for connection in connections:
|
|
connections.append(connection.get_accounts())
|
|
return Response(200) |