From 6252f9ffacc414e16191e6ee44b1900d9df03e49 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Radek=20Pu=C5=A1?= <pusradek@fit.cvut.cz>
Date: Sun, 27 Oct 2019 17:17:57 +0100
Subject: [PATCH] registration compatible with auth, unused code deletion

---
 .../src/app/login/login.component.ts          | 38 +++-------------
 .../ClientApp/src/app/login/login.service.ts  | 32 +-------------
 .../registration/registration.component.ts    | 15 +++----
 .../app/registration/registration.service.ts  | 31 +++----------
 Core/Core/Controllers/ImportController.cs     | 13 ------
 Core/Core/Controllers/LoginController.cs      | 32 +-------------
 .../Controllers/RegistrationController.cs     | 38 +++-------------
 Core/Core/Controllers/SampleDataController.cs | 44 -------------------
 8 files changed, 27 insertions(+), 216 deletions(-)
 delete mode 100644 Core/Core/Controllers/SampleDataController.cs

diff --git a/Core/Core/ClientApp/src/app/login/login.component.ts b/Core/Core/ClientApp/src/app/login/login.component.ts
index c8207b2..38d3062 100644
--- a/Core/Core/ClientApp/src/app/login/login.component.ts
+++ b/Core/Core/ClientApp/src/app/login/login.component.ts
@@ -1,23 +1,18 @@
 import { Component, OnInit } from '@angular/core';
-import { HttpClient } from '@angular/common/http';
 import { LoginService } from './login.service';
 import { Router } from '@angular/router';
-import { AuthGuard } from '../auth.guard';
 
 @Component({
-    selector: 'app-login',
-    templateUrl: './login.component.html',
-    styleUrls: ['./login.component.css']
+  selector: 'app-login',
+  templateUrl: './login.component.html',
+  styleUrls: ['./login.component.css']
 })
 /** login component*/
 export class LoginComponent implements OnInit {
 
   ngOnInit() { }
 
-  constructor(private HttpClient: HttpClient,
-    private Router: Router,
-    private LoginService: LoginService
-  ) { }
+  constructor(private Router: Router, private LoginService: LoginService) { }
 
   loginUser(event): void {
     event.preventDefault();
@@ -26,33 +21,12 @@ export class LoginComponent implements OnInit {
     const target = event.target;
     const username = target.querySelector('#username').value;
     const password = target.querySelector('#password').value;
-    console.log(username, password);
-
-    if (!this.LoginService.validateInput(username, password))
-      return;
+    //console.log(username, password);
 
     this.LoginService.login(username, password).subscribe(() => {
-      console.log('loggedin:');
-      console.log(this.LoginService.IsLoggedIn);
+      console.log('Logged in: ', this.LoginService.IsLoggedIn);
       if (localStorage.getItem('loginStatus') == '1')
         this.Router.navigate(['home']);
     }, error => console.error(error));
-
-    //this.LoginService.loginUser(username, password).subscribe(data => {
-    //  console.log('subscribe' + data.item1, data.item2);
-
-    //  let token = (<any>data).token;
-    //  console.log(token);
-    //  //console.log(data.userRole);
-
-    //  if (data.item1 == 100) {//success
-    //    this.Auth.IsLoggedIn = true;
-    //    this.Router.navigate(['home']);
-    //    console.log(data);
-    //  }
-    //  else {
-    //    alert('nesprávné uživatelské jméno nebo heslo');
-    //  }
-    //  });
   }
 }
diff --git a/Core/Core/ClientApp/src/app/login/login.service.ts b/Core/Core/ClientApp/src/app/login/login.service.ts
index e501cb9..c3ce5ee 100644
--- a/Core/Core/ClientApp/src/app/login/login.service.ts
+++ b/Core/Core/ClientApp/src/app/login/login.service.ts
@@ -18,8 +18,6 @@ export class LoginService {
   }
 
   get IsLoggedIn(): Observable<boolean> {
-    console.log('LoginStatus:');
-    console.log(this.LoginStatus);
     return this.LoginStatus.asObservable();
   }
 
@@ -27,26 +25,7 @@ export class LoginService {
     return this.UserName.asObservable();
   }
 
-  constructor(private HttpClient: HttpClient,
-    private Router: Router
-  ) { }
-
-  validateInput(username: string, password: string): boolean {
-    if (username.length < 1 && password.length < 1)
-      return false;
-
-    if (username.length < 1 && (password.length > 0)) {
-      alert("Vyplňte uživatelské jméno");
-      return false;
-    }
-
-    if (username.length > 0 && password.length < 1) {
-      alert("Vyplňte heslo");
-      return false;
-    }
-
-    return true;
-  }
+  constructor(private HttpClient: HttpClient, private Router: Router) { }
 
   login(username: string, password: string) {
     return this.HttpClient.post<any>('api/Login', { username, password }).pipe(
@@ -75,14 +54,5 @@ export class LoginService {
 
   loginUser(username: string, password: string) {
     return this.HttpClient.post<{ item1: number, item2: string }>('api/Login', { username, password });
-    /*return this.HttpClent.post<{ item1: number, item2: string }>('api/Login', { username, password })
-      .toPromise()
-      .then(res => {
-        console.log(res.item1, res.item2);
-        if (res.item1 == 100) {//success
-          this.Auth.IsLoggedIn = true;
-        }
-
-      }, error => console.error(error));*/
   }
 }
diff --git a/Core/Core/ClientApp/src/app/registration/registration.component.ts b/Core/Core/ClientApp/src/app/registration/registration.component.ts
index 99370b5..5337924 100644
--- a/Core/Core/ClientApp/src/app/registration/registration.component.ts
+++ b/Core/Core/ClientApp/src/app/registration/registration.component.ts
@@ -1,6 +1,6 @@
 import { Component } from '@angular/core';
-import { HttpClient } from '@angular/common/http';
 import { RegistrationService } from './registration.service';
+import { Router } from '@angular/router';
 
 @Component({
   selector: 'app-registration',
@@ -10,11 +10,7 @@ import { RegistrationService } from './registration.service';
 /** registration component*/
 export class RegistrationComponent {
 
-  private registrationService: RegistrationService;
-
-  constructor(private httpClient: HttpClient) {
-    this.registrationService = new RegistrationService(httpClient);
-  }
+  constructor(private Router: Router, private registrationService: RegistrationService) { }
 
   registerUser(event): void {
 
@@ -26,7 +22,10 @@ export class RegistrationComponent {
     const password = target.querySelector('#password').value;
     const passwordCheck = target.querySelector('#passwordCheck').value;
 
-    var success: boolean = this.registrationService.registerUser(username, password, passwordCheck);
-    
+    this.registrationService.register(username, password, passwordCheck).subscribe((res) => {
+      console.log('Registration successful: ', res.status.toString());
+      if (res.status = 1)
+        this.Router.navigate(['login']);
+    }, error => console.error(error));
   }
 }
diff --git a/Core/Core/ClientApp/src/app/registration/registration.service.ts b/Core/Core/ClientApp/src/app/registration/registration.service.ts
index e1564da..9132a03 100644
--- a/Core/Core/ClientApp/src/app/registration/registration.service.ts
+++ b/Core/Core/ClientApp/src/app/registration/registration.service.ts
@@ -8,7 +8,7 @@ import { Observable } from 'rxjs';
 )
 export class RegistrationService {
 
-  constructor(private httpClent: HttpClient) { }
+  constructor(private HttpClient: HttpClient) { }
 
   private registrationReaction(code: number, message: string): boolean {
     switch (code) {
@@ -27,32 +27,13 @@ export class RegistrationService {
     }
   }
 
-  registerUser(username: string, password: string, passwordCheck: string) {
-
-    if (username.length < 1 && password.length < 1 && passwordCheck.length < 1)
-      return false;
-
-    if (username.length < 1 && (password.length > 0 || passwordCheck.length > 0)) {
-      alert("Vyplňte uživatelské jméno");
-      return false;
-    }
-
-    if (username.length > 0 && password.length < 1 && passwordCheck.length < 1) {
-      alert("Vyplňte heslo");
-      return false;
-    }
-
+  register(username: string, password: string, passwordCheck: string) {
+    // better safe than sorry (1. check defined in *.html)
     if (password != passwordCheck) {
-      alert("Hesla se musejĂ­ shodovat");
-      return false;
+      alert('Hesla se musejĂ­ shodovat');
+      return;
     }
 
-    //this.httpClent.post<{ item1: number, item2: string }>('api/Registration', new Credentials(username, password))
-    this.httpClent.post<{ item1: number, item2: string }>('api/Registration', {username, password})
-      .toPromise()
-      .then(res => {
-        console.log(res.item1, res.item2);
-        this.registrationReaction(res.item1, res.item2);
-      }, error => console.error(error));
+    return this.HttpClient.post<{ username: string, status: number, messasge: string }>('api/Registration', { username, password });
   }
 }
diff --git a/Core/Core/Controllers/ImportController.cs b/Core/Core/Controllers/ImportController.cs
index 08068d4..859ab03 100644
--- a/Core/Core/Controllers/ImportController.cs
+++ b/Core/Core/Controllers/ImportController.cs
@@ -14,13 +14,6 @@ namespace Core.Controllers
     [Authorize(Policy = "RequireLoggedIn")]
     public class ImportController : ControllerBase
     {
-        // GET: api/Import
-        [HttpGet]
-        public IEnumerable<string> Get()
-        {
-            return new string[] { "value1", "value2" };
-        }
-
         // GET: api/Import/5
         [HttpGet("{id}", Name = "GetImport")]
         public string Get(int id)
@@ -58,12 +51,6 @@ namespace Core.Controllers
             return Ok(new { count = files.Count, size, filePaths });
         }
 
-        // PUT: api/Import/5
-        [HttpPut("{id}")]
-        public void Put(int id, [FromBody] string value)
-        {
-        }
-
         // DELETE: api/ApiWithActions/5
         [HttpDelete("{id}")]
         public void Delete(int id)
diff --git a/Core/Core/Controllers/LoginController.cs b/Core/Core/Controllers/LoginController.cs
index 443de56..bbf70a5 100644
--- a/Core/Core/Controllers/LoginController.cs
+++ b/Core/Core/Controllers/LoginController.cs
@@ -29,19 +29,6 @@ namespace Core.Controllers
             Settings = appSettings.Value;
         }
 
-        // GET: api/Login
-        [HttpGet]
-        public IEnumerable<string> Get()
-        {
-            return new string[] { "value1", "value2" };
-        }
-
-        // GET: api/Login/5
-        //[HttpGet("{id}", Name = "GetLogin")]
-        //public (int, string) Get(CredentialContainer credentials)
-        //{
-        //}
-
         private SecurityTokenDescriptor CreateTokenDescriptor(string ID, string username)
         {
             // JWT token options
@@ -83,24 +70,7 @@ namespace Core.Controllers
             var tokenHandler = new JwtSecurityTokenHandler();
             var token = tokenHandler.CreateToken(tokenDescriptor);
 
-            return Ok(new
-            {
-                token = tokenHandler.WriteToken(token),
-                expiration = token.ValidTo,
-                username = user.Username
-            });
-        }
-
-        // PUT: api/Login/5
-        [HttpPut("{id}")]
-        public void Put(int id, [FromBody] string value)
-        {
-        }
-
-        // DELETE: api/ApiWithActions/5
-        [HttpDelete("{id}")]
-        public void Delete(int id)
-        {
+            return Ok(new { token = tokenHandler.WriteToken(token), expiration = token.ValidTo, username = user.Username });
         }
     }
 }
diff --git a/Core/Core/Controllers/RegistrationController.cs b/Core/Core/Controllers/RegistrationController.cs
index 3d3d06e..14885eb 100644
--- a/Core/Core/Controllers/RegistrationController.cs
+++ b/Core/Core/Controllers/RegistrationController.cs
@@ -4,6 +4,7 @@ using System.Linq;
 using System.Threading.Tasks;
 using Core.Controllers.containers;
 using Core.Data;
+using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 
@@ -11,6 +12,7 @@ namespace Core.Controllers
 {
     [Route("api/[controller]")]
     [ApiController]
+    //[AllowAnonymous]
     public class RegistrationController : ControllerBase
     {
         private readonly Model Context;
@@ -19,47 +21,19 @@ namespace Core.Controllers
             Context = context;
         }
 
-        // GET: api/Registration
-        [HttpGet]
-        public IEnumerable<string> Get()
-        {
-            return new string[] { "value1", "value2" };
-        }
-
-        // GET: api/Registration/5
-        [HttpGet("{id}", Name = "GetRegistration")]
-        public string Get(int id)
-        {
-            return "value";
-        }
-
         // POST: api/Registration
         [HttpPost]
-        public (int, string) Post([FromBody] CredentialContainer credentials)
+        public IActionResult Post([FromBody] CredentialContainer credentials)
         {
             Console.WriteLine($"username: {credentials.username}, password: {credentials.password}");
 
-            //unique constraint
-            //ITaskResult: return BadRequest (new JsonResult(errorList));
-            //ModelState.AddModelError("",error.Description);
+            //defensive 
             if (Context.Users.Any(u => u.Username == credentials.username))
-                return (400, "Bad Request: username already exist");
+                return BadRequest(new { credentials.username, status = 0, message = "Username already exist" });
 
             Context.Users.Add(new Models.User(credentials.username, credentials.password));
             Context.SaveChanges();
-            return (201, "Created");//return Ok(new{username = user.Username, status=1, message = Registration Successful"});
-        }
-
-        // PUT: api/Registration/5
-        [HttpPut("{id}")]
-        public void Put(int id, [FromBody] string value)
-        {
-        }
-
-        // DELETE: api/ApiWithActions/5
-        [HttpDelete("{id}")]
-        public void Delete(int id)
-        {
+            return Ok(new { credentials.username, status = 1, message = "Registration Successful" });
         }
     }
 }
diff --git a/Core/Core/Controllers/SampleDataController.cs b/Core/Core/Controllers/SampleDataController.cs
deleted file mode 100644
index 906aa5f..0000000
--- a/Core/Core/Controllers/SampleDataController.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Mvc;
-
-namespace Core.Controllers
-{
-    [Route("api/[controller]")]
-    public class SampleDataController : Controller
-    {
-        private static string[] Summaries = new[]
-        {
-            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
-        };
-
-        [HttpGet("[action]")]
-        public IEnumerable<WeatherForecast> WeatherForecasts()
-        {
-            var rng = new Random();
-            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
-            {
-                DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
-                TemperatureC = rng.Next(-20, 55),
-                Summary = Summaries[rng.Next(Summaries.Length)]
-            });
-        }
-
-        public class WeatherForecast
-        {
-            public string DateFormatted { get; set; }
-            public int TemperatureC { get; set; }
-            public string Summary { get; set; }
-
-            public int TemperatureF
-            {
-                get
-                {
-                    return 32 + (int)(TemperatureC / 0.5556);
-                }
-            }
-        }
-    }
-}
-- 
GitLab