private async Task <dynamic> GetToken(LoggedInUserVM data) { var claims = new List <Claim>() { new Claim(ClaimTypes.Name, data.FirstName), new Claim(ClaimTypes.NameIdentifier, data.UserName), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()) }; foreach (var role in data.Roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } var token = new JwtSecurityToken( new JwtHeader( new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("thisIsOnlyForTestingAndWillBeReplaced")), SecurityAlgorithms.HmacSha256) ), new JwtPayload(claims) ); var tokenOutput = new { id = data.Id, userName = data.UserName, firstName = data.FirstName, lastName = data.LastName, mailId = data.MailId, contactNumber = data.ContactNumber, roles = data.Roles, token = new JwtSecurityTokenHandler().WriteToken(token), }; return(tokenOutput); }
public IActionResult loggedinuser() { var currentUser = HttpContext.User; Int32 userId = Convert.ToInt32(currentUser.Claims.FirstOrDefault(c => c.Type == "user_id").Value); LoggedInUser objLoggedInUser = new LoggedInUser(); LoggedInUserVM custobj = new LoggedInUserVM(); string loggedInUser = string.Empty; try { var data = _dbContext.LoginCredentials.FirstOrDefault(q => q.UserId == userId); custobj = new LoggedInUserVM(); custobj = _mapper.Map <LoggedInUserVM>(data); if (custobj != null) { string folderName = "Images"; string webRootPath = _hostingEnvironment.WebRootPath; string imagename = data.ProfileImage; var domain = _configuration["DevImageDomain"]; if (imagename != null) { string uploadFilesPath = Path.Combine(webRootPath, folderName, imagename); if (System.IO.File.Exists(uploadFilesPath)) { custobj.ProfileImageURL = string.Format("{0}/Images/{1}", domain, imagename); } } } } catch (Exception) { } return(Ok(custobj)); }
public PartialViewResult Navigation() { // first, get the userId var userId = User.Identity.GetUserId(); var rolesList = RoleManager.Roles.OrderBy(y => y.Index).ToList(); var roleName = ""; var currentIndex = 0; var roleGroupIndex = 0; foreach (var role in rolesList) { if (UserManager.IsInRole(userId, role.Name)) { roleName = role.Name; roleGroupIndex = role.RoleGroup.Index; currentIndex = role.Index; } } UserVM = new LoggedInUserVM { UserID = userId, RoleIndex = currentIndex, UserRole = roleName, RoleGroupIndex = roleGroupIndex, HasPassword = UserManager.HasPassword(userId) }; return(PartialView("navigationPartial", UserVM)); }
public async Task <IActionResult> Create([FromBody] UserVM data) { if (data != null) { try { if (_context.Users.FirstOrDefault(e => data.email == e.Email) != null) { return(Conflict()); } else { User user = new User(); user.FirstName = data.first_name.Trim(); user.LastName = data.last_name.Trim(); user.HashedPassword = PasswordConverter.Encrypt(data.password); user.Email = data.email.Trim(); _context.Users.Add(user); await _context.SaveChangesAsync(); LoggedInUserVM viewModel = GetUserInfoFromEmail(data.email); return(Ok(viewModel)); } } catch { throw new System.Web.Http.HttpResponseException(System.Net.HttpStatusCode.InternalServerError); } } else { return(NoContent()); } }
private LoggedInUserVM GetUserInfoFromUser(User user) { LoggedInUserVM viewModel = new LoggedInUserVM(); viewModel.first_name = user.FirstName; viewModel.last_name = user.LastName; viewModel.id = user.Id; return(viewModel); }
public async Task <IActionResult> GetUserInfo() { var signedInUserId = new Guid(User.Identity.Name); var userInfo = await _userService.GetUserInfoAsync(signedInUserId); if (userInfo == null) { return(BadRequest()); } var newAuthToken = _securityService.GenerateAuthToken(userInfo); var loggedInUser = new LoggedInUserVM(userInfo, newAuthToken); return(Ok(loggedInUser)); }
public async Task <IActionResult> Register([FromBody] UserCreationVM model) { if (model == null || !ModelState.IsValid) { return(BadRequest("Invalid user creation data.")); } model.Password = _securityService.EncryptPassword(model.Password); var user = await _userService.CreateUserAsync(model); if (user == null) { return(BadRequest("Username is not unique.")); } var authToken = _securityService.GenerateAuthToken(user); var loggedInUser = new LoggedInUserVM(user, authToken); return(Ok(loggedInUser)); }
public async Task <IActionResult> Login([FromBody] LoginVM model) { var user = await _userService.GetUserByLoginDataAsync(model); if (user == null) { return(BadRequest("Invalid username or password.")); } bool passwordCorrect = _securityService.VerifyPassword(model.Password, user.Password); if (!passwordCorrect) { return(BadRequest("Invalid username or password.")); } var authToken = _securityService.GenerateAuthToken(user); var loggedInUser = new LoggedInUserVM(user, authToken); return(Ok(loggedInUser)); }
[HttpGet] // ännu ej implementerad public IActionResult Settings() { var aspNetId = _userManager .GetUserId(HttpContext.User); var userEmail = _identityContext.Users .FirstOrDefault(x => x.Id == aspNetId) .Email; var userName = _identityContext.Users .FirstOrDefault(x => x.Id == aspNetId) .UserName; LoggedInUserVM loggedInUserVM = new LoggedInUserVM { AspNetId = aspNetId, Username = userName, Email = userEmail }; return(View(loggedInUserVM)); }
public IActionResult Login([FromBody] LogInAttempt data) { if (data.email != null && data.password != null) { try { var user = _context.Users.FirstOrDefault(a => a.Email == data.email); if (user != null) { string hashedPasswordAttempt = PasswordConverter.Encrypt(data.password); var actualPassword = user.HashedPassword; if (actualPassword == hashedPasswordAttempt) { LoggedInUserVM viewModel = GetUserInfoFromUser(user); return(Ok(viewModel)); } else { return(Unauthorized()); } } else { return(NotFound()); } } catch { throw new System.Web.Http.HttpResponseException(System.Net.HttpStatusCode.InternalServerError); } } else { return(NoContent()); } }