From 274de94f9533b89a9800251847991856b92f445d Mon Sep 17 00:00:00 2001
From: Jonny Ngo Luong <jonnynl@stud.ntnu.no>
Date: Tue, 23 Feb 2021 21:23:39 +0100
Subject: [PATCH] =?UTF-8?q?refactor:=20lagt=20til=20kommentarer=20der=20de?=
 =?UTF-8?q?t=20er=20n=C3=B8dvendig=20i=20frontend?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 client/src/app/authentication/auth.service.ts | 19 +++++--
 .../user-login-form.component.ts              | 16 ++----
 .../user-profile/user-profile.component.ts    |  3 +-
 .../user-registration-form.component.ts       |  8 +--
 client/src/app/users/user.service.spec.ts     | 50 -------------------
 client/src/app/users/user.service.ts          |  4 +-
 6 files changed, 27 insertions(+), 73 deletions(-)

diff --git a/client/src/app/authentication/auth.service.ts b/client/src/app/authentication/auth.service.ts
index ce40111..2d2fa6d 100644
--- a/client/src/app/authentication/auth.service.ts
+++ b/client/src/app/authentication/auth.service.ts
@@ -18,6 +18,9 @@ export class AuthService {
 
   constructor(private http: HttpClient, private router: Router) { }
 
+  /**
+   * Logins an user, if given correct combination of username and password.
+   */
   login(body: IUserLogin): Promise<string> {
     return new Promise<string>(
       (resolve, reject) => {
@@ -36,14 +39,20 @@ export class AuthService {
     );
   }
   private login_user(body: IUserLogin) {
+    // Pipes output to setSession function if a valid user is returned
     return this.http.post(this.loginUrl, body).pipe(
         tap(res =>this.setSession(res)),
-        shareReplay());;
+        shareReplay());
   }
+  // Set authentication token on localStorage if a valid user is received
   private setSession(authResult) {
     console.log(authResult);
     localStorage.setItem('token', authResult.token);
   }
+
+  /**
+   * Checks validity of token, redirects to homepage and removes it if it is expired
+   */
   checkTokenExpiration() {
     const token = localStorage.getItem("token");
     if (token) {
@@ -64,11 +73,16 @@ export class AuthService {
     this.router.navigateByUrl("/")
     return false
   }
+
+  /**
+   * Logout an user and redirects to the homepage
+   */
   logout() {
     localStorage.removeItem("token");
+    this.router.navigateByUrl("/");
   }
 
-    /**
+  /**
    * Register an user, if not duplicate, add to database.
    */
   registerUser(user: User): Promise<string> {
@@ -88,7 +102,6 @@ export class AuthService {
       }
     );
   }
-
   private register_user(user: User) {
     return this.http.post(this.registrationUrl, user.serialize());
   }
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 328d380..3f4cefd 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
@@ -21,7 +21,7 @@ export class UserLoginFormComponent implements OnInit {
   }
 
   /**
-   * Validates form.
+   * Validates the form
    */
   checkForm(): boolean {
     if (this.username == "") {
@@ -38,7 +38,7 @@ export class UserLoginFormComponent implements OnInit {
   }
 
   /**
-   * Login the user if it is valid.
+   * Login the user if it is valid
    */
   loginUser() {
     if (this.checkForm()) {
@@ -47,26 +47,18 @@ export class UserLoginFormComponent implements OnInit {
         password: this.password,
       };
 
-      // Login the user
+      // Logins the user
       this.authService.login(request).then(status => {
         console.log("User login1: " + JSON.stringify(status));
         this.router.navigateByUrl("/");
       }).catch(error => {
         console.log("Error user login: " + error);
       });
-      /* Old
-      this.userService.login(request).then(status => {
-        console.log("User login2: " + JSON.stringify(status));
-        this.router.navigateByUrl("/");
-      }).catch(error => {
-        console.log("Error adding user: " + error);
-      });
-      */
     }
   }
 
   /**
-   * Sets a status message.
+   * Sets the status message
    */
   setStatusMessage(message: string) {
     this.statusMessage = message;
diff --git a/client/src/app/users/user-profile/user-profile.component.ts b/client/src/app/users/user-profile/user-profile.component.ts
index 53be4cc..ce10985 100644
--- a/client/src/app/users/user-profile/user-profile.component.ts
+++ b/client/src/app/users/user-profile/user-profile.component.ts
@@ -18,9 +18,10 @@ export class UserProfileComponent implements OnInit {
   ngOnInit(): void {
     // Check for token expiration
     if (this.authService.checkTokenExpiration()) { // redirects to "/" if token is expired
+    // Get user data from JWT token
       const token = localStorage.getItem('token');
-      // Get user data from JWT token
       const user_data = JSON.parse(atob(token.split(".")[1])).data[0];
+      
       // Gets all user information and displays them in the component
       this.userService.getUser(user_data.userId).then(user => {
         this.user = user;
diff --git a/client/src/app/users/user-registration-form/user-registration-form.component.ts b/client/src/app/users/user-registration-form/user-registration-form.component.ts
index 25cf7f6..bfd0eec 100644
--- a/client/src/app/users/user-registration-form/user-registration-form.component.ts
+++ b/client/src/app/users/user-registration-form/user-registration-form.component.ts
@@ -22,7 +22,7 @@ export class UserRegistrationFormComponent implements OnInit {
   }
 
   /**
-   * Validates form.
+   * Validates the form
    */
   checkForm(): boolean {
     if (this.username == "") {
@@ -43,7 +43,7 @@ export class UserRegistrationFormComponent implements OnInit {
   }
 
   /**
-   * Publishes user if it is valid.
+   * Publishes and registers the user if given arguments are valid
    */
   registerUser() {
     if (this.checkForm()) {
@@ -53,7 +53,7 @@ export class UserRegistrationFormComponent implements OnInit {
         password: this.password,
       });
 
-      // Adds user to database and changes page afterwards
+      // Adds user to database and redirects to the homepage afterwards
       this.authService.registerUser(newUser).then(status => {
         console.log("User was added: " + JSON.stringify(status));
         this.router.navigateByUrl("/");
@@ -64,7 +64,7 @@ export class UserRegistrationFormComponent implements OnInit {
   }
 
   /**
-   * Sets a status message.
+   * Sets the status message for user feedback on form submit
    */
   setStatusMessage(message: string) {
     this.statusMessage = message;
diff --git a/client/src/app/users/user.service.spec.ts b/client/src/app/users/user.service.spec.ts
index 4896330..e0577bf 100644
--- a/client/src/app/users/user.service.spec.ts
+++ b/client/src/app/users/user.service.spec.ts
@@ -76,55 +76,5 @@ describe('UserService', () => {
       });
     });
   
-    describe('addUser', () => {
-      it('should add an user', () => {
-        const user = new User({
-            userId: 1,
-            username: "zorg",
-            email: "blob@planet.us",
-            password: "Hyttepine",
-            create_time: 1613552549000,
-        });
-  
-        // Adds user
-        service.addUser(user)
-        .then(post => {})
-        .catch(error => {
-          fail();
-        });
-  
-        // Mocks and checks HTTP request
-        const req = httpMock.expectOne("api/user/");
-        expect(req.request.method).toBe("POST");
-        expect(req.request.body).toEqual(user.serialize());
-        req.flush({
-          data: [{
-            status: "success"
-          }]
-        });
-      });
-  
-      it('should reject on http error', () => {
-        const user = new User({
-            userId: 1,
-            username: "zorg",
-            email: "blob@planet.us",
-            password: "Hyttepine",
-            create_time: 1613552549000,
-        });
-  
-        // Adds user, gets HTTP error, should catch
-        service.addUser(user).then(user => {
-          fail();
-        }).catch(error => {});
-  
-        // Mocks and checks HTTP request
-        const req = httpMock.expectOne("api/user/");
-        expect(req.request.method).toBe("POST");
-        expect(req.request.body).toEqual(user.serialize());
-        req.error(new ErrorEvent("400"));
-      });
-    });
-  
 });
 
diff --git a/client/src/app/users/user.service.ts b/client/src/app/users/user.service.ts
index b56d038..f4def23 100644
--- a/client/src/app/users/user.service.ts
+++ b/client/src/app/users/user.service.ts
@@ -16,7 +16,7 @@ export class UserService {
   constructor(private http: HttpClient) { }
 
   /**
-   * Get user from database by id.
+   * Get an user from the database by id.
    */
   getUser(id: number): Promise<User> {
     return new Promise<User>(
@@ -40,7 +40,6 @@ export class UserService {
       }
     );
   }
-
   private get_user(id: number) {
     return this.http.get(this.userUrl + id);
   }
@@ -74,7 +73,6 @@ export class UserService {
       }
     );
   }
-
   private get_all_users() {
     return this.http.get(this.userUrl);
   }
-- 
GitLab