Compare commits

...

2 commits

Author SHA1 Message Date
048c8927b8 refactor: Remove djoser dependency 2021-05-18 12:07:03 +02:00
a8464d7536 fix: Transmit confidant_email on edit 2021-05-18 11:06:02 +02:00
12 changed files with 140 additions and 57 deletions

View file

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

View file

@ -2,7 +2,7 @@ import Cookies from "js-cookie";
type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH";
class APIError extends Error {
export class APIError extends Error {
constructor(message: string, public readonly errors: unknown) {
super(message);
}
@ -29,7 +29,7 @@ async function request(
}
init.headers.set("Accept", "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 === successStatus) {
return await response.json();
@ -39,41 +39,69 @@ 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 {
email: string | undefined;
password: string | undefined;
private username: string | null = null;
private confidantEmail: string | null = null;
username: string | null = null;
confidantEmail: string | null = null;
isAuthenticated = false;
private token = "";
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> {
const response = await request("POST", "token/login", 200, {
email: this.email,
password: this.password,
});
this.token = response.auth_token;
if (!this.email || !this.password) throw new APIError("", "");
// logout any existing sessions
//await logout()
// fetch the login endpoint we use for authentication
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> {
await request(
await api_request(
"PATCH",
"users/me",
200,
{
username: this.username,
confidant_email: this.confidantEmail,
},
this.token
);
}
async signup(): Promise<void> {
await request("POST", "users", 201, {
await api_request("POST", "users", 201, {
email: this.email,
password: this.password,
});

View file

@ -24,11 +24,15 @@
</tr>
<tr>
<td>Benutzername</td>
<td><InlineEditor v-model="user.username" @input="user.save()" /></td>
<td>
<InlineEditor v-model="user.username" @input="user.save()" />
</td>
</tr>
<tr>
<td>Vertrauensperson</td>
<td><inline-editor v-model="user.confidant_email" /></td>
<td>
<inline-editor v-model="user.confidantEmail" @input="user.save()" />
</td>
</tr>
<tr>
<td>E-Mail-Adresse</td>

19
src/mixins.ts Normal file
View file

@ -0,0 +1,19 @@
import Component from "vue-class-component";
import Vue from "vue";
@Component
export class NotifyMixin extends Vue {
showError(): void {
this.$buefy.toast.open({
message: "Es ist leider ein Fehler aufgetreten.",
type: "is-danger",
});
}
showSuccess(message: string): void {
this.$buefy.toast.open({
message,
type: "is-success",
});
}
}

View file

@ -15,24 +15,34 @@
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Component } from "vue-property-decorator";
import LoginForm from "@/components/LoginForm.vue";
import { mixins } from "vue-class-component";
import { User } from "@/api";
import UserTable from "@/components/UserTable.vue";
import { NotifyMixin } from "@/mixins";
@Component({ components: { UserTable, LoginForm } })
export default class Home extends Vue {
export default class Home extends mixins(NotifyMixin) {
private user = new User();
public async created(): Promise<void> {
if (this.$route.name === "confirm") {
await this.doConfirm();
} else if (!this.user.isAuthenticated) {
this.$router.push({ name: "login" });
}
}
private async doConfirm() {
try {
await User.confirm(this.$route.params.uid, this.$route.params.token);
this.$router.push({ name: "login" });
this.$buefy.toast.open({
message:
"Deine E-Mail-Adresse wurde bestätigt. Du kannst dich nun anmelden.",
type: "is-success",
});
this.showSuccess(
"Deine E-Mail-Adresse wurde bestätigt. Du kannst dich nun anmelden."
);
} catch {
this.showError();
}
}
}

View file

@ -0,0 +1,20 @@
# Generated by Django 2.2.20 on 2021-05-18 08:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('userausfall', '0003_auto_20210414_0827'),
]
operations = [
migrations.AddField(
model_name='user',
name='confidant',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
),
]

View file

@ -68,6 +68,7 @@ class User(AbstractBaseUser, PermissionsMixin):
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
confidant = models.ForeignKey("User", on_delete=models.SET_NULL, null=True)
objects = UserManager()
@ -83,6 +84,9 @@ class User(AbstractBaseUser, PermissionsMixin):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_confidant_email(self):
return ""
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.

View file

@ -1,15 +1,19 @@
from djoser.serializers import UserSerializer as BaseUserSerializer
from rest_framework import serializers
from userausfall.models import AccountRequest
from userausfall.models import AccountRequest, User
class AccountRequestSerializer(serializers.HyperlinkedModelSerializer):
class UserSerializer(serializers.ModelSerializer):
confidant_email = serializers.EmailField(source="get_confidant_email")
class Meta:
model = AccountRequest
fields = ('url', 'email', 'confidant_email', 'username', 'is_verified', 'is_trustable')
model = User
fields = ("email", "username", "confidant_email")
def get_confidant_email(self):
return ""
class UserSerializer(BaseUserSerializer):
class Meta(BaseUserSerializer.Meta):
fields = ('email', 'username')
def update(self, instance, validated_data):
print(validated_data)
confidant = validated_data.pop("get_confidant_email")
return super().update(instance, validated_data)

View file

@ -1,6 +1,6 @@
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.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.decorators import action
from rest_framework.response import Response
from userausfall.models import AccountRequest
from userausfall.rest_api.serializers import AccountRequestSerializer
from userausfall.models import User
from userausfall.rest_api.serializers import UserSerializer
class AccountRequestViewSet(viewsets.ModelViewSet):
serializer_class = AccountRequestSerializer
queryset = AccountRequest.objects.all()
class UserViewSet(viewsets.ModelViewSet):
class Meta:
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',
'userausfall',
'rest_framework',
'rest_framework.authtoken',
'djoser',
]
MIDDLEWARE = [
@ -137,18 +135,6 @@ MEDIA_ROOT = os.path.join(BASE_DIR, '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
# https://docs.djangoproject.com/en/3.2/topics/email/
@ -160,6 +146,6 @@ EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_FRAMEWORK = {
'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 = [
path('admin/', admin.site.urls),
path('api/', include(rest_api_urls.router.urls)),
path('api/', include('djoser.urls')),
path('api/', include('djoser.urls.authtoken')),
path("api-auth/", include("rest_framework.urls")),
]