check email duplicates on the server before registration

This commit is contained in:
Chneemann 2024-08-07 04:48:22 +02:00
parent bfa8b61449
commit 01f98753cc
4 changed files with 39 additions and 6 deletions

View file

@ -145,3 +145,9 @@ class AuthView(ObtainAuthToken):
if request.user.is_authenticated:
return Response(request.user.id, status=status.HTTP_200_OK)
return Response({"error": "User is not logged in"}, status=status.HTTP_401_UNAUTHORIZED)
def post(self, request):
email = request.data.get('email')
if CustomUser.objects.filter(email=email).exists():
return Response({'mail': 'A user with this email already exists.'}, status=status.HTTP_400_BAD_REQUEST)
return Response(status=status.HTTP_200_OK)

View file

@ -33,6 +33,11 @@
!isUserEmailValid(authData.mail.toLowerCase())) {
<p>This is not a valid email format</p>
}}
<div *ngIf="errorService.error$ | async as errors">
<div *ngIf="errors?.['mail']">
<p>{{ errors["mail"] }}</p>
</div>
</div>
</div>
<app-btn-large
[value]="'Sign Up'"

View file

@ -3,6 +3,8 @@ import { FormsModule, NgForm } from '@angular/forms';
import { BtnLargeComponent } from '../../shared/components/btn-large/btn-large.component';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ErrorService } from '../../services/error.service';
import { AuthService } from '../../services/auth.service';
@Component({
selector: 'app-auth',
@ -15,20 +17,36 @@ export class AuthComponent {
authData = {
mail: '',
};
constructor(private router: Router) {}
constructor(
private router: Router,
public errorService: ErrorService,
private authService: AuthService
) {}
isUserEmailValid(emailValue: string) {
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(emailValue);
}
onSubmit(ngForm: NgForm, mailInput: any) {
async onSubmit(ngForm: NgForm, mailInput: any) {
if (ngForm.submitted && ngForm.form.valid) {
const queryParams = { mail: this.authData.mail };
this.router.navigate(['/register'], { queryParams });
ngForm.form.reset();
await this.checkDuplicatesEmail();
} else {
mailInput.control.markAsTouched();
}
}
async checkDuplicatesEmail() {
const body = {
email: this.authData.mail,
};
try {
await this.authService.checkAuthUserMail(body);
const queryParams = { mail: this.authData.mail };
this.router.navigate(['/register'], { queryParams });
this.errorService.clearError();
} catch (error) {
this.errorService.errorMsg(error);
}
}
}

View file

@ -56,6 +56,10 @@ export class AuthService {
);
}
async checkAuthUserMail(body: any) {
await lastValueFrom(this.http.post(`${environment.baseUrl}/auth/`, body));
}
private getAuthHeaders(): HttpHeaders {
let authToken = localStorage.getItem('authToken');
if (!authToken) {