public JsonModel Login(ApplicationUserDTO applicationUser, JwtIssuerOptions _jwtOptions) { // check user by Username User dbuser = iUserRepository.GetFirstOrDefault(a => a.UserName == applicationUser.UserName); if (dbuser != null) { // get User info Staffs staff = iStaffRepository.GetFirstOrDefault(a => a.UserID == dbuser.Id); if (staff == null) { return(new JsonModel(null, StatusMessage.StaffInfoNotFound, (int)HttpStatusCodes.NotFound)); } // check user active or inactive else if (staff.IsActive == false) { return(new JsonModel(null, StatusMessage.AccountDeactivated, (int)HttpStatusCodes.Unauthorized)); } else { // check username and password var identity = GetClaimsIdentity(applicationUser, dbuser); if (identity != null) { return(LoginUser(applicationUser, _jwtOptions, dbuser, staff, identity)); } } } return(new JsonModel(null, StatusMessage.InvalidUserOrPassword, (int)HttpStatusCodes.Unauthorized)); }
public async Task <IActionResult> AddUserRole([FromBody] ApplicationUserDTO userDTO) { if (!ModelState.IsValid) { _logger.LogError("ModelState is invalid in the AddUserRole() method"); return(BadRequest(ModelState)); } var foundUser = await userManager.FindByIdAsync(userDTO.Id); if (foundUser == null) { _logger.LogWarning("User not found in the AddUserRole() method"); return(NotFound()); } var roleResult = await userManager.AddToRoleAsync(foundUser, userDTO.Roles.LastOrDefault()); if (roleResult.Succeeded) { await signInManager.SignInAsync(foundUser, isPersistent : false); } _logger.LogInformation("Creating role to user in the AddUserRole() method"); return(NoContent()); }
private OrderCreateBindingModel CreateOrderCreateBindingModel(ApplicationUserDTO user) { return(new OrderCreateBindingModel() { FirstName = user.FirstName, LastName = user.LastName, PhoneNumber = user.PhoneNumber }); }
public async Task <Result> CreateAsync(ApplicationUserDTO userDto) { ApplicationUser user = await Database.UserManager.FindByEmailAsync(userDto.Email); if (user == null) { user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email }; var result = await Database.UserManager.CreateAsync(user, userDto.Password); if (result.Errors.Count() > 0) { return(new Result(false, result.Errors.FirstOrDefault(), "")); } await Database.UserManager.AddToRoleAsync(user.Id, userDto.Role); ApplicationProfile clientProfile = new ApplicationProfile { Id = user.Id, Name = userDto.ApplicationProfile.Name, Balance = userDto.ApplicationProfile.Balance, CreditCard = userDto.ApplicationProfile.CreditCard }; user.ApplicationProfile = clientProfile; var list = Database.UserManager.Users.ToList(); await Database.SaveAsync(); return(new Result(true, $"User {userDto.Email} has been registered", "")); } else { return(new Result(false, $"The user with {userDto.Email} is already registered", "Email")); } }
public async Task <ApplicationUserDTO> GetUser(string userId) { ApplicationUserDTO result = null; try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("gooiosapikey", "6de960be9183367800160026c7e9f3d2"); var reqUrl = $"https://authservice.gooios.com/api/user?userid={userId}"; var res = await client.GetAsync(reqUrl); if (res.IsSuccessStatusCode) { var resultStr = await res.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <ApplicationUserDTO>(resultStr); } } } catch (Exception ex) { } return(result); }
public ActionResult <ApplicationUserDTO> PostUser(ApplicationUserDTO userDTO) { if (userDTO.password?.Trim() != userDTO.passwordRepeat?.Trim()) { throw new Exception("Passwords do not match!"); } if (userDTO.username == null || userDTO.username?.Trim() == "") { throw new Exception("No username provided!"); } var manager = ServiceLocator.Current.GetInstance <IMiniSessionService>(); var repo = new Repository(manager); var applicationUser = new ApplicationUser(); applicationUser.UserName = userDTO.username; applicationUser.Name = userDTO.name; applicationUser.Email = userDTO.email; applicationUser.PhoneNumber = userDTO.phoneNumber; string possibleError = zAppDev.DotNet.Framework.Identity.IdentityHelper.CreateUser(applicationUser, (userDTO.password?.Trim() ?? "")); if ((((possibleError == null || possibleError == "")) == false)) { throw new Exception("Something Went Wrong"); } foreach (var roleDTO in userDTO.roles) { var role = repo.GetById <ApplicationRole>(roleDTO.Id); applicationUser.AddRoles(role); } repo.Save <ApplicationUser>(applicationUser); manager.Session.Flush(); return(CreatedAtAction("PostUser", new { id = applicationUser.UserName })); }
private ApplicationUserDTO CreateUser(ApplicationUser user) { if (user == null) { return(null); } string id = user.Id; string firstName = user.FirstName; string lastName = user.LastName; string origin = user.Origin; if (firstName == null || lastName == null) { return(null); } ApplicationUserDTO userDTO = new ApplicationUserDTO { Id = id, FirstName = firstName, LastName = lastName, Origin = origin, //AssignedUsers, //Quizes, //Scores //TO DO }; return(userDTO); }
public static ApplicationUserDTO ApplicationUserDTOMapper(IdentityModels.ApplicationUser applicationUser) { var applicationUserDto = new ApplicationUserDTO { UserId = applicationUser.Id, CreateDate = applicationUser.CreateDate, AccessFailedCount = applicationUser.AccessFailedCount, DisplayName = applicationUser.DisplayName, Email = applicationUser.Email, EmailConfirmed = applicationUser.EmailConfirmed, Status = applicationUser.Status, LockoutEnabled = applicationUser.LockoutEnabled, LockoutEndDateUtc = applicationUser.LockoutEndDateUtc, PasswordHash = applicationUser.PasswordHash, PhoneNumber = applicationUser.PhoneNumber, PhoneNumberConfirmed = applicationUser.PhoneNumberConfirmed, SecurityStamp = applicationUser.SecurityStamp, TwoFactorEnabled = applicationUser.TwoFactorEnabled, UserName = applicationUser.UserName, IsAdmin = applicationUser.IsAdmin, IsCustomizedAccess = applicationUser.IsCustomizedAccess, }; return(applicationUserDto); }
public async Task <IActionResult> LoginEmpresa(LoginUser loginUser) { try { var result = await signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Secret, false, false); if (!result.Succeeded) { return(BadRequest("Acesso negado! Login inválido!")); } var user = userManager.FindByNameAsync(loginUser.Email); var claimsPrincipal = await signInManager.CreateUserPrincipalAsync(user.Result); var claims = claimsPrincipal.Claims.ToList(); var permissions = claims.Where(c => c.Type.Contains("role")).Select(c => c.Value).ToList(); if (permissions.Where(x => x.Contains("Master")).Any()) { return(BadRequest("Acesso negado! Usuário é Master!")); } var applicationUserDTO = new ApplicationUserDTO(); var empresa = empresaRepository.Get(genericRepository.Where(x => x.ApplicationUserId == user.Result.Id).FirstOrDefault().EmpresaId); applicationUserDTO.Token = TokenService.GenerateToken(user.Result, configuration, empresa, permissions); applicationUserDTO.Email = user.Result.Email; applicationUserDTO.UserName = user.Result.UserName; applicationUserDTO.NomeEmpresa = string.Concat(empresa.Id.ToString(), " - ", empresa.Nome); return(new JsonResult(applicationUserDTO)); } catch (Exception ex) { return(BadRequest("Falha no login! " + ex.Message)); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { ApplicationUserDTO userDto = new ApplicationUserDTO { Email = model.Email, Password = model.Password }; ClaimsIdentity claim = await IdentityService.Authenticate(userDto); if (claim == null) { ModelState.AddModelError("", "Email or password is invalid."); } else { AuthenticationManager.SignOut(); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claim); return(RedirectToAction("Profile", "Market")); } } return(View(model)); }
public ActionResult <ApplicationUser> CreateAdmin(ApplicationUserDTO userDTO) { if (userDTO.password?.Trim() != userDTO.passwordRepeat?.Trim()) { throw new Exception("Passwords do not match!"); } if (userDTO.username?.Trim() == "") { throw new Exception("No username provided!"); } var adminUser = new ApplicationUser(); adminUser.UserName = (userDTO.username?.Trim() ?? ""); string possibleError = zAppDev.DotNet.Framework.Identity.IdentityHelper.CreateUser(adminUser, (userDTO.password?.Trim() ?? "")); if ((((possibleError == null || possibleError == "")) == false)) { throw new Exception("Something Went Wrong"); } var repo = new Repository(); var adminRole = repo.GetAsQueryable <ApplicationRole>((r) => r.Name == "Administrator")?.FirstOrDefault(); if ((adminRole == null)) { throw new Exception("No Administrator role found in Database!"); } var appAdminUser = repo.GetAsQueryable <ApplicationUser>(a => a.UserName == userDTO.username).FirstOrDefault(); appAdminUser.AddRoles(adminRole); repo.Save(appAdminUser); return(CreatedAtAction("CreateAdmin", new { id = adminUser.UserName }, adminUser)); }
public async Task <IActionResult> Update([FromBody] ApplicationUserDTO userDto) { ApplicationUserDTO applicationUserDto = await this.Service.UpdateAsync(userDto, this.HostingEnvironment.WebRootPath); return(Ok(applicationUserDto)); }
public string CreateOrder(OrderCreateBindingModel model, ApplicationUserDTO user) { List <OrderProduct> orderProducts = new List <OrderProduct>(); var shoppingCartProducts = this.shoppingCartService.FindAllDomainShoppingCartProducts(user.UserName).ToList(); if (shoppingCartProducts.Count == 0) { return(string.Empty); } var country = this.FindCountryByName(model.Country); var order = this.MapOrderAndSetNewId(model, user, country); orderProducts = this.CreateOrderProductsFromShoppingCartProducts(orderProducts, shoppingCartProducts, order); order.OrderProducts = orderProducts; order.TotalPrice = this.CalculateTotalPrice(order); this.dbContext.OrderProducts.AddRange(orderProducts); this.dbContext.Orders.Add(order); this.dbContext.SaveChanges(); return(order.Id); }
private JsonModel LoginUser(ApplicationUserDTO applicationUser, JwtIssuerOptions _jwtOptions, User dbuser, Staffs userInfo, ClaimsIdentity identity) { // initialize claims for jwt token var claims = new[] { new System.Security.Claims.Claim("UserName", applicationUser.UserName.ToString()), new System.Security.Claims.Claim("UserID", dbuser.Id.ToString()), new System.Security.Claims.Claim("StaffID", userInfo.Id.ToString()), new System.Security.Claims.Claim("OrganizationID", dbuser.OrganizationID.ToString()), new System.Security.Claims.Claim("RoleID", userInfo.RoleID.ToString()), new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, applicationUser.UserName), new System.Security.Claims.Claim(JwtRegisteredClaimNames.Jti, _jwtOptions.JtiGenerator()), identity.FindFirst("HealthCare") }; // initilize jwt params var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); // Genrate Jwt token var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new JsonModel { access_token = encodedJwt, data = "User Authenticated", }; return(response); }
public async Task <object> DeleteAsync(string userId) { var model = await this.userManager.FindByIdAsync(userId); if (model != null) { model.IsDeleted = true; model.UpdatedDate = Converters.GetCurrentEpochTime(); await this.userManager.UpdateAsync(model); ApplicationUserDTO modelDTO = Mapper.Map <ApplicationUser, ApplicationUserDTO>(model); this.DisplayMessage = CommonMethods.GetMessage(LogType.User, LogAction.Delete); return(model); } else { this.IsSuccess = false; this.ErrorMessages = new List <ErrorMessageDTO>() { new ErrorMessageDTO() { Message = "User not found with user id " + userId } }; return(null); } }
public async Task <IActionResult> Login(LoginUser loginUser) { try { var result = await signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Secret, false, false); if (!result.Succeeded) { return(BadRequest("Acesso negado! Login inválido!")); } var user = await userManager.FindByEmailAsync(loginUser.Email); var claimsPrincipal = await signInManager.CreateUserPrincipalAsync(user); var claims = claimsPrincipal.Claims.ToList(); var permissions = claims.Where(c => c.Type.Contains("role")).Select(c => c.Value).ToList(); if (!permissions.Where(x => x.Contains("Master")).Any()) { return(BadRequest("Acesso negado! Usuário não é Master!")); } var applicationUser = new ApplicationUser(); applicationUser.Id = user.Id; var applicationUserDTO = new ApplicationUserDTO(); applicationUserDTO.Token = TokenService.GenerateToken(applicationUser, configuration, permissions); applicationUserDTO.Email = user.Email; applicationUserDTO.UserName = user.UserName; return(new JsonResult(applicationUserDTO)); } catch (Exception ex) { return(BadRequest("Falha no login! " + ex.Message)); } }
//[ValidateAntiForgeryToken] public async Task <JsonResult> Login(LoginModel model) { await SetInitialDataAsync(); if (ModelState.IsValid) { ApplicationUserDTO userDto = new ApplicationUserDTO { Email = model.Email, Password = model.Password }; ClaimsIdentity claim = await userService.Authenticate(userDto); if (claim == null) { return(Json("Wrong email or password", JsonRequestBehavior.AllowGet)); } else { AuthenticationManager.SignOut(); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claim); userDto = await userService.GetUser(userDto); return(Json(userDto, JsonRequestBehavior.AllowGet)); } } return(Json(model)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { IApplicationUserService serviceUser = _container.Resolve <IApplicationUserService>(); ApplicationUserDTO request = new ApplicationUserDTO(); request.Email = context.UserName; request.Password = context.Password; ApplicationUserDTO response = serviceUser.AuthenticateUser(request); if (response == null) { context.SetError("invalid_grant", "Usuário não encontrado!"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); //Definindo as Claims identity.AddClaim(new Claim("Usuario", JsonConvert.SerializeObject(response))); var principal = new GenericPrincipal(identity, new string[] { }); Thread.CurrentPrincipal = principal; context.Validated(identity); } catch (Exception ex) { context.SetError("invalid_grant", ex.Message); return; } }
public async Task <IActionResult> GetApplicationUsers() { var manager = ServiceLocator.Current.GetInstance <IMiniSessionService>(); var repo = new Repository(manager); var users = repo.GetAll <ApplicationUser>(); var results = new List <ApplicationUserDTO>(); foreach (var user in users) { var userDto = new ApplicationUserDTO { email = user.Email, name = user.Name, username = user.UserName, phoneNumber = user.PhoneNumber }; results.Add(userDto); } return(Ok(new { value = results } )); }
//POST : api/ApplicationUser/Registro public async Task <Object> PostApplicationUser(ApplicationUserDTO model) { model.Role = "Invitado"; var applicationuser = new ApplicationUser() { UserName = model.UserName, Email = model.Email, FullName = model.FullName, }; try { var result = await _userManager.CreateAsync(applicationuser, model.Password); if (result.Succeeded == true) { await _userManager.AddToRoleAsync(applicationuser, model.Role); return(Ok(result)); } else { return(BadRequest(result.Errors)); } } catch (Exception ex) { throw ex; } }
private FavouriteList FindFavouriteListByUserId(ApplicationUserDTO user) { var favouriteList = this.dbContext.FavouriteLists .FirstOrDefault(x => x.UserId == user.Id); return(favouriteList); }
private ShoppingCart FindShoppingCartByUserId(ApplicationUserDTO user) { var userCart = this.dbContext.ShoppingCarts .FirstOrDefault(x => x.User.Id == user.Id); return(userCart); }
/// <summary> /// Create Jwt token for the given user. /// </summary> /// <param name="user"></param> /// <returns></returns> public string GetJwtToken(ApplicationUserDTO user) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("JwtKey").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays(Convert.ToInt32(_configuration.GetSection("JwtExpireDays").Value)); var tokenTemplate = new JwtSecurityToken( "MySite", "MySite", claims, expires: expires, signingCredentials: creds ); var token = new JwtSecurityTokenHandler().WriteToken(tokenTemplate); var jsonFormatedToken = JsonSerializer.Serialize(token); return(jsonFormatedToken != null ? jsonFormatedToken : null); }
public async Task <ActionResult> Login(LoginViewModel model) { await SetInitialDataAsync(); if (ModelState.IsValid) { ApplicationUserDTO applicationUserDTO = new ApplicationUserDTO { Email = model.Email, Password = model.Password }; ClaimsIdentity claim = await ApplicationUserService.Authenticate(applicationUserDTO); if (claim == null) { ModelState.AddModelError("", "Неверный логин или пароль."); } else { AuthenticationManager.SignOut(); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claim); return(RedirectToAction("Index", "Home")); } } return(View(model)); }
public async Task <Object> Register(ApplicationUserDTO applicationUserDto) { var result = await _registrationService.Register(applicationUserDto); Log.Information("register completed!"); return(Ok(result)); }
public async Task <ActionResult> Register(RegisterViewModel model) { await SetInitialDataAsync(); if (ModelState.IsValid) { ApplicationUserDTO applicationUserDTO = new ApplicationUserDTO { Email = model.Email, Password = model.Password, //Address = model.Address, //Name = model.Name, RolesID = { 1 } }; OperationDetails operationDetails = await ApplicationUserService.Create(applicationUserDTO); if (operationDetails.Succedeed) { return(View("SuccessRegister")); } else { ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } } return(View(model)); }
public async Task <IdentityResult> Register(ApplicationUserDTO user) { try { ApplicationUser applicationUser = _mapper.Map <ApplicationUserDTO, ApplicationUser>(user); var identityResult = await _userManager.CreateAsync(applicationUser, user.Password).ConfigureAwait(false); if (identityResult.Succeeded) { await _userManager.AddClaimsAsync(applicationUser, new List <Claim>() { new Claim("email", applicationUser.Email) }).ConfigureAwait(false); await _userManager.AddToRolesAsync(applicationUser, new List <string>() { "admin" }) .ConfigureAwait(false); // Define user roles on registration } return(identityResult); } catch (Exception ex) { _logger.LogError(ex, nameof(Register)); throw; } }
public string GenerateAccessToken(ApplicationUserDTO user, string refreshToken) { var claims = new List <Claim> { new Claim(ClaimKeys.UserId, user.Id.ToString()), new Claim(ClaimKeys.FirstName, user.FirstName), new Claim(ClaimKeys.LastName, user.LastName), new Claim(ClaimKeys.Email, user.Email), new Claim(ClaimKeys.PhoneNumber, user.PhoneNumber), new Claim(ClaimKeys.DateOfBirth, user.DateOfBirth.ToString()), new Claim(ClaimKeys.City, user.City), new Claim(ClaimKeys.ExpiresTime, DateTime.Now.AddMinutes(Constants.MinToExpireAccessToken).ToString()), new Claim(ClaimKeys.RefreshToken, refreshToken), new Claim(ClaimKeys.Country, user.Country) }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Authorization", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var now = DateTime.Now; var jwt = new JwtSecurityToken(issuer: _authOptions.ISSUER, audience: _authOptions.AUDIENCE, notBefore: now, claims: claimsIdentity.Claims, expires: now.Add(TimeSpan.FromMinutes(_authOptions.LIFETIME)), signingCredentials: new SigningCredentials(_authOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); return(_tokenHandler.WriteToken(jwt)); }
public ApplicationUserDTO Create(ApplicationUserDTO user, string password) { if (_userRepository.GetAll().Any(u => u.Email == user.Email)) { throw new HttpStatusCodeException( HttpStatusCode.UnprocessableEntity, "Such user already exists"); } user.SettingsId = _settingsRepository.GetSettingsByPhoneId(user.PhoneIdentifier).SettingsId; user.Id = _userRepository.GetAll().First(u => u.PhoneIdentifier == user.PhoneIdentifier).AccountId; _userRepository.UpdateUser(new ApplicationUserModel { City = user.City, Country = user.Country, DateOfBirth = Convert.ToDateTime(user.DateOfBirth).Date, Email = user.Email, FirstName = user.FirstName, Id = user.Id, LastName = user.LastName, PasswordHash = PasswordGenerators.CreatePasswordHash(password), SettingsId = user.SettingsId.Value, PhoneNumber = user.PhoneNumber, PhoneIdentifier = user.PhoneIdentifier, ValidationCode = user.ValidationCode, CodeCreationTime = user.CodeCreationTime }); _theaterScheduleUnitOfWork.Save(); return(user); }
public async Task <IActionResult> UpdateAppUser(string appUserId, [FromBody] ApplicationUserDTO appUser) { if (appUserId != appUser.Id) { return(BadRequest()); } _wrapper.AppUserRepository.UpdateAppUser(_mapper.Map <AppUser>(appUser)); try { await _wrapper.SaveAsync(); } catch (DbUpdateConcurrencyException e) { if (!await AppUserExists(appUserId)) { return(NotFound()); } else { return(BadRequest(e.Message)); } } return(Ok()); }