Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Chat.Enums;
- using Chat.Identity;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Primitives;
- namespace _Chat.Controllers
- {
- public class HomeController : Controller
- {
- private AuthenticateUser authenticateUser = new AuthenticateUser();
- public async Task<IActionResult> Index()
- {
- var request = Request;
- var headers = request.Headers;
- StringValues token;
- if (headers.TryGetValue("Authorization", out token))
- {
- var result = await this.authenticateUser.ValidateToken(token);
- if (result.Result == AuthenticateResult.Success)
- {
- return View();
- }
- else
- {
- return RedirectToAction("Index", "Account");
- }
- }
- return RedirectToAction("Index", "Account");
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Chat.Models;
- using Chat.DatabaseAccessObject;
- using Chat.Identity;
- using Chat.DatabaseAccessObject.CommandObjects;
- using System.Linq.Expressions;
- using System.Net.Mime;
- using System.Security.Claims;
- using System.Text;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.IdentityModel.Tokens;
- namespace Chat.Controllers
- {
- public class AccountController : Controller
- {
- private const string SECRET_KEY = "CHATSECRETKEY";
- public static SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
- private ServerToStorageFacade serverToStorageFacade = new ServerToStorageFacade();
- private AuthenticateUser authenticateUser = new AuthenticateUser();
- public IActionResult Index()
- {
- return View();
- }
- // Post: /login/
- [HttpPost]
- public async Task<IActionResult> Login([FromBody]LoginModel loginModel)
- {
- if (ModelState.IsValid)
- {
- var mapLoginModelToUser = new MapLoginModelToUser();
- var user = await mapLoginModelToUser.MapObject(loginModel);
- // If login user with those credentials does not exist
- if(user == null)
- {
- return BadRequest();
- }
- else
- {
- var result = await this.authenticateUser.Authenticate(user);
- if(result.Result == Chat.Enums.AuthenticateResult.Success)
- {
- // SUCCESSFUL LOGIN
- // Creating and storing cookies
- var token = Json(new
- {
- data = this.GenerateToken(user.Email, user.PantherID),
- redirectUrl = Url.Action("Index","Home"),
- success = true
- });
- return Ok(token);
- }
- else
- {
- // Unsuccessful login
- return Unauthorized();
- }
- }
- }
- return BadRequest();
- }
- private string GenerateToken(string email, string pantherId)
- {
- var claimsData = new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Actor, pantherId) };
- var signInCredentials = new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256);
- var token = new JwtSecurityToken(
- issuer: "localhost",
- audience: "localhost",
- expires: DateTime.Now.AddDays(7),
- claims: claimsData,
- signingCredentials: signInCredentials
- );
- return new JwtSecurityTokenHandler().WriteToken(token);
- }
- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
- public async Task<IActionResult> Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
- public class MapLoginModelToUser
- {
- private ServerToStorageFacade serverToStorageFacade;
- public MapLoginModelToUser()
- {
- serverToStorageFacade = new ServerToStorageFacade();
- }
- public async Task<User> MapObject(LoginModel loginModel)
- {
- Expression<Func<User, bool>> expression = x => x.Email == loginModel.inputEmail;
- var user = await this.serverToStorageFacade.ReadObjectByExpression(new User(Guid.NewGuid()), expression);
- if(user == default(Command))
- {
- return null;
- }
- return new User(user.ID)
- {
- Email = loginModel.inputEmail,
- Password = loginModel.inputPassword,
- FirstName = user.FirstName,
- LastName = user.LastName,
- PantherID = user.PantherID,
- ClassDictionary = user.ClassDictionary,
- UserEntitlement = user.UserEntitlement
- };
- }
- }
- }
- $(document).ready(function () {
- $("#formSubmit").submit(function (event) {
- event.preventDefault();
- var email = $("#inputEmail").val();
- var password = $("#inputPassword").val();
- var remember = $("#rememberMe").val();
- var loginModel = {
- inputEmail: email,
- inputPassword: password,
- rememberMe: remember
- };
- $.ajax({
- type: 'POST',
- url: 'Account/Login',
- data: JSON.stringify(loginModel),
- contentType: 'application/json; charset=utf-8;',
- success: function (response) {
- var token = response.value.data;
- localStorage.setItem("token", token);
- alert("You have successfully logged in.");
- setHeader();
- redirect(response.value.redirectUrl);
- }
- });
- });
- function setHeader() {
- $.ajaxSetup({
- beforeSend: function (xhr) {
- xhr.setRequestHeader('Authorization', localStorage.getItem("token"));
- }
- });
- }
- function redirect(redirectUrl) {
- $.ajax({
- type: 'GET',
- contentType: 'application/json; charset=utf-8;',
- url: redirectUrl,
- success: function (response) {
- $("html").html(response);
- }
- });
- }
- });
Add Comment
Please, Sign In to add comment