From 66f9121f1b08278106be88d681acb875d3d9ec31 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tormod=20Nyg=C3=A5rd?= <tormodny@stud.ntnu.no>
Date: Mon, 15 Mar 2021 12:59:44 +0100
Subject: [PATCH] Issue: Fixed logout error and other problems (#12)

---
 client/src/app/app-routing.module.ts          |  4 +--
 client/src/app/app.component.html             |  8 +++---
 client/src/app/app.component.ts               |  6 ++++-
 client/src/app/authentication/auth.service.ts | 22 ++++++++-------
 .../post-details/post-details.component.ts    |  3 ++-
 .../posts/post-form/post-form.component.ts    |  4 +--
 .../post-thumbnail.component.html             |  2 +-
 .../user-login-form.component.ts              |  3 +++
 .../user-logout/user-logout.component.html    |  1 -
 .../user-logout/user-logout.component.scss    |  0
 .../user-logout/user-logout.component.spec.ts | 27 -------------------
 .../user-logout/user-logout.component.ts      | 17 ------------
 client/src/app/users/user.module.ts           |  5 +---
 13 files changed, 32 insertions(+), 70 deletions(-)
 delete mode 100644 client/src/app/users/user-logout/user-logout.component.html
 delete mode 100644 client/src/app/users/user-logout/user-logout.component.scss
 delete mode 100644 client/src/app/users/user-logout/user-logout.component.spec.ts
 delete mode 100644 client/src/app/users/user-logout/user-logout.component.ts

diff --git a/client/src/app/app-routing.module.ts b/client/src/app/app-routing.module.ts
index 9de5dfd..4bae76e 100644
--- a/client/src/app/app-routing.module.ts
+++ b/client/src/app/app-routing.module.ts
@@ -6,7 +6,6 @@ import { PostListComponent } from './posts/post-list/post-list.component';
 import { UserRegistrationFormComponent } from './users/user-registration-form/user-registration-form.component';
 import { UserLoginFormComponent } from './users/user-login-form/user-login-form.component';
 import { UserProfileComponent } from './users/user-profile/user-profile.component';
-import { UserLogoutComponent } from './users/user-logout/user-logout.component';
 
 const routes: Routes = [
   { path: 'annonse/ny', component: PostFormComponent },
@@ -16,8 +15,7 @@ const routes: Routes = [
 
   { path: 'profile', component: UserProfileComponent },
   { path: 'register', component: UserRegistrationFormComponent },
-  { path: 'login', component: UserLoginFormComponent },
-  { path: 'logout', component: UserLogoutComponent }
+  { path: 'login', component: UserLoginFormComponent }
 ];
 
 @NgModule({
diff --git a/client/src/app/app.component.html b/client/src/app/app.component.html
index 81cb33f..956e369 100644
--- a/client/src/app/app.component.html
+++ b/client/src/app/app.component.html
@@ -3,10 +3,10 @@
 	<nav>
 		<span (click)="navigate('/annonse')">Annonser</span>
 		<span (click)="navigate('/annonse/ny')">Lag annonse</span>
-		<span *ngIf="!user" (click)="navigate('/register')">Registrer</span>
-		<span *ngIf="!user" (click)="navigate('/login')">Logg inn</span>
-		<span *ngIf="user" (click)="navigate('/profile')">Profil</span>
-		<span *ngIf="user" (click)="navigate('/logout')">Logg ut</span>
+		<span *ngIf="!user.getUserId" (click)="navigate('/register')">Registrer</span>
+		<span *ngIf="!user.getUserId" (click)="navigate('/login')">Logg inn</span>
+		<span *ngIf="user.getUserId" (click)="navigate('/profile')">Profil</span>
+		<span *ngIf="user.getUserId" (click)="logout()">Logg ut</span>
 	</nav>
 </div>
 <div class="splash">
diff --git a/client/src/app/app.component.ts b/client/src/app/app.component.ts
index 83a949b..df5c4ff 100644
--- a/client/src/app/app.component.ts
+++ b/client/src/app/app.component.ts
@@ -17,7 +17,7 @@ export class AppComponent implements OnInit {
   constructor(private authService: AuthService, private router: Router){}
 
   ngOnInit() {
-    this.user = this.authService.getCurrentUser();
+    this.user = this.authService.getCurrentUser(false);
     this.userSubscription = this.authService.userObservable.subscribe(user => {
       this.user = user;
     });
@@ -26,4 +26,8 @@ export class AppComponent implements OnInit {
   navigate(url) {
     this.router.navigateByUrl(url);
   }
+
+  logout() {
+    this.authService.logout();
+  }
 }
diff --git a/client/src/app/authentication/auth.service.ts b/client/src/app/authentication/auth.service.ts
index 315b898..bdc964a 100644
--- a/client/src/app/authentication/auth.service.ts
+++ b/client/src/app/authentication/auth.service.ts
@@ -22,16 +22,16 @@ export class AuthService {
 
   constructor(private http: HttpClient, private router: Router, private userService: UserService) { }
 
-  getCurrentUser(): User{
+  getCurrentUser(route=true): User{
     // Check for token expiration
-    if (this.checkTokenExpiration()) { // redirects to "/" if token is expired
+    if (this.checkTokenExpiration(route)) { // redirects to "/" if token is expired
       // Get user data from JWT token
       const token = localStorage.getItem('token');
       const user_data = JSON.parse(atob(token.split(".")[1])).data[0];
 
       return new User(user_data);
     }
-    return null;
+    return new User();
   }
 
   /**
@@ -71,7 +71,7 @@ export class AuthService {
   /**
    * Checks validity of token, redirects to homepage and removes it if it is expired
    */
-  checkTokenExpiration() {
+  checkTokenExpiration(route) {
     const token = localStorage.getItem("token");
     if (token) {
       const {iat, exp} = JSON.parse(atob(token?.split(".")[1]));
@@ -82,27 +82,31 @@ export class AuthService {
         // Expired token
         if (now < issued || now >= expires) {
           this.logout();
-          this.router.navigateByUrl("/login");
+          if (route) {
+            this.router.navigate(["/login"], {replaceUrl: true});
+          }
           return false
         }
         return true;
       }
     }
-    this.router.navigateByUrl("/login")
+    if (route) {
+      this.router.navigate(["/login"], {replaceUrl: true});
+    }
     return false
   }
 
   /**
-   * Logout an user and redirects to the homepage
+   * Logout a user and redirects to the homepage
    */
   logout() {
     localStorage.removeItem("token");
     this.router.navigateByUrl("/");
-    this.userObservable.next(null);
+    this.userObservable.next(new User());
   }
 
   /**
-   * Register an user, if not duplicate, add to database.
+   * Register a user, if not duplicate, add to database.
    */
   registerUser(user: User): Promise<string> {
     return new Promise<string>(
diff --git a/client/src/app/posts/post-details/post-details.component.ts b/client/src/app/posts/post-details/post-details.component.ts
index 35099eb..d995c98 100644
--- a/client/src/app/posts/post-details/post-details.component.ts
+++ b/client/src/app/posts/post-details/post-details.component.ts
@@ -21,7 +21,7 @@ export class PostDetailsComponent implements OnInit {
     const id = this.activatedRoute.snapshot.params["id"];
 
     // Gets ID from current user
-    this.userId = this.authService.getCurrentUser().getUserId;
+    this.userId = this.authService.getCurrentUser(false).getUserId;
 
     // Gets Post with id from database
     this.postService.getPost(id).then(post => {
@@ -42,6 +42,7 @@ export class PostDetailsComponent implements OnInit {
    * Deletes post in database and navigates to post list
    */
   deletePost() {
+    // Check if we are the owner of the post
     if (this.userId == this.post.getOwner) {
       this.postService.deletePost(this.post.getId).then(data => {
         console.log("Successfully deleted post: " + this.post.getId);
diff --git a/client/src/app/posts/post-form/post-form.component.ts b/client/src/app/posts/post-form/post-form.component.ts
index 3e9587e..3baa3d0 100644
--- a/client/src/app/posts/post-form/post-form.component.ts
+++ b/client/src/app/posts/post-form/post-form.component.ts
@@ -34,7 +34,7 @@ export class PostFormComponent implements OnInit {
     this.currentUser = this.authService.getCurrentUser();
 
     if (!this.currentUser) {
-      this.router.navigateByUrl("/login");
+      this.router.navigate(["/login"], {replaceUrl: true});
     }
 
     const id = this.activatedRoute.snapshot.params["id"];
@@ -63,7 +63,7 @@ export class PostFormComponent implements OnInit {
     this.postService.getAllCategories().then(categories => {
       this.categories = categories;
     }).catch (error => {
-      console.log("Error adding catrgories:" + error);
+      console.log("Error adding categories:" + error);
     });
   }
 
diff --git a/client/src/app/posts/post-thumbnail/post-thumbnail.component.html b/client/src/app/posts/post-thumbnail/post-thumbnail.component.html
index 5dc53d6..a2998df 100644
--- a/client/src/app/posts/post-thumbnail/post-thumbnail.component.html
+++ b/client/src/app/posts/post-thumbnail/post-thumbnail.component.html
@@ -1,3 +1,3 @@
 <div class="postthumb">
-	<a href="javascript:void(0)"(click)="goToPost()">{{post.getTitle}}</a>
+	<a href="javascript:void(0)" (click)="goToPost()">{{post.getTitle}}</a>
 </div>
diff --git a/client/src/app/users/user-login-form/user-login-form.component.ts b/client/src/app/users/user-login-form/user-login-form.component.ts
index 198c7d2..d1ea4fb 100644
--- a/client/src/app/users/user-login-form/user-login-form.component.ts
+++ b/client/src/app/users/user-login-form/user-login-form.component.ts
@@ -18,6 +18,9 @@ export class UserLoginFormComponent implements OnInit {
   constructor(private userService: UserService, private authService: AuthService, private router: Router) { }
 
   ngOnInit(): void {
+    if (this.authService.getCurrentUser(false).getUserId) {
+      this.router.navigate(["/"], {replaceUrl: true});
+    }
   }
 
   /**
diff --git a/client/src/app/users/user-logout/user-logout.component.html b/client/src/app/users/user-logout/user-logout.component.html
deleted file mode 100644
index c19d097..0000000
--- a/client/src/app/users/user-logout/user-logout.component.html
+++ /dev/null
@@ -1 +0,0 @@
-<p>user-logout works!</p>
diff --git a/client/src/app/users/user-logout/user-logout.component.scss b/client/src/app/users/user-logout/user-logout.component.scss
deleted file mode 100644
index e69de29..0000000
diff --git a/client/src/app/users/user-logout/user-logout.component.spec.ts b/client/src/app/users/user-logout/user-logout.component.spec.ts
deleted file mode 100644
index 393de0a..0000000
--- a/client/src/app/users/user-logout/user-logout.component.spec.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { ComponentFixture, TestBed } from '@angular/core/testing';
-import { HttpClientTestingModule } from '@angular/common/http/testing';
-import { RouterTestingModule } from '@angular/router/testing';
-import { UserLogoutComponent } from './user-logout.component';
-
-describe('UserLogoutComponent', () => {
-  let component: UserLogoutComponent;
-  let fixture: ComponentFixture<UserLogoutComponent>;
-
-  beforeEach(async () => {
-    await TestBed.configureTestingModule({
-      declarations: [ UserLogoutComponent ],
-      imports: [ HttpClientTestingModule, RouterTestingModule ]
-    })
-    .compileComponents();
-  });
-
-  beforeEach(() => {
-    fixture = TestBed.createComponent(UserLogoutComponent);
-    component = fixture.componentInstance;
-    fixture.detectChanges();
-  });
-
-  it('should create', () => {
-    expect(component).toBeTruthy();
-  });
-});
diff --git a/client/src/app/users/user-logout/user-logout.component.ts b/client/src/app/users/user-logout/user-logout.component.ts
deleted file mode 100644
index e0e21b8..0000000
--- a/client/src/app/users/user-logout/user-logout.component.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { Component, OnInit } from '@angular/core';
-import { AuthService } from 'src/app/authentication/auth.service';
-
-@Component({
-  selector: 'app-user-logout',
-  templateUrl: './user-logout.component.html',
-  styleUrls: ['./user-logout.component.scss']
-})
-export class UserLogoutComponent implements OnInit {
-
-  constructor(private authService: AuthService) { }
-
-  ngOnInit(): void {
-    this.authService.logout();
-  }
-
-}
diff --git a/client/src/app/users/user.module.ts b/client/src/app/users/user.module.ts
index 8d80789..2ad1ce5 100644
--- a/client/src/app/users/user.module.ts
+++ b/client/src/app/users/user.module.ts
@@ -5,16 +5,13 @@ import { FormsModule } from '@angular/forms';
 import { UserRegistrationFormComponent } from './user-registration-form/user-registration-form.component';
 import { UserProfileComponent } from './user-profile/user-profile.component';
 import { UserLoginFormComponent } from './user-login-form/user-login-form.component';
-import { UserLogoutComponent } from './user-logout/user-logout.component';
-
 
 
 @NgModule({
   declarations: [
     UserRegistrationFormComponent,
     UserProfileComponent,
-    UserLoginFormComponent,
-    UserLogoutComponent
+    UserLoginFormComponent
   ],
   imports: [
     CommonModule,
-- 
GitLab