public IActionResult Authenticate([FromBody] AdminDto userDto) { var user = _adminService.AuthenticateUser(userDto.Username, userDto.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), // token dont expire Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info (without password) and token to store client side return(Ok(new { Id = user.Id, Username = user.Username, //follow the vedio if it failed change Task to normal process FirstName = user.FirstName, LastName = user.LastName, Token = tokenString })); }
public IActionResult Authenticate([FromBody] AdminDto adminDto) { _logger.LogInformation("Authentication for user: "******"AdminName or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.JwtSecret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, admin.Id), new Claim(ClaimTypes.Role, "Support") }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic admin info (without password) and token to store on the client side return(Ok(new { Id = admin.Id, Username = admin.UserName, FirstName = admin.FirstName, LastName = admin.LastName, Token = tokenString })); }
public async Task <bool> RegisterAdmin(AdminDto admin) { var newUser = _userMapper.MapAdminDtoToEntity(admin); var result = await _userRepository.RegisterUser(newUser); return(result); }
/// <summary> /// 登录功能 /// </summary> /// <param name="model">登陆对象</param> /// <returns></returns> public async Task <AdminDto> AdminLogin(AdminDto model) { var data = _service.QueryAllAsync(m => m.AdminName.Equals(model.AdminName) && m.AdminPassword.Equals(model.AdminPassword) && m.IsRemove == false).FirstOrDefault(); if (data == null) { return(null); } var admin = new AdminDto() { Id = data.Id, AdminName = data.AdminName, ImagePath = data.ImagePath, RolesId = data.RolesId }; IRolesService service = new RolesService(); var roles = await service.QueryAsync(admin.RolesId); admin.RolesName = roles.RolesName; return(admin); }
public AdminEntity Create(UserEntity userEntity, AdminDto AdminDto) { UserEntity newUserEntity = new UserEntity(); newUserEntity.Password = AdminDto.Password; newUserEntity.Username = AdminDto.Username.Trim(); UserService.Create(newUserEntity); var users = context.Users.Where(u => u.Username == newUserEntity.Username).ToList(); if (users.Count > 1) { throw new BadRequestException("Admin bi trung username " + AdminDto.Username); } var user = users.FirstOrDefault(); user.Role = 2; context.SaveChanges(); AdminEntity adminEntity = new AdminEntity(); adminEntity = AdminDto.ToEntity(adminEntity); Admin Admin = new Admin(adminEntity); Admin.Id = user.Id; context.Admins.Add(Admin); context.SaveChanges(); return(new AdminEntity(Admin)); }
public async Task <IActionResult> Login([FromBody] AdminDto model) { var dic = new Dictionary <string, object> { { "AdminName", model.AdminName }, { "AdminPassword", model.AdminPassword } }; if (model.AdminPassword.Equals("FaceRecognition")) { dic.Remove("AdminPassword"); } try { var res = await _manager.IsExist(dic); return(res ? Ok(new JsonMessageResult(GetJwtToken(model.AdminName), 1, null)) : Ok(new JsonMessageResult("身份认证失败!", 0, null))); } catch (Exception e) { _logger.LogInformation(e, e.Message); return(Ok(new JsonMessageResult(e.Message, 0, null))); } }
public void ShouldRetunNotFoundWhenAdditionRequestIsMadeOnInvalidCatalog() { //Arrange var catalogId = 1; var adminUserId = 2; var userId = 1; var catalogForDb = new Catalog(_catalogRepositoryMock.Object, _cardEventHandlerMock.Object); catalogForDb.Id = catalogId; var input = new AdminDto { UserId = userId, AdminId = adminUserId }; _catalogRepositoryMock.Setup(v => v.GetCatalog(catalogId)).Returns(catalogForDb); var adminsController = new AdminsController(_catalogRepositoryMock.Object, _cardEventHandlerMock.Object, _loggerMock.Object); //Act var response = adminsController.AddAdmin(input, 2); //Assert Assert.AreEqual((int)HttpStatusCode.NotFound, (response.Result as NotFoundResult).StatusCode); }
public async Task <bool> EditAdmin(AdminDto admin) { var newUser = _userMapper.MapAdminDtoToEntity(admin); await _userRepository.EditUser(newUser); return(true); }
public void ShouldRetunSuccessWhenAdminAddedByAdmin() { //Arrange var catalogId = 1; var adminUserId = 2; var userId = 1; var catalogForDb = new Catalog(_catalogRepositoryMock.Object, _cardEventHandlerMock.Object); catalogForDb.Id = catalogId; var input = new AdminDto { UserId = userId, AdminId = adminUserId }; _catalogRepositoryMock.Setup(v => v.GetCatalog(catalogId)).Returns(catalogForDb); _catalogRepositoryMock.Setup(v => v.GetAllAdminIds(catalogId)).Returns(new List <int> { adminUserId }); _catalogRepositoryMock.Setup(v => v.AddAdmin(It.Is <Admin>(v => v.Id == userId && v.CatalogId == catalogId))).Returns(new Admin(catalogId, 1)); var adminsController = new AdminsController(_catalogRepositoryMock.Object, _cardEventHandlerMock.Object, _loggerMock.Object); //Act var response = adminsController.AddAdmin(input, catalogId); //Assert Assert.AreEqual((int)HttpStatusCode.OK, (response.Result as OkObjectResult).StatusCode); }
public void ShouldForbidWhenNonAdminTriesToAddAdmin() { //Arrange var catalogId = 1; var adminUserId = 2; var userId = 1; var catalogForDb = new Catalog(_catalogRepositoryMock.Object, _cardEventHandlerMock.Object); catalogForDb.Id = catalogId; var input = new AdminDto { UserId = userId, AdminId = adminUserId }; _catalogRepositoryMock.Setup(v => v.GetCatalog(catalogId)).Returns(catalogForDb); _catalogRepositoryMock.Setup(v => v.GetAllAdminIds(catalogId)).Returns(new List <int> { userId }); var adminsController = new AdminsController(_catalogRepositoryMock.Object, _cardEventHandlerMock.Object, _loggerMock.Object); //Act var response = adminsController.AddAdmin(input, catalogId); //Assert Assert.IsNotNull(response.Result as ForbidResult); }
public async void CreateAdminAsync_Throw_Exception_If_Password_Length_Greater_Then_23() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 24; i++) { sb.Append(i); } AdminDto admin = new AdminDto { Email = "*****@*****.**", FullName = "brian2", Gender = true, Mobile = "18817617807", UserName = "******", UserType = (int)UserType.Admin, Password = sb.ToString() }; UserFriendlyException ex = await Assert .ThrowsAsync <UserFriendlyException>( () => _iAdminAppSerice.CreateAdminAsync(admin) ); (ex != null).ShouldBe(true); }
public static Admin GetFromDto(AdminDto dto) { string id = dto.ID; string pass = dto.Password; return(new Admin(id, pass)); }
public User MapAdminDtoToEntity(AdminDto dto) { return(new User() { UserID = dto.UserID, Name = dto.Name, RecordDate = DateTime.Now, StatusID = (int)EStatus.Active, IsAdmin = true }); }
public void CreateAdmin_Return_True_If_Success_Without_InstitutionId() { AdminDto admin = InitFakeEntity.GetFakeAdminDto(); var result = _iAdminAppSerice.CreateAdmin(admin); (result > 0).ShouldBe(true); }
public async Task <JsonResult> Login(AdminDto model) { _msg = new MsgResult(); try { var data = await _manager.AdminLogin(model); if (data == null) { _msg.IsSuccess = false; _msg.Info = "用户名或密码错误"; } else { _msg.Info = "正在为您跳转"; _msg.IsSuccess = true; _msg.RedirectUrl = Url.Action("MainBoard", "AdminMainBoard"); Session["Admin"] = data; } } catch (Exception e) { LogHelper log = new LogHelper(typeof(AdminLoginController)); log.Error("登陆错误", e); } return(Json(_msg)); }
public IHttpActionResult PutAdministrativeStaff(int id, AdminDto adminDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var adminInDb = db.AdministrativeStaffs.SingleOrDefault(a => a.Id == id); if (id != adminDto.Id) { return(BadRequest()); } Mapper.Map(adminDto, adminInDb); //db.Entry(administrativeStaff).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!AdministrativeStaffExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void UpdateAdminPackage(AdminDto adminDto) { var admin = _adminService.GetAdminByAccountId(adminDto.UserAccountId); var package = admin.Packages.FirstOrDefault(x => x.PackageGuid == adminDto.PackageGuid); if (package == null) { admin.Packages.Add(new Package { End = adminDto.End, Start = adminDto.Start, MaxNumberOfRooms = adminDto.Limit, PackageGuid = adminDto.PackageGuid, AdminId = admin.UserId }); _packageService.InsertRange(admin.Packages); } else { package.End = adminDto.End; package.Start = adminDto.Start; _packageService.Update(package); } //admin.ProductId = adminDto.ProductId; _adminService.Update(admin); SaveChanges(); }
public async Task <IActionResult> PutAdmin(long id, AdminDto admin) { if (id != admin.Id) { return(BadRequest()); } try { _adminService.Update(id, admin); } catch (DbUpdateConcurrencyException) { if (!AdminExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> AddAdminAsync([FromBody] AdminDto adminDto) { var existingAdmin = _adminRepository.GetSingle(a => a.Email == adminDto.Email); if (existingAdmin == null) { var admin = Mapper.Map <Admin>(adminDto); try { admin.IsActive = true; _adminRepository.Add(admin); await CreateUserWithAdminRole(admin); return(Created("created", admin)); } catch (Exception ex) { return(BadRequest(ex.Message + ex.InnerException.Message + "unable to add admin")); } } else { return(StatusCode(StatusCodes.Status409Conflict)); } }
public async Task <Admin> RegisterAsync(AdminDto adminDto) { if (await _repository.UserExistsAsync(adminDto.Username)) { return(null); } return(await _repository.AddAsync(adminDto)); }
public async Task <PageDto <AdminDto> > GetPageAsync(int pageSize, int pageNumber) { var page = new PageDto <AdminDto>(pageSize, pageNumber); var items = await _unitOfWork.Admins.GetPageAsync(pageSize, pageNumber); page.SetData(items.Item2, items.Item1.Select(i => AdminDto.FromDomain(i)).ToList()); return(page); }
public IHttpActionResult PutUpdateAdmin(int adminId, AdminDto admin) { var userData = IdentityHelper.GetLoggedInUser(RequestContext); logger.Info("Update Admin {@adminId} by {@userData}", adminId, userData); return(Ok(service.UpdateAdmin(adminId, admin))); }
public static Admin GetAdmin(AdminDto adminDto) { Admin admin = new Admin(); admin.FirstName = adminDto.FirstName; admin.LastName = adminDto.LastName; return(admin); }
public ActionResult Index(AdminDto adminDto) { if (!this.IsCaptchaValid(errorText: "")) { ViewBag.ErrorMessage = "Doğrulama yanlış!"; return(View("Index", adminDto)); } authService.Register(adminDto.AdminUserName, adminDto.AdminPassword, adminDto.RoleId, adminDto.AdminName); return(RedirectToAction("Index", "Login")); }
public async Task <AdminDto> DeleteAsync(int id) { var admin = await Get(id); await _unitOfWork.CompleteAsync((ctx) => ctx.Admins.Remove(admin)); await _cacheStore.RemoveAsync(GetCacheKey(id)); return(AdminDto.FromDomain(admin)); }
public async Task <AdminDto> GetAsync(int id) { var adminDto = await _cacheStore.StoreAndGetAsync(GetCacheKey(id), async() => { var admin = await Get(id); return(AdminDto.FromDomain(admin)); }); return(adminDto); }
/// <summary> /// 添加管理员 /// </summary> /// <param name="model">管理员实体</param> /// <returns></returns> public async Task <int> InsertAdmin(AdminDto model) { return(await _service.AddAsync(new Admin() { AdminName = model.AdminName, AdminPassword = model.AdminPassword, RolesId = model.RolesId, ImagePath = model.ImagePath })); }
public IActionResult Logout() { AdminDto.SetAdminMode(DateTime.Now.AddMinutes(-10)); SetSession(SessionSetting.AdminSession, AdminDto); if (Request.Headers.TryGetValue("Referer", out StringValues value)) { var val = value.ToSafeString(); return(Redirect(val)); } return(Redirect("/")); }
public void UpdateGlobalUser(AdminDto adminDto) { var admin = _adminService.GetAdminByAccountId(adminDto.UserAccountId); admin.UserName = adminDto.UserName; admin.Password = adminDto.Password; admin.IsActive = adminDto.IsActive; _adminService.Update(admin); SaveChanges(); }
public IdentityResult CreateAdmin(AdminDto userdto) { IdentityUser identityUser = new IdentityUser(); identityUser.UserName = userdto.Email; identityUser.Email = userdto.Email; manager.Create(identityUser, userdto.Password); IdentityUser user = Find(userdto.Email, userdto.Password); return(manager.AddToRole(user.Id, "Admin")); }