protected override SvcRepository ConvertToModel(SvcRepositoryDto dto) { IUser checkoutUser = this.userStore.GetById(dto.CheckoutUserId); if (checkoutUser == null) { throw new InvalidOperationException("User not found."); } dto.CheckoutUser = checkoutUser.ToDto(); CredentialsDto mappedCheckoutCredentials = dto.CheckoutUser.RepositoryCredentials.FirstOrDefault(c => c.RepositoryType == dto.Type); dto.MappedCheckoutCredentials = mappedCheckoutCredentials; IUser pushUser = this.userStore.GetById(dto.PushUserId); if (pushUser == null) { throw new InvalidOperationException("User not found."); } dto.PushUser = pushUser.ToDto(); CredentialsDto mappedPushCredentials = dto.PushUser.RepositoryCredentials.FirstOrDefault(c => c.RepositoryType == dto.Type); dto.MappedCheckoutCredentials = mappedPushCredentials; return(dto.ToSvcRepository()); }
public Models.AccessGrantDto GenerateAccessGrant(User user, CredentialsDto credentials) { var tokenExpirationTimeSpan = TimeSpan.FromDays(14); var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, credentials.Provider)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY")); AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan); var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); Authentication.SignIn(identity); AccessGrantDto grant = new AccessGrantDto { AccessToken = accesstoken, Expires = ticket.Properties.ExpiresUtc.Value.DateTime, ExpiresIn = tokenExpirationTimeSpan.Seconds.ToString(), Issued = ticket.Properties.IssuedUtc.Value.DateTime, ID = user.Id, UserName = user.UserName, TokenType = TOKEN_TYPE }; return(grant); }
public async Task <IActionResult> Login(CredentialsDto credentialsDto) { if (credentialsDto is null) { _logger.LogInformation("The {@DtoName} is null!", nameof(credentialsDto)); throw new ArgumentNullException(); } string token; try { token = await _playerService.LoginAsync(credentialsDto.Username.Trim(), credentialsDto.Password); } catch (PlayerNotFoundException) { return(NotFound()); } catch (WrongPasswordException) { return(Unauthorized()); } var dto = new TokenDto { Token = token }; return(Ok(dto)); }
private async Task <CredentialsDto> BuidlCredentials(LoginDto login, int userId) { var now = DateTimeOffset.UtcNow; var accessToken = await BuildToken(login.UserName, userId); var accessTokenExpiration = now.AddMinutes(JwtConfigModel.AccessTokenExpirationMinutes); var token = new UserToken { UserTokenGuid = Guid.NewGuid(), OwnerUserId = userId, AccessToken = accessToken, AccessTokenExpiration = accessTokenExpiration }; _dbContext.UserTokens.Add(token); await _dbContext.SaveChangesAsync(); var r = _dbContext.UserTokens.Count(); var data = new CredentialsDto { AccessToken = accessToken, AccessTokenExpiration = accessTokenExpiration }; return(data); }
public async Task <ActionResult <UserDto> > SignUp(CredentialsDto userModel) { try { // check if the Username/Email already exists var user = await _userManager.FindByNameAsync(userModel.Name).ConfigureAwait(false); if (user != null) { return(BadRequest("User name is already exists.")); } user = Mapper.Map <User>(userModel); var errors = await CreateUser(user, userModel.Password).ConfigureAwait(false); if (errors != null) { return(BadRequest(errors)); } return(await CreateUserDto(user).ConfigureAwait(false)); } catch (Exception e) { // return the error. return(BadRequest(e.Message)); } }
public async Task <IActionResult> Authentication(UserLogin login) { CredentialsDto result = new CredentialsDto(); var cedentialDto = await IsValiduser(login); if (cedentialDto.Validate) { string token = _segUsuarioService.GenerateToken(); result.Token = token; result.User = login.User; result.Validate = cedentialDto.Validate; result.Role = cedentialDto.Role; if (result.Role == "358") { result.Role = "387"; } List <PageMenuDto> resultMenu = new List <PageMenuDto>(); resultMenu = await _segUsuarioService.GetMenuDtoByRole(Convert.ToInt32(result.Role)); result.PageMenuDto = resultMenu; } else { result.Token = ""; result.User = login.User; result.Validate = cedentialDto.Validate; result.Role = cedentialDto.Role; } return(Ok(result)); }
public ActionResult <TweetResponseDto> DeleteTweet(CredentialsDto credentials, int id) { var result = _tweetService.DeleteTweet(credentials, id); var mappedTweets = _mapper.Map <Tweet, TweetResponseDto>(result); return(mappedTweets); }
public void t() { CredentialsDto credentialsDto = new CredentialsDto(); credentialsDto.Login = "******"; credentialsDto.Password = "******"; }
public ActionResult <TweetResponseDto> Post(string content, CredentialsDto credentials) { var result = _tweetService.PostTweet(content, credentials); var mappedTweets = _mapper.Map <Tweet, TweetResponseDto>(result); return(mappedTweets); }
public async Task <IActionResult> LogIn(CredentialsDto credentials) { var user = this._identityService.Authentication(credentials); var result = new StandardResult(); if (user == null) { result.StatusCode = SAE.CommonLibrary.Common.StatusCode.AccountOrPassword; } else { var claims = new List <Claim>() { new Claim("name", user.Information.Name), new Claim(ClaimTypes.Sid, user.Id), new Claim("sub", user.Id), new Claim("role", "admin") }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await this.HttpContext.SignInAsync(principal); } return(this.Json(result)); }
public void Follow(string username, CredentialsDto credentials) { var followee = _context.Users .SingleOrDefault(u => u.Credentials.Username == username && !u.Deleted); var follower = _context.Users .SingleOrDefault(u => u.Credentials.Username == credentials.Username && !u.Deleted); if (followee == null || follower == null) { throw new UserNotFoundException(); } if (follower.Credentials.Password != credentials.Password) { throw new InvalidCredentialsException(); } bool exists = _context.UserFollowJoin.Where(u => u.FolloweeId == followee.Id && u.FollowerId == follower.Id).Any(); if (!exists) { var userUser = new UserUser { Followee = followee, FolloweeId = followee.Id, Follower = follower, FollowerId = follower.Id }; _context.UserFollowJoin.Add(userUser); _context.SaveChanges(); } }
public async Task <IActionResult> Login([FromBody] CredentialsDto dto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // is the user authorized var user = await _userManager.FindByEmailAsync(dto.Email); if (user == null || !await _userManager.CheckPasswordAsync(user, dto.Password)) { return(Unauthorized()); } var token = TokenHelper.GenerateToken(_authSettings, user); return(Ok(Mapper.Map <User, UserAuthenticationDto>( user, opt => opt.AfterMap((src, dest) => AfterMapConversion(dest))) )); UserAuthenticationDto AfterMapConversion(UserAuthenticationDto dest) { dest.Token = token.TokenId; dest.ExpirationDate = token.ExpirationDate; return(dest); } }
public async Task <UserDto> AddAsync(CredentialsDto credentials) { var newUser = this.mapper.Map <User>(credentials); newUser.Culture = LocalizationHelper.GetClosestSupportedCultureName(); await using (var transaction = await this.context.Database.BeginTransactionAsync()) { try { var result = await this.userManager.CreateAsync(newUser, credentials.Password); this.ThrowIfNotSucceed(result); await this.AddToRoleAsync(newUser, Constants.Roles.User); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } await this.userAccountService.SendConfirmationEmailAsync(newUser.UserName); return(this.mapper.Map <UserDto>(newUser)); }
public async Task <IActionResult> WalletTransactions([FromBody] CredentialsDto credentials) { var session = new Session(credentials.Identifier.ToSecureString(), credentials.Password.ToSecureString()); var txns = await unitOfWork.GetTransactionRepository().All(session); return(new OkObjectResult(txns)); }
public async Task <TokenDto> AuthenticateAsync(CredentialsDto credentials) { var user = await this.userManager.FindByNameAsync(credentials.UserName); if (user == null) { var message = this.localizer.GetAndApplyKeys("NotFound", "User"); throw new NotFoundException(message); } if (!user.EmailConfirmed) { throw new EmailNotConfirmedException(this.localizer.Get("EmailNotConfirmed")); } var passwordIsValid = await this.userManager.CheckPasswordAsync(user, credentials.Password); if (!passwordIsValid) { throw new InvalidPasswordException(this.localizer.Get("InvalidPassword")); } var roles = await this.userManager.GetRolesAsync(user); var encodedToken = this.GenerateEncodedToken(user, roles); var tokenResult = this.GenerateTokenResult(encodedToken, user, roles); await this.LogAccess(user); return(tokenResult); }
public async Task <CredentialsDto> UsuarioValido(string Usuario, string Password) { bool Validado = false; CredentialsDto credentialsDto = new CredentialsDto(); //var usu = await _context.SegUsuario.Where(x => x.Usuario == Usuario ).FirstOrDefaultAsync(); var BuscarUsuario = (from u in _context.SegUsuario join ur in _context.SegUsuarioRol on u.IdUsuario equals ur.IdUsuario join r in _context.SegRol on ur.IdRol equals r.IdRol where u.Usuario == Usuario & r.IdPrograma == 141 select new { Clave = u.Clave, IdRol = r.IdRol, NombreUsuario = u.NombreUsuario }).FirstOrDefault(); if (BuscarUsuario != null) { if (BuscarUsuario.Clave == ConvertSha1(Password)) { credentialsDto.Validate = true; credentialsDto.User = Usuario; credentialsDto.Role = BuscarUsuario.IdRol.ToString(); } } return(credentialsDto); }
public async Task <IActionResult> Login([FromBody] CredentialsDto credentials) { if (credentials == null) { return(BadRequest()); } var user = await _userManager.FindByNameAsync(credentials.UserName); user = user ?? await _userManager.FindByEmailAsync(credentials.UserName); if (user == null) { return(NotFound()); } var identity = await GenerateClaimsIdentity(user, credentials.Password); if (identity == null) { return(BadRequest(ModelState)); } var response = new Login { UserName = user.UserName, Roles = _userManager.GetRolesAsync(user).Result, AuthToken = _tokenFactory.GenerateToken(credentials.UserName, identity).Result, ExpiresIn = (int)JwtTokenProviderOptions.Expiration.TotalSeconds }; await HttpContext.SignInAsync("Identity.Application", new ClaimsPrincipal(identity)); return(Ok(response)); }
public async Task Login(CredentialsDto credentials) { var identity = await GetIdentity(credentials.Nickname, credentials.PasswordHash); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; } string encodedJwt = CreateToken(identity); var response = new { access_token = encodedJwt, username = identity.Name }; Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
public async Task <ActionResult <TokenDto> > AuthenticateAsync([FromBody] CredentialsDto credentials) { this.userSession.DisableTenantFilter = true; var result = await this.tokenService.AuthenticateAsync(credentials); return(result); }
private async Task <AuthenticationResultDto> GetAuthenticationResult( CredentialsDto credentials, CancellationToken cancellationToken) { if (credentials == null || string.IsNullOrEmpty(credentials.Email) || string.IsNullOrEmpty(credentials.Password)) { return(null); } var userIdentity = await this.userIdentityLogic.GetUserByEmail( credentials.Email, cancellationToken); if (userIdentity == null || userIdentity.UserId == 0) { return(null); } var result = await this.signInManager.CheckPasswordSignInAsync( userIdentity, credentials.Password, true); if (!result.Succeeded) { return(null); } return(await this.GetAuthenticationResult(userIdentity)); }
public ActionResult <UserProfileWithToken> Authenticate([FromBody] CredentialsDto credentials) { var token = securityService.GenerateJwtToken(credentials.UserName, credentials.Password); if (token == null) { return(Unauthorized()); } var user = alohaDbContext.Users .Include(u => u.Worker) .ThenInclude(w => w.Photo) .Single(u => u.UserName == credentials.UserName); var response = new UserProfileWithToken() { UserName = user.UserName, Token = token, WorkerId = user.Worker?.Id, Name = user.Worker?.Name, SurName = user.Worker?.Surname, ImageId = user.Worker?.Photo?.Id }; return(new ActionResult <UserProfileWithToken>(response)); }
public ActionResult <TweetDto> DeleteTweet(int id, [FromBody] CredentialsDto credentialsDto) { var credentials = _mapper.Map <Credentials>(credentialsDto); var user = _userService.GetAndValidateUser(credentials); var deletedTweet = _tweetService.DeleteTweet(id, user); return(_mapper.Map <TweetDto>(deletedTweet)); }
public ActionResult FollowUser(string usernameToFollow, [FromBody] CredentialsDto credentialsDto) { var credentials = _mapper.Map <Credentials>(credentialsDto); var user = _userService.GetAndValidateUser(credentials); _userService.FollowUser(usernameToFollow, user); return(Ok()); }
public void WriteCredentials(CredentialsDto credentialsForUserCredentialDto) { var userLogin = credentialsForUserCredentialDto.Login; var userPassword = credentialsForUserCredentialDto.Password; var networkPath = credentialsForUserCredentialDto.NetworkPath; CredentialManager.WriteCredential(networkPath, userLogin, userPassword, CredentialPersistence.LocalMachine); }
public ActionResult <TweetDto> RepostTweet(int id, [FromBody] CredentialsDto credentialsDto) { var credentials = _mapper.Map <Credentials>(credentialsDto); var user = _userService.GetAndValidateUser(credentials); var tweetRepost = _tweetService.CreateRepostTweet(user, id); return(_mapper.Map <TweetDto>(tweetRepost)); }
public ActionResult LikeTweet(int id, [FromBody] CredentialsDto credentialsDto) { var credentials = _mapper.Map <Credentials>(credentialsDto); var user = _userService.GetAndValidateUser(credentials); _tweetService.LikeTweet(id, user); return(Ok()); }
public void ValidateUser(CredentialsDto credentials) { var user = GetByUsername(credentials.Username); if (user.Credentials.Password != credentials.Password) { throw new InvalidCredentialsException(); } }
public TweetResponseDto RepostTweet([FromBody] CredentialsDto credentialsDto, int id) { _userService.ValidateUser(credentialsDto); return(_mapper.Map <Tweet, TweetResponseDto>( _tweetService.CreateRepost( _userService.GetByUsername(credentialsDto.Username), id ) )); }
public ActionResult <UserResponseDto> Delete(string username, [FromBody] CredentialsDto credentialsDto) { if (credentialsDto.Username != username) { return(Forbid()); } var credentials = _mapper.Map <Credentials>(credentialsDto); return(_mapper.Map <UserResponseDto>(_userService.DeleteUser(credentials))); }
public void Initialize() { _facebookUser = UserGenerator.GenerateFacebookUser(); _twitterUser = UserGenerator.GenerateTwitterUser(); _facebookResult = ProviderVerifyResultGenerator.GenFacebookVerifyResult(); _twitterResult = ProviderVerifyResultGenerator.GenTwitterVerifyResult(); _facebookGrant = AccessGrantGenerator.GenFacebookGrant(); _twitterGrant = AccessGrantGenerator.GenTwitterGrant(); _facebookCredentials = CredentialsDtoGenerator.GenFacebookCredentials(); _twitterCredentials = CredentialsDtoGenerator.GenTwitterCredentials(); }