public async Task <Models.Database.User> Index() { var characterId = Int32.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var characterInfo = await esiClient.Character.GetCharacterPublicInfoV4Async(characterId); var corporationInfo = await esiClient.Corporation.GetCorporationInfoV4Async((int)characterInfo.Model.CorporationId); var auth = new AuthDTO { AccessToken = new AccessTokenDetails { AccessToken = User.FindFirst("AccessToken").Value, ExpiresUtc = DateTime.Parse(User.FindFirst("AccessTokenExpiry").Value), RefreshToken = User.FindFirst("RefreshToken").Value }, CharacterId = characterId, Scopes = User.FindFirst("Scopes").Value }; var locationInfo = await esiClient.Location.GetCharacterLocationV1Async(auth); var location = await esiClient.Universe.GetSolarSystemInfoV4Async(locationInfo.Model.SolarSystemId); var mining = await esiClient.Industry.CharacterMiningLedgerV1Async(auth); var model = new Models.Database.User { CharacterName = characterInfo.Model.Name, CorporationName = corporationInfo.Model.Name, CharacterLocation = location.Model.Name, CharacterMining = mining }; return(model); }
public AuthDTO CreateUser(AuthDTO authDto) { byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } string saltHash = Encoding.Unicode.GetString(salt); string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: authDto.Password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8 )); var user = new User() { Email = authDto.Email, Username = new Regex("@.+").Replace(authDto.Email, ""), Password = hashed, Salt = saltHash, Role = "User" }; _context.Users.Add(user); _context.SaveChanges(); authDto.Id = _context.Users.FirstOrDefault(u => u.Email == authDto.Email).Id; authDto.Role = "User"; return(authDto); }
public IActionResult Authorize(AuthDTO authDto) { if (!ModelState.IsValid) { _logger.LogWarning(HttpStatusCode.BadRequest.ToString()); return(BadRequest(HttpStatusCode.BadRequest)); } var user = _authManager.Authenticate(authDto.Email.ToLower(), authDto.Password); if (user == null) { _logger.LogWarning(HttpStatusCode.NotFound.ToString()); return(NotFound(HttpStatusCode.NotFound)); } var claimsIdentity = _authManager.SignIn(user); if (claimsIdentity == null) { _logger.LogWarning(HttpStatusCode.NotFound.ToString()); return(Unauthorized(HttpStatusCode.NotFound)); } var token = _tokenService.CreateAuthToken(claimsIdentity); return(Ok(new { token })); }
public IActionResult Login([FromBody] AuthDTO auth) { JwtSecurityToken token; DateTime expiration; var llave = Encoding.UTF8.GetBytes(Config["Tokens:Key"]); var key = new SymmetricSecurityKey(llave); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new Claim[] { new Claim(ClaimTypes.Sid, auth.Guid), new Claim(ClaimTypes.Role, auth.Role), new Claim("Organization", auth.Organization) }; token = new JwtSecurityToken(Config["Tokens:Issuer"], Config["Tokens:Issuer"], claims, expires: DateTime.Now.AddDays(1), signingCredentials: creds); string tokenHandler = new JwtSecurityTokenHandler().WriteToken(token); expiration = token.ValidTo; return(Ok(tokenHandler)); }
public LoggedUser Execute(AuthDTO request) { var user = Context.Users .Include(u => u.Role) .Where(u => u.Username == request.Username) .Where(u => u.Password == request.Password) .FirstOrDefault(); if (user == null || user.IsDeleted) { throw new EntityNotFoundException("User"); } return(new LoggedUser { FirstName = user.FirstName, LastName = user.LastName, Id = user.Id, IsLogged = true, Role = user.Role.Name, Username = user.Username }); }
public AuthDTO CheckAuthData(AuthDTO authDto) { var user = _context.Users.FirstOrDefault(u => u.Email == authDto.Email); if (user == null) { return(null); } var salt = Encoding.Unicode.GetBytes(user.Salt); string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: authDto.Password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8 )); if (user.Password != hashed) { authDto = null; } else { authDto.Role = user.Role; authDto.Id = user.Id; } return(authDto); }
public async Task <IdentityResult> RegisterUser(AuthDTO userModel) { IdentityUser user = new IdentityUser { UserName = userModel.Email }; _ctx.Clients.Add(new Client() { Id = Guid.NewGuid(), FirstName = userModel.FirstName, Surname = userModel.Surname, Email = userModel.Email, BirthDate = userModel.BirthDate, DriverLicenseNumber = userModel.DriverLicenseNumber }); var result = await _userManager.CreateAsync(user, userModel.Password); await _userManager.AddToRoleAsync(user.Id, "user"); await _ctx.SaveChangesAsync(); return(result); }
public async Task <IActionResult> Login(AuthDTO model) { if (!IsValidApiRequest()) { return(ApiBadRequest("Invalid headers!")); } var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(ApiBadRequest("User does not exist.")); } var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, false, lockoutOnFailure : false); if (result.IsLockedOut) { return(ApiBadRequest("User account locked out.")); } if (!result.Succeeded) { return(ApiBadRequest("Invalid username or password.")); } return(Ok(new { token = _jwt.GenerateSecurityToken(new User() { Username = user.UserName, Email = user.Email }) })); }
public ActionResult Main(LoginDTO loginDTO) { String chatChannel = ConfigurationHelper.ChatChannel; String textToSpeechChannel = ConfigurationHelper.TextToSpeechChannel; String authKey = loginDTO.Username + DateTime.Now.Ticks.ToString(); var chatManager = new ChatManager(); if (loginDTO.ReadAccessOnly) { chatManager.GrantUserReadAccessToChannel(authKey, chatChannel); } else { chatManager.GrantUserReadWriteAccessToChannel(authKey, chatChannel); } chatManager.GrantUserReadWriteAccessToChannel(authKey, textToSpeechChannel); var authDTO = new AuthDTO() { PublishKey = ConfigurationHelper.PubNubPublishKey, SubscribeKey = ConfigurationHelper.PubNubSubscribeKey, AuthKey = authKey, Username = loginDTO.Username, ChatChannel = chatChannel, TextToSpeechChannel = textToSpeechChannel }; return(View(authDTO)); }
public void ShouldAuthenticate() { Mock <IUserRepository> userRepositoryMock = new Mock <IUserRepository>(); Mock <ICryptoService> cryptoServiceMock = new Mock <ICryptoService>(); Mock <IConfiguration> configurationMock = new Mock <IConfiguration>(); var mapper = TestHelper.GetMapper(); var authData = new AuthDTO { Email = "*****@*****.**", Password = "******" }; var key = "1a78sd8a7s8d7aysda87s23"; configurationMock.Setup(x => x[It.IsAny <string>()]).Returns(() => key); userRepositoryMock.Setup(x => x.GetByEmail(It.IsAny <string>())).Returns(new User { Email = authData.Email }); cryptoServiceMock.Setup(x => x.VerifyPassword(It.IsAny <string>(), It.IsAny <string>())).Returns(true); var sut = new AuthService(cryptoServiceMock.Object, userRepositoryMock.Object, configurationMock.Object, mapper); var result = sut.Authenticate(authData); Assert.NotNull(result); Assert.NotNull(result.User); Assert.Null(result.User.Password); Assert.Equal(authData.Email, result.User.Email); Assert.NotEmpty(result.Token); }
public IActionResult Auth(AuthDTO authDTO) { VResult result = new VResult() { Code = ReturnCode.FAIL }; if (!ModelState.IsValid) { result.Msg = "参数有误"; return(new JsonResult(result)); } var userInfo = this.AuthAppService.Auth(authDTO.Username, authDTO.Password, authDTO.VCode); if (userInfo != null) { result.Code = ReturnCode.SUCCESS; result.Data = this.SecurityService.CreateToken(userInfo.Id, userInfo.NickName, userInfo.Mobile); result.Msg = "授权成功"; } else { result.Msg = "授权失败"; } return(new JsonResult(result)); }
public async Task <IActionResult> Registration(AuthDTO authDTO) { var users = shopContext.Users.ToList(); foreach (var user in users) { if (user.PhoneNumber == authDTO.PhoneNumber) { return(BadRequest()); } } var responseDTO = await twilioSmsService.SendVerificationCode(authDTO.PhoneNumber); if (responseDTO == null) { return(BadRequest("Сообщение не отправлено")); } if (authDTO.Code != responseDTO.VerificationCode) { return(BadRequest("Код введен не верно")); } shopContext.Users.AddRange(new User { PhoneNumber = authDTO.PhoneNumber, VerificationCode = authDTO.Code }); shopContext.SaveChanges(); return(Ok("Пользователь создан")); }
/// <summary> /// Authenticates user and generates JWT token. /// </summary> /// <param name="authDto">DTO containing authentication data.</param> /// <param name="token">JWT token (generated when user passed valid login and password, otherwise null).</param> /// <returns>True if user has been authenticated with success, otherwise false.</returns> public bool LogIn(AuthDTO authDto, out string token) { var hashedPassword = HashPassword(authDto.Password); var user = _userRepository.GetByUserNameAndPassword(authDto.UserName, hashedPassword); if (user == null) { token = null; return(false); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_settings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var tokenContainer = tokenHandler.CreateToken(tokenDescriptor); token = tokenHandler.WriteToken(tokenContainer); return(true); }
public async Task <IActionResult> SignIn(AuthDTO authDTO) { var user = await context.Users.SingleOrDefaultAsync(x => x.PhoneNumber == authDTO.PhoneNumber); if (user == null) { return(BadRequest()); } if (string.IsNullOrWhiteSpace(authDTO.VerificationCode)) { Random random = new Random(); var code = random.Next(1000, 9999).ToString(); user.VerificationCode = code; await smsService.SendVerificationCode(user.PhoneNumber, user.VerificationCode); return(Ok("We sent a verification code on your phone. Please send it back with your next request")); } else { if (authDTO.VerificationCode == user.VerificationCode) { user.VerificationCode = ""; return(Ok(userService.Authenticate(user.PhoneNumber))); } else { return(BadRequest("Invalid verification code")); } } }
public async Task <IActionResult> Index() { var characterId = Int32.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var characterInfo = await esiClient.Character.GetCharacterPublicInfoV4Async(characterId); var corporationInfo = await esiClient.Corporation.GetCorporationInfoV4Async((int)characterInfo.Model.CorporationId); var auth = new AuthDTO { AccessToken = new AccessTokenDetails { AccessToken = User.FindFirstValue("AccessToken"), ExpiresUtc = DateTime.Parse(User.FindFirstValue("AccessTokenExpiry")), RefreshToken = User.FindFirstValue("RefreshToken") }, CharacterId = characterId, Scopes = User.FindFirstValue("Scopes") }; var locationInfo = await esiClient.Location.GetCharacterLocationV1Async(auth); var location = await esiClient.Universe.GetSolarSystemInfoV3Async(locationInfo.Model.SolarSystemId); var model = new SecurePageViewModel { CharacterName = characterInfo.Model.Name, CorporationName = corporationInfo.Model.Name, CharacterLocation = location.Model.Name }; return(View(model)); }
public TokenDTO Authenticate(AuthDTO authData) { var validator = new AuthDataValidator(); var validationResult = validator.Validate(authData); if (!validationResult.IsValid) { throw new ValidationException(validationResult.Errors); } var user = _userRepository.GetByEmail(authData.Email); if (user == null) { throw new NotFoundException("Usuário não encontrado ou senha inválida"); } var valid = _cryptoService.VerifyPassword(user.Password, authData.Password); if (!valid) { throw new NotFoundException("Usuário não encontrado ou senha inválida"); } var tokenData = new TokenDTO { User = _mapper.Map <User, UserDTO>(user), Token = GenerateToken(user) }; return(tokenData); }
public async Task <IActionResult> Assets() { AuthDTO auth = GetAuth(_ESIClient); _Log.LogDebug(String.Format("Logged in to retrieve Character Info for Character Id: {0}", auth.CharacterId)); List <AssetDataModel> assets = new List <AssetDataModel>(); List <Asset> assets_api = new List <Asset>(); var assetsApi = await _ESIClient.Assets.GetCharacterAssetsV3Async(auth, 1); var assetsApiModel = assetsApi.Model; assets_api = assetsApiModel; if (assetsApi.MaxPages > 1) { for (int x = 2; x < assetsApi.MaxPages; x++) { assetsApi = await _ESIClient.Assets.GetCharacterAssetsV3Async(auth, x); assets_api.AddRange(assetsApi.Model); } } // Get all ItemTypes, Systems, and Stations at once (quicker) List <int> itemTypeIds = assets_api.Select(x => x.TypeId).Distinct().ToList(); List <ItemType_V_Row> itemTypes = _DBService.GetItemTypes(itemTypeIds); List <int> locationIds = assets_api.Select(x => (int)x.LocationId).Distinct().ToList(); List <SolarSystem_V_Row> solarSystems = _DBService.GetSolarSystems(locationIds); List <Station_V_Row> stations = _DBService.GetStations(locationIds); for (int x = 0; x < assets_api.Count; x++) { Asset asset = assets_api[x]; ItemType_V_Row itemType = itemTypes.Where(b => b.Id == asset.TypeId).FirstOrDefault(); SolarSystem_V_Row system = null; Station_V_Row station = null; if (asset.LocationType == EVEStandard.Enumerations.LocationTypeEnum.solar_system) { system = solarSystems.Where(b => b.Id == (int)asset.LocationId).FirstOrDefault(); } else if (asset.LocationType == EVEStandard.Enumerations.LocationTypeEnum.station) { station = stations.Where(b => b.Id == (int)asset.LocationId).FirstOrDefault(); } AssetDataModel a = new AssetDataModel() { Asset_API = asset, ItemType = itemType, System = system, Station = station }; assets.Add(a); } var model = new AssetsPageViewModel() { Assets = assets }; return(View(model)); }
private async Task <List <SkillQueueDataModel> > GetSkillQueue(AuthDTO auth, int characterId) { if (characterId <= 0 || characterId != auth.CharacterId) { return(new List <SkillQueueDataModel>()); // This only works for current logged in character } var characterSkillsQueueApi = await _ESIClient.Skills.GetCharacterSkillQueueV2Async(auth); List <SkillQueue> skillsQueueApiModel = characterSkillsQueueApi.Model; skillsQueueApiModel = skillsQueueApiModel.Where(x => x.FinishDate == null || x.FinishDate >= DateTime.Now.AddHours(-6)).ToList(); // Get only the skills that are completed within 6 hours from now (to current planned) List <SkillQueueDataModel> skillsQueue = new List <SkillQueueDataModel>(); foreach (SkillQueue skillApi in skillsQueueApiModel) { Skill_V_Row skill = _DBService.GetSkillForIdAndSkillLevel(skillApi.SkillId, skillApi.FinishedLevel); skillsQueue.Add(new SkillQueueDataModel() { Sequence = skillApi.QueuePosition, Skill = skill, Skill_API = skillApi }); } skillsQueue = skillsQueue.OrderBy(x => x.Sequence).ToList(); return(skillsQueue); }
public IActionResult Login([FromBody] AuthDTO auth) { ///////////////////////////////////////////// //Código para Validar si usuario es correcto. ///////////////////////////////////////////// JwtSecurityToken token; DateTime expiration; //Obtener la llave del archivo appsettings.json var llave = Encoding.UTF8.GetBytes(Config["Tokens:Key"]); //Crear la llave simetrica: introducir la clave secreta que fue utilizada para firmar digitalmente el token var key = new SymmetricSecurityKey(llave); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // Creamos los claims (pertenencias, características) del usuario var claims = new Claim[] { new Claim(ClaimTypes.Sid, auth.Guid), new Claim(ClaimTypes.Role, auth.Role), new Claim("Organization", auth.Organization) }; token = new JwtSecurityToken(Config["Tokens:Issuer"], Config["Tokens:Issuer"], claims, expires: DateTime.Now.AddDays(1), signingCredentials: creds); string tokenHandler = new JwtSecurityTokenHandler().WriteToken(token); expiration = token.ValidTo; return(Ok(tokenHandler)); }
public TokenDTO RegisterUser(UserDTO userData) { var validator = new RegisterUserValidator(_userRepository); var validationResult = validator.Validate(userData); if (!validationResult.IsValid) { throw new ValidationException(validationResult.Errors); } var user = new User { Name = userData.Name, Email = userData.Email, Password = _cryptoService.Encrypt(userData.Password) }; _userRepository.Insert(user); var auth = new AuthDTO { Email = userData.Email, Password = userData.Password }; return(_authService.Authenticate(auth)); }
/// <summary> /// Delete a fleet squad, only empty squads can be deleted. /// <para>DELETE /fleets/{fleet_id}/squads/{squad_id}/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="fleetId">ID for a fleet.</param> /// <param name="squadId">The squad to delete.</param> /// <returns></returns> public async Task DeleteFleetSquadV1Async(AuthDTO auth, long fleetId, long squadId) { CheckAuth(auth, Scopes.ESI_FLEETS_WRITE_FLEET_1); var responseModel = await DeleteAsync($"/v1/fleets/{fleetId}/squads/{squadId}/", auth); CheckResponse(nameof(DeleteFleetSquadV1Async), responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
/// <summary> /// Move a fleet member around. /// <para>PUT /fleets/{fleet_id}/members/{member_id}/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="fleetId">ID for a fleet.</param> /// <param name="memberId">The character ID of a member in this fleet.</param> /// <param name="movement">Details of the invitation.</param> /// <returns></returns> public async Task MoveFleetMemberV1Async(AuthDTO auth, long fleetId, int memberId, FleetMemberMove movement) { CheckAuth(auth, Scopes.ESI_FLEETS_WRITE_FLEET_1); var responseModel = await PutAsync($"/v1/fleets/{fleetId}/members/{memberId}/", auth, movement); CheckResponse(nameof(MoveFleetMemberV1Async), responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
/// <summary> /// Invite a character into the fleet. If a character has a CSPA charge set it is not possible to invite them to the fleet using ESI. /// <para>POST /fleets/{fleet_id}/members/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="fleetId">ID for a fleet.</param> /// <param name="invite">Details of the invitation.</param> /// <returns></returns> public async Task CreateFleetInvitationV1Async(AuthDTO auth, long fleetId, FleetInvitation invite) { CheckAuth(auth, Scopes.ESI_FLEETS_WRITE_FLEET_1); var responseModel = await PostAsync($"/v1/fleets/{fleetId}/members/", auth, invite); CheckResponse(nameof(CreateFleetInvitationV1Async), responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
/// <summary> /// Open the New Mail window, according to settings from the request if applicable. /// <para>GET /ui/openwindow/newmail/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="mail">The details of mail to create.</param> /// <returns></returns> public async Task OpenNewMailWindowV1Async(AuthDTO auth, UiNewMail mail) { CheckAuth(auth, Scopes.ESI_UI_OPEN_WINDOW_1); var responseModel = await PostAsync("/v1/ui/openwindow/newmail/", auth, mail); CheckResponse(nameof(OpenNewMailWindowV1Async), responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
/// <summary> /// Update metadata about a mail. /// <para>PUT /characters/{character_id}/mail/{mail_id}/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="mailId">An EVE mail ID.</param> /// <param name="contents">Data used to update the mail.</param> /// <returns></returns> public async Task UpdateMetadataAboutMailV1Async(AuthDTO auth, long mailId, UpdateMailMetadata contents) { CheckAuth(auth, Scopes.ESI_MAIL_ORGANIZE_MAIL_1); var responseModel = await PutAsync($"/v1/characters/{auth.CharacterId}/mail/{mailId}/", auth, contents); CheckResponse(nameof(ReturnMailV1Async), responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
public async Task <IActionResult> SignIn(AuthDTO auth) { var user = await context.Users.Where(user => user.Login == auth.Login && user.Password == auth.Password).FirstOrDefaultAsync(); if (!(user is null)) { return(Ok(user.SecureCode)); }
/// <summary> /// Delete a mail. /// <para>DELETE /characters/{character_id}/mail/{mail_id}/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="mailId">An EVE mail ID.</param> /// <returns></returns> public async Task DeleteMailV1Async(AuthDTO auth, long mailId) { CheckAuth(auth, Scopes.ESI_MAIL_ORGANIZE_MAIL_1); var responseModel = await DeleteAsync($"/v1/characters/{auth.CharacterId}/mail/" + mailId + "/", auth); CheckResponse(nameof(DeleteMailV1Async), responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
public async Task <IActionResult> Post(AuthDTO auth) { if (ModelState.IsValid) { return(Ok(await _authService.Auth(_mapper.Map <Usuario> (auth)))); } return(BadRequest(new { msg = "Usuário ou senha inválido." })); }
/// <summary> /// Delete a fitting from a character. /// <para>DELETE /characters/{character_id}/fittings/{fitting_id}/</para> /// </summary> /// <param name="auth">The <see cref="AuthDTO"/> object.</param> /// <param name="fittingId">ID for a fitting of this character.</param> /// <returns></returns> public async Task DeleteFittingV1Async(AuthDTO auth, long fittingId) { CheckAuth(auth, Scopes.ESI_FITTINGS_WRITE_FITTINGS_1); var responseModel = await DeleteAsync($"/v1/characters/{auth.CharacterId}/fittings/{fittingId}/", auth); CheckResponse("DeleteFittingV1Async", responseModel.Error, responseModel.Message, responseModel.LegacyWarning, logger); }
public async Task <ActionResult> StationInfoSetSystemAsWaypoint(UniverseStationInfoPageViewModel model) { AuthDTO auth = GetAuth(_ESIClient); _Log.LogDebug(String.Format("Logged in to retrieve Character Info for Character Id: {0}", auth.CharacterId)); await _ESIClient.UserInterface.SetAutopilotWaypointV2Async(auth, model.SetDestination.AddToBeginning, model.SetDestination.ClearOtherWaypoints, model.SetDestination.DestinationId); return(RedirectToAction("StationInfo", new { id = model.SetDestination.DestinationId })); }
private AuthDTO GetAuth(ClientEntry clEntry) { var auth = new AuthDTO(); auth.system = rpxsystemname; auth.username = rpxusername; auth.password = rpxpassword; auth.licensekey = rpxlicensekey; auth.pmcid = clEntry.PmcId; auth.siteid = clEntry.SiteId; return auth; }