refactor: Remove djoser dependency

This commit is contained in:
aldrin 2021-05-18 12:07:03 +02:00
parent a8464d7536
commit 048c8927b8
7 changed files with 62 additions and 54 deletions

View file

@ -1,4 +1,3 @@
setuptools~=56.0.0 setuptools~=40.8.0
django~=2.2.13 django~=2.2.13
djangorestframework~=3.12.4 djangorestframework~=3.9.0
djoser~=2.1.0

View file

@ -29,7 +29,7 @@ async function request(
} }
init.headers.set("Accept", "application/json"); init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json"); init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}/`, init); const response = await fetch(`/${endpoint}/`, init);
if (response.status !== 204) { if (response.status !== 204) {
if (response.status === successStatus) { if (response.status === successStatus) {
return await response.json(); return await response.json();
@ -39,6 +39,16 @@ async function request(
} }
} }
async function api_request(
method: HTTPMethod,
endpoint: string,
successStatus: number,
data: any,
authToken?: string
) {
return request(method, `api/${endpoint}`, successStatus, data, authToken);
}
export class User { export class User {
email: string | undefined; email: string | undefined;
password: string | undefined; password: string | undefined;
@ -48,20 +58,37 @@ export class User {
private token = ""; private token = "";
static async confirm(uid: string, token: string): Promise<void> { static async confirm(uid: string, token: string): Promise<void> {
await request("POST", "users/activation", 204, { uid, token }); await api_request("POST", "users/activation", 204, { uid, token });
} }
async login(): Promise<void> { async login(): Promise<void> {
const response = await request("POST", "token/login", 200, { if (!this.email || !this.password) throw new APIError("", "");
email: this.email,
password: this.password, // logout any existing sessions
}); //await logout()
this.token = response.auth_token; // fetch the login endpoint we use for authentication
this.isAuthenticated = true; const loginEndpoint = "/api-auth/login/";
// fetch the login page, so it sets csrf cookies
await window.fetch(loginEndpoint);
// authenticate us
const body = new window.FormData();
body.append("username", this.email);
body.append("password", this.password);
const csrf_token = Cookies.get("csrftoken");
if (csrf_token) body.append("csrfmiddlewaretoken", csrf_token);
const res = await window.fetch(loginEndpoint, { method: "post", body });
// successful logins are followed by a redirect
if (res.redirected && res.status === 200) {
this.isAuthenticated = true;
} else {
throw new APIError("", "");
}
} }
async save(): Promise<void> { async save(): Promise<void> {
await request( await api_request(
"PATCH", "PATCH",
"users/me", "users/me",
200, 200,
@ -74,7 +101,7 @@ export class User {
} }
async signup(): Promise<void> { async signup(): Promise<void> {
await request("POST", "users", 201, { await api_request("POST", "users", 201, {
email: this.email, email: this.email,
password: this.password, password: this.password,
}); });

View file

@ -1,26 +1,13 @@
from djoser.serializers import UserSerializer as BaseUserSerializer
from rest_framework import serializers from rest_framework import serializers
from userausfall.models import AccountRequest from userausfall.models import AccountRequest, User
class AccountRequestSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.ModelSerializer):
class Meta:
model = AccountRequest
fields = (
"url",
"email",
"confidant_email",
"username",
"is_verified",
"is_trustable",
)
class UserSerializer(BaseUserSerializer):
confidant_email = serializers.EmailField(source="get_confidant_email") confidant_email = serializers.EmailField(source="get_confidant_email")
class Meta(BaseUserSerializer.Meta): class Meta:
model = User
fields = ("email", "username", "confidant_email") fields = ("email", "username", "confidant_email")
def get_confidant_email(self): def get_confidant_email(self):

View file

@ -1,6 +1,6 @@
from rest_framework import routers from rest_framework import routers
from userausfall.rest_api.views import AccountRequestViewSet from userausfall.rest_api.views import UserViewSet
router = routers.DefaultRouter(trailing_slash=True) router = routers.DefaultRouter(trailing_slash=True)
router.register(r'account_requests', AccountRequestViewSet) router.register(r'users', UserViewSet, basename="user")

View file

@ -1,9 +1,19 @@
from rest_framework import viewsets from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from userausfall.models import AccountRequest from userausfall.models import User
from userausfall.rest_api.serializers import AccountRequestSerializer from userausfall.rest_api.serializers import UserSerializer
class AccountRequestViewSet(viewsets.ModelViewSet): class UserViewSet(viewsets.ModelViewSet):
serializer_class = AccountRequestSerializer class Meta:
queryset = AccountRequest.objects.all() queryset = User.objects.all()
@action(detail=False, methods=["PATCH"])
def me(self, request):
return Response(
UserSerializer(
instance=request.user, context={"request": request}
).data
)

View file

@ -38,8 +38,6 @@ INSTALLED_APPS = [
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'userausfall', 'userausfall',
'rest_framework', 'rest_framework',
'rest_framework.authtoken',
'djoser',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -137,18 +135,6 @@ MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/' MEDIA_URL = '/media/'
# Djoser settings
# https://djoser.readthedocs.io/en/2.1.0/settings.html
DJOSER = {
"ACTIVATION_URL": "confirm/{uid}/{token}",
"SEND_ACTIVATION_EMAIL": True,
"SERIALIZERS": {
"current_user": "userausfall.rest_api.serializers.UserSerializer",
}
}
# Sending email # Sending email
# https://docs.djangoproject.com/en/3.2/topics/email/ # https://docs.djangoproject.com/en/3.2/topics/email/
@ -160,6 +146,6 @@ EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_FRAMEWORK = { REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ( 'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication',
), ),
} }

View file

@ -6,6 +6,5 @@ from userausfall.rest_api import urls as rest_api_urls
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('api/', include(rest_api_urls.router.urls)), path('api/', include(rest_api_urls.router.urls)),
path('api/', include('djoser.urls')), path("api-auth/", include("rest_framework.urls")),
path('api/', include('djoser.urls.authtoken')),
] ]