· 7 years ago · Oct 08, 2018, 07:30 PM
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5using Chat.Enums;
6using Chat.Identity;
7using Microsoft.AspNetCore.Authorization;
8using Microsoft.AspNetCore.Mvc;
9using Microsoft.Extensions.Primitives;
10
11namespace _Chat.Controllers
12{
13 public class HomeController : Controller
14 {
15 private AuthenticateUser authenticateUser = new AuthenticateUser();
16
17 public async Task<IActionResult> Index()
18 {
19 var request = Request;
20 var headers = request.Headers;
21
22 StringValues token;
23 if (headers.TryGetValue("Authorization", out token))
24 {
25 var result = await this.authenticateUser.ValidateToken(token);
26 if (result.Result == AuthenticateResult.Success)
27 {
28 return View();
29 }
30 else
31 {
32 return RedirectToAction("Index", "Account");
33 }
34 }
35
36 return RedirectToAction("Index", "Account");
37 }
38 }
39}
40
41using System;
42using System.Collections.Generic;
43using System.Diagnostics;
44using System.IdentityModel.Tokens.Jwt;
45using System.Linq;
46using System.Threading.Tasks;
47using Microsoft.AspNetCore.Mvc;
48using Chat.Models;
49using Chat.DatabaseAccessObject;
50using Chat.Identity;
51using Chat.DatabaseAccessObject.CommandObjects;
52using System.Linq.Expressions;
53using System.Net.Mime;
54using System.Security.Claims;
55using System.Text;
56using Microsoft.AspNetCore.Authentication;
57using Microsoft.IdentityModel.Tokens;
58
59namespace Chat.Controllers
60{
61 public class AccountController : Controller
62 {
63 private const string SECRET_KEY = "CHATSECRETKEY";
64 public static SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
65 private ServerToStorageFacade serverToStorageFacade = new ServerToStorageFacade();
66 private AuthenticateUser authenticateUser = new AuthenticateUser();
67
68 public IActionResult Index()
69 {
70 return View();
71 }
72
73 // Post: /login/
74 [HttpPost]
75 public async Task<IActionResult> Login([FromBody]LoginModel loginModel)
76 {
77 if (ModelState.IsValid)
78 {
79 var mapLoginModelToUser = new MapLoginModelToUser();
80 var user = await mapLoginModelToUser.MapObject(loginModel);
81
82 // If login user with those credentials does not exist
83 if(user == null)
84 {
85 return BadRequest();
86 }
87
88 else
89 {
90 var result = await this.authenticateUser.Authenticate(user);
91
92 if(result.Result == Chat.Enums.AuthenticateResult.Success)
93 {
94 // SUCCESSFUL LOGIN
95 // Creating and storing cookies
96
97 var token = Json(new
98 {
99 data = this.GenerateToken(user.Email, user.PantherID),
100 redirectUrl = Url.Action("Index","Home"),
101 success = true
102 });
103 return Ok(token);
104 }
105 else
106 {
107 // Unsuccessful login
108 return Unauthorized();
109 }
110 }
111 }
112
113 return BadRequest();
114 }
115
116 private string GenerateToken(string email, string pantherId)
117 {
118 var claimsData = new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Actor, pantherId) };
119
120 var signInCredentials = new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256);
121 var token = new JwtSecurityToken(
122 issuer: "localhost",
123 audience: "localhost",
124 expires: DateTime.Now.AddDays(7),
125 claims: claimsData,
126 signingCredentials: signInCredentials
127 );
128
129 return new JwtSecurityTokenHandler().WriteToken(token);
130 }
131
132 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
133 public async Task<IActionResult> Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
134 }
135
136 public class MapLoginModelToUser
137 {
138 private ServerToStorageFacade serverToStorageFacade;
139
140 public MapLoginModelToUser()
141 {
142 serverToStorageFacade = new ServerToStorageFacade();
143 }
144
145
146 public async Task<User> MapObject(LoginModel loginModel)
147 {
148 Expression<Func<User, bool>> expression = x => x.Email == loginModel.inputEmail;
149
150 var user = await this.serverToStorageFacade.ReadObjectByExpression(new User(Guid.NewGuid()), expression);
151
152 if(user == default(Command))
153 {
154 return null;
155 }
156
157 return new User(user.ID)
158 {
159 Email = loginModel.inputEmail,
160 Password = loginModel.inputPassword,
161 FirstName = user.FirstName,
162 LastName = user.LastName,
163 PantherID = user.PantherID,
164 ClassDictionary = user.ClassDictionary,
165 UserEntitlement = user.UserEntitlement
166 };
167 }
168 }
169}
170
171$(document).ready(function () {
172 $("#formSubmit").submit(function (event) {
173 event.preventDefault();
174 var email = $("#inputEmail").val();
175 var password = $("#inputPassword").val();
176 var remember = $("#rememberMe").val();
177 var loginModel = {
178 inputEmail: email,
179 inputPassword: password,
180 rememberMe: remember
181 };
182
183 $.ajax({
184 type: 'POST',
185 url: 'Account/Login',
186 data: JSON.stringify(loginModel),
187 contentType: 'application/json; charset=utf-8;',
188 success: function (response) {
189 var token = response.value.data;
190 localStorage.setItem("token", token);
191 alert("You have successfully logged in.");
192 setHeader();
193 redirect(response.value.redirectUrl);
194 }
195 });
196 });
197
198 function setHeader() {
199 $.ajaxSetup({
200 beforeSend: function (xhr) {
201 xhr.setRequestHeader('Authorization', localStorage.getItem("token"));
202 }
203 });
204 }
205
206 function redirect(redirectUrl) {
207 $.ajax({
208 type: 'GET',
209 contentType: 'application/json; charset=utf-8;',
210 url: redirectUrl,
211 success: function (response) {
212 $("html").html(response);
213 }
214 });
215 }
216});