This commit is contained in:
Eugene Pankov
2021-07-06 23:45:52 +02:00
parent 6bd5aff8b7
commit 3ff34b2618
36 changed files with 76 additions and 83 deletions

0
tabby/__init__.py Normal file
View File

0
tabby/app/__init__.py Normal file
View File

11
tabby/app/admin.py Normal file
View File

@@ -0,0 +1,11 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User, Config
class CustomUserAdmin(UserAdmin):
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('custom_connection_gateway', 'custom_connection_gateway_token')}),
)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Config)

105
tabby/app/api.py Normal file
View File

@@ -0,0 +1,105 @@
import os
from dataclasses import dataclass
from django.conf import settings
from django.contrib.auth import logout
from rest_framework import fields
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.serializers import ModelSerializer, Serializer
from rest_framework_dataclasses.serializers import DataclassSerializer
from .models import Config, User
@dataclass
class AppVersion:
version: str
class AppVersionSerializer(DataclassSerializer):
class Meta:
dataclass = AppVersion
class ConfigSerializer(ModelSerializer):
class Meta:
model = Config
read_only_fields = ('user', 'created_at', 'modified_at')
fields = '__all__'
class ConfigViewSet(ModelViewSet):
queryset = Config.objects.all()
serializer_class = ConfigSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
if self.request.user.is_authenticated:
return Config.objects.filter(user=self.request.user)
return Config.objects.none()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class AppVersionViewSet(ListModelMixin, GenericViewSet):
serializer_class = AppVersionSerializer
lookup_field = 'id'
lookup_value_regex = r'[\w\d.-]+'
queryset = ''
def _get_versions(self):
return [AppVersion(version=x) for x in os.listdir(settings.APP_DIST_PATH)]
def list(self, request, *args, **kwargs):
return Response(self.serializer_class(
self._get_versions(),
many=True,
).data)
class UserSerializer(ModelSerializer):
id = fields.IntegerField()
is_pro = fields.SerializerMethodField()
class Meta:
model = User
fields = ('id', 'username', 'active_config', 'custom_connection_gateway', 'custom_connection_gateway_token', 'is_pro')
read_only_fields = ('id', 'username')
def get_is_pro(self, obj):
return False
class UserViewSet(RetrieveModelMixin, UpdateModelMixin, GenericViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
def get_object(self):
if self.request.user.is_authenticated:
return self.request.user
raise PermissionDenied()
class LogoutView(APIView):
def post(self, request, format=None):
logout(request)
return Response(None)
class InstanceInfoSerializer(Serializer):
login_enabled = fields.BooleanField()
class InstanceInfoViewSet(RetrieveModelMixin, GenericViewSet):
queryset = '' # type: ignore
serializer_class = InstanceInfoSerializer
def get_object(self):
return {
'login_enabled': settings.ENABLE_LOGIN,
}

6
tabby/app/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class AppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tabby.app'

74
tabby/app/consumers.py Normal file
View File

@@ -0,0 +1,74 @@
import asyncio
import os
import ssl
import websockets
from channels.generic.websocket import AsyncWebsocketConsumer
from django.conf import settings
from urllib.parse import quote
class GatewayConnection:
_ssl_context: ssl.SSLContext = None
def __init__(self, host: str, port: int):
if settings.CONNECTION_GATEWAY_AUTH_KEY and not GatewayConnection._ssl_context:
ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain(
os.path.realpath(settings.CONNECTION_GATEWAY_AUTH_CERTIFICATE),
os.path.realpath(settings.CONNECTION_GATEWAY_AUTH_KEY),
)
if settings.CONNECTION_GATEWAY_AUTH_CA:
ctx.load_verify_locations(
cafile=os.path.realpath(settings.CONNECTION_GATEWAY_AUTH_CA),
)
ctx.verify_mode = ssl.CERT_REQUIRED
GatewayConnection._ssl_context = ctx
proto = 'wss' if GatewayConnection._ssl_context else 'ws'
self.url = f'{proto}://localhost:9000/connect/{quote(host)}:{quote(str(port))}'
async def connect(self):
self.context = websockets.connect(self.url, ssl=GatewayConnection._ssl_context)
self.socket = await self.context.__aenter__()
async def send(self, data):
await self.socket.send(data)
def recv(self, timeout=None):
return asyncio.wait_for(self.socket.recv(), timeout)
async def close(self):
await self.socket.close()
await self.context.__aexit__(None, None, None)
class TCPConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.closed = False
self.conn = GatewayConnection(
self.scope['url_route']['kwargs']['host'],
int(self.scope['url_route']['kwargs']['port']),
)
await self.conn.connect()
await self.accept()
self.reader = asyncio.get_event_loop().create_task(self.socket_reader())
async def disconnect(self, close_code):
self.closed = True
await self.conn.close()
async def receive(self, bytes_data):
await self.conn.send(bytes_data)
async def socket_reader(self):
while True:
if self.closed:
return
try:
data = await self.conn.recv(timeout=10)
except asyncio.TimeoutError:
continue
except websockets.exceptions.ConnectionClosed:
await self.close()
return
await self.send(bytes_data=data)

View File

@@ -0,0 +1,44 @@
# Generated by Django 3.2.3 on 2021-06-05 21:23
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View File

@@ -0,0 +1,48 @@
# Generated by Django 3.2.3 on 2021-06-05 21:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='active_version',
field=models.CharField(max_length=32, null=True),
),
migrations.AddField(
model_name='user',
name='created_at',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='modified_at',
field=models.DateTimeField(auto_now=True),
),
migrations.CreateModel(
name='Config',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField(default='{}')),
('last_used_with_version', models.CharField(max_length=32, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('modified_at', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='configs', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='user',
name='active_config',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='app.config'),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.2.3 on 2021-06-20 20:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20210605_2137'),
]
operations = [
migrations.AddField(
model_name='user',
name='custom_connection_gateway',
field=models.CharField(max_length=255, null=True),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.2.3 on 2021-06-20 20:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0003_user_custom_connection_gateway'),
]
operations = [
migrations.AddField(
model_name='user',
name='custom_connection_gateway_token',
field=models.CharField(max_length=255, null=True),
),
]

View File

28
tabby/app/models.py Normal file
View File

@@ -0,0 +1,28 @@
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from django.db.models.signals import post_save
class Config(models.Model):
user = models.ForeignKey('app.User', related_name='configs', on_delete=models.CASCADE)
content = models.TextField(default='{}')
last_used_with_version = models.CharField(max_length=32, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class User(AbstractUser):
active_config = models.ForeignKey(Config, null=True, on_delete=models.CASCADE, related_name='+')
active_version = models.CharField(max_length=32, null=True)
custom_connection_gateway = models.CharField(max_length=255, null=True)
custom_connection_gateway_token = models.CharField(max_length=255, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
# @receiver(user_logged_in)
# def post_login(sender, user, request, **kwargs):
# if not user.active_config:
# user.active_config = Config.objects.filter()

63
tabby/app/sponsors.py Normal file
View File

@@ -0,0 +1,63 @@
from django.conf import settings
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
GQL_ENDPOINT = 'https://api.github.com/graphql'
def get_sponsor_usernames():
client = Client(
transport=RequestsHTTPTransport(
url=GQL_ENDPOINT,
use_json=True,
headers={
'Authorization': f'Bearer {settings.GITHUB_TOKEN}',
}
)
)
result = []
after = None
while True:
params = 'first: 1'
if after:
params += f', after:"{after}"'
query = '''
query {
user (login: "eugeny") {
sponsorshipsAsMaintainer(%s, includePrivate: true) {
pageInfo {
startCursor
hasNextPage
endCursor
}
nodes {
createdAt
tier {
monthlyPriceInDollars
}
sponsor{
... on User {
login
}
}
}
}
}
}
''' % (params,)
response = client.execute(gql(query))
after = response['user']['sponsorshipsAsMaintainer']['pageInfo']['endCursor']
nodes = response['user']['sponsorshipsAsMaintainer']['nodes']
if not len(nodes):
break
for node in nodes:
if node['tier']['monthlyPriceInDollars'] >= settings.GITHUB_SPONSORS_MIN_PAYMENT:
result.append(node['sponsor']['login'])
return result

3
tabby/app/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

28
tabby/app/urls.py Normal file
View File

@@ -0,0 +1,28 @@
from django.urls import path, re_path, include
from rest_framework import routers
from . import api
from . import consumers
from . import views
router = routers.DefaultRouter(trailing_slash=False)
router.register('api/1/configs', api.ConfigViewSet)
router.register('api/1/versions', api.AppVersionViewSet, basename='app-versions')
urlpatterns = [
path('api/1/auth/logout', api.LogoutView.as_view()),
path('api/1/user', api.UserViewSet.as_view({'get': 'retrieve', 'put': 'update'})),
path('api/1/instance-info', api.InstanceInfoViewSet.as_view({'get': 'retrieve'})),
re_path('^(|login|app)$', views.IndexView.as_view()),
path('terminal', views.TerminalView.as_view()),
path('app-dist/<version>/<path:path>', views.AppDistView.as_view()),
path('build/<path:path>', views.BuildView.as_view()),
path('', include(router.urls)),
]
websocket_urlpatterns = [
re_path(r'^api/1/gateway/tcp/(?P<host>[^/]+):(?P<port>\d+)$', consumers.TCPConsumer.as_asgi()),
]

26
tabby/app/views.py Normal file
View File

@@ -0,0 +1,26 @@
import os
from django.conf import settings
from django.views import static
from rest_framework.views import APIView
class IndexView(APIView):
def get(self, request, format=None):
return static.serve(request, 'index.html', document_root=str(settings.BASE_DIR / 'build'))
class TerminalView(APIView):
def get(self, request, format=None):
response = static.serve(request, 'terminal.html', document_root=str(settings.BASE_DIR / 'build'))
response['X-Frame-Options'] = 'SAMEORIGIN'
return response
class AppDistView(APIView):
def get(self, request, version=None, path=None, format=None):
return static.serve(request, os.path.join(version, path), document_root=str(settings.APP_DIST_PATH))
class BuildView(APIView):
def get(self, request, path=None, format=None):
return static.serve(request, path, document_root=str(settings.BASE_DIR / 'build'))

16
tabby/asgi.py Normal file
View File

@@ -0,0 +1,16 @@
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tabby.settings')
from .app.urls import websocket_urlpatterns
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter(websocket_urlpatterns),
),
})

178
tabby/settings.py Normal file
View File

@@ -0,0 +1,178 @@
import os
import dj_database_url
from dotenv import load_dotenv
from pathlib import Path
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-jw3fshufj(1$iv+&9bie=r%27+^e2sz0!_gq38*5p5!csrm&#s'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'rest_framework',
'social_django',
'tabby.app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'tabby.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
ASGI_APPLICATION = 'tabby.asgi.application'
WSGI_APPLICATION = 'tabby.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': dj_database_url.config(conn_max_age=600)
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTH_USER_MODEL = 'app.User'
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
STATICFILES_DIRS = [BASE_DIR / 'build']
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CSRF_USE_SESSIONS = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_NAME = 'XSRF-TOKEN'
CSRF_HEADER_NAME = 'HTTP_X_XSRF_TOKEN'
AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2',
'social_core.backends.gitlab.GitLabOAuth2',
'social_core.backends.azuread.AzureADOAuth2',
'social_core.backends.microsoft.MicrosoftOAuth2',
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_GITHUB_SCOPE = ['read:user', 'user:email']
LOGIN_REDIRECT_URL = '/app'
APP_DIST_PATH = BASE_DIR / 'app-dist'
for key in [
'SOCIAL_AUTH_GITHUB_KEY',
'SOCIAL_AUTH_GITHUB_SECRET',
'SOCIAL_AUTH_GITLAB_KEY',
'SOCIAL_AUTH_GITLAB_SECRET',
'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY',
'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET',
'SOCIAL_AUTH_MICROSOFT_GRAPH_KEY',
'SOCIAL_AUTH_MICROSOFT_GRAPH_SECRET',
'CONNECTION_GATEWAY_AUTH_CA',
'CONNECTION_GATEWAY_AUTH_CERTIFICATE',
'CONNECTION_GATEWAY_AUTH_KEY',
'GITHUB_SPONSORS_USER',
'GITHUB_SPONSORS_MIN_PAYMENT',
'GITHUB_TOKEN',
'ENABLE_LOGIN',
]:
globals()[key] = os.getenv(key)
for key in [
'GITHUB_SPONSORS_MIN_PAYMENT',
]:
globals()[key] = int(globals()[key]) if globals()[key] else None
for key in [
'CONNECTION_GATEWAY_AUTH_CA',
'CONNECTION_GATEWAY_AUTH_CERTIFICATE',
'CONNECTION_GATEWAY_AUTH_KEY',
]:
v = globals()[key]
if v and not os.path.exists(v):
raise ValueError(f'{v} does not exist')

9
tabby/urls.py Normal file
View File

@@ -0,0 +1,9 @@
from django.contrib import admin
from django.urls import path, include
from .app.urls import urlpatterns
urlpatterns = [
path('', include(urlpatterns)),
path('api/1/auth/social/', include('social_django.urls', namespace='social')),
path('admin/', admin.site.urls),
]

7
tabby/wsgi.py Normal file
View File

@@ -0,0 +1,7 @@
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tabby.settings')
application = get_wsgi_application()