Skip to content

Commit

Permalink
🦺 Feat: update auth service and components
Browse files Browse the repository at this point in the history
  • Loading branch information
Sye0w committed Oct 2, 2024
1 parent daef4fb commit 58cd4f6
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 26 deletions.
16 changes: 14 additions & 2 deletions src/app/services/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core';
import { Auth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, GoogleAuthProvider, signInWithPopup, User, AuthError } from '@angular/fire/auth';
import { BehaviorSubject, Observable } from 'rxjs';
import { IUser } from '../blog.interface';

export enum AuthErrorType {
EmailAlreadyInUse = 'auth/email-already-in-use',
Expand All @@ -25,9 +26,10 @@ export class AuthService {
});
}

async register(email: string, password: string): Promise<void> {
async register(email: string, password: string): Promise<IUser> {
try {
await createUserWithEmailAndPassword(this.auth, email, password);
const userCredential = await createUserWithEmailAndPassword(this.auth, email, password);
return this.createUserObject(userCredential.user);
} catch (error) {
throw this.handleAuthError(error as AuthError);
}
Expand Down Expand Up @@ -84,4 +86,14 @@ export class AuthService {
}
return { type: errorType, message: error.message };
}

private createUserObject(user: User): IUser {
return {
email: user.email!,
password: '', // We don't store the password
image: user.photoURL || '',
username: user.displayName || '',
uid: user.uid
};
}
}
2 changes: 1 addition & 1 deletion src/app/views/auth/login/login.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ <h4>Login</h4>
</form>
<footer>
<span>Don't have an account?</span>
<a routerLink="/auth/register" class="link-effect">
<a routerLink="/auth/register/" class="link-effect">
<span>Create account</span>
</a>
</footer>
Expand Down
2 changes: 1 addition & 1 deletion src/app/views/auth/login/login.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class LoginComponent implements OnInit {
const { email, password } = this.loginForm.value;
try {
await this.authService.login(email, password);
this.messageService.add({severity:'success', summary: 'Success', detail: 'Login successful!',life: 3000})
this.messageService.add({severity:'success', summary: 'Success', detail: 'Login successful!',life: 3000});
setTimeout(() => {
this.router.navigate(['/fireblog/posts'])
}, 3000);
Expand Down
55 changes: 33 additions & 22 deletions src/app/views/auth/register/register.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angula
import { CommonModule } from '@angular/common';
import { MessageService } from 'primeng/api';
import { ToastModule } from 'primeng/toast';
import { IUser } from '../../../services/blog.interface';
import { FireblogFacadeService } from '../../../services/fireblog/fireblog-facade.service';

@Component({
selector: 'app-register',
Expand All @@ -23,7 +25,8 @@ export class RegisterComponent implements OnInit {
private authService: AuthService,
private fb: FormBuilder,
private messageService: MessageService,
private router: Router
private router: Router,
private blogFacade: FireblogFacadeService
) {}

ngOnInit(): void {
Expand All @@ -50,12 +53,13 @@ export class RegisterComponent implements OnInit {
this.isLoading = true;
const { email, password } = this.registerForm.value;
try {
await this.authService.register(email, password);
this.messageService.add({severity:'success', summary: 'Success', detail: 'Registration successful!', life: 3000});
setTimeout(() => {
this.router.navigate(['/auth/login'])
}, 3000);
const user: IUser = await this.authService.register(email, password);
await this.blogFacade.createEmptyBlogPost(user);
this.messageService.add({severity:'success', summary: 'Success', detail: 'Registration successful!', life: 2500});
await new Promise(resolve => setTimeout(resolve, 2000));
await this.router.navigate(['/auth/login']);
} catch (error: any) {
console.error('Registration error:', error);
this.handleRegistrationError(error);
} finally {
this.isLoading = false;
Expand All @@ -65,24 +69,31 @@ export class RegisterComponent implements OnInit {
}
}

private handleRegistrationError(error: { type: AuthErrorType, message: string }) {
private handleRegistrationError(error: any) {
console.error('Full error object:', error);
let errorMessage: string;
switch (error.type) {
case AuthErrorType.EmailAlreadyInUse:
errorMessage = 'This email is already in use. Please try a different email.';
break;
case AuthErrorType.WeakPassword:
errorMessage = 'The password is too weak. Please choose a stronger password.';
break;
case AuthErrorType.InvalidEmail:
errorMessage = 'The email address is invalid. Please enter a valid email.';
break;
case AuthErrorType.TooManyRequests:
errorMessage = 'Too many unsuccessful attempts. Please try again later.';
break;
default:
errorMessage = 'An unexpected error occurred. Please try again.';

if (error && error.type) {
switch (error.type) {
case AuthErrorType.EmailAlreadyInUse:
errorMessage = 'This email is already in use. Please try a different email.';
break;
case AuthErrorType.WeakPassword:
errorMessage = 'The password is too weak. Please choose a stronger password.';
break;
case AuthErrorType.InvalidEmail:
errorMessage = 'The email address is invalid. Please enter a valid email.';
break;
case AuthErrorType.TooManyRequests:
errorMessage = 'Too many unsuccessful attempts. Please try again later.';
break;
default:
errorMessage = `An unexpected error occurred: ${error.message || 'Unknown error'}`;
}
} else {
errorMessage = 'An unexpected error occurred. Please try again.';
}

this.messageService.add({severity:'error', summary: 'Error', detail: errorMessage});
}
}

0 comments on commit 58cd4f6

Please sign in to comment.