public override async Task <SignInQueryResult> ExecuteAsync(SignInQuery query) { Logger.ExecuteUserSignIn(query.Email); Tuple <Guid, string, string, IEnumerable <string> >?userByEmail = await Reader.SingleOrDefaultAsync <User, Tuple <Guid, string, string, IEnumerable <string> > >( u => u.Email == query.Email.ToLowerInvariant(), u => new Tuple <Guid, string, string, IEnumerable <string> >(u.Id, u.PasswordHash, u.Email, u.Roles)); if (userByEmail == null) { Logger.UserSignInUserNotFound(query.Email); return(new SignInQueryResult(true, false, string.Empty)); } bool passwordOk = _passwordStorage.Match(query.Password, userByEmail.Item2); if (!passwordOk) { Logger.UserSignInPasswordMismatch(query.Email); return(new SignInQueryResult(false, true, string.Empty)); } string token = _securityTokenFactory.Create(userByEmail.Item1, userByEmail.Item3, userByEmail.Item4); var result = new SignInQueryResult(false, false, token); Logger.ExecuteUserSignInSuccessful(query.Email); return(result); }
public async Task Invoke(HttpContext httpContext) { var token = _securityTokenFactory.Create("*****@*****.**"); httpContext.Request.Headers.Add("Authorization", $"Bearer {token}"); await _next.Invoke(httpContext); }
public async Task <SignInQueryResult> ExecuteAsync(SignInQuery query) { _logger.PartnerSignInInitiated(query.Id); (Guid id, string?name, string?hash) = await _reader.GetByIdOrThrowAsync <TokenIssuer, Tuple <Guid, string, string> >( query.Id, u => new Tuple <Guid, string, string>(u.Id, u.Name, u.SecretHash)); if (id == Guid.Empty) { _logger.PartnerSignInPartnerNotFound(query.Id); return(new SignInQueryResult(true, false, string.Empty)); } bool passwordOk = _passwordStorage.Match(query.Secret, hash); if (!passwordOk) { _logger.PartnerSignInPasswordMismatch(query.Id); return(new SignInQueryResult(false, true, string.Empty)); } _logger.PartnerSignInSuccessful(query.Id, name); string token = _securityTokenFactory.Create(id, name, new[] { Roles.Partner }); return(new SignInQueryResult(false, false, token)); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { return(new Response() { AccessToken = _securityTokenFactory.Create(request.Username), UserId = 0 }); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { User user = await _context.Users .SingleOrDefaultAsync(x => x.Username.ToLower() == request.Username.ToLower()); if (user == null) { throw new InvalidUsernameOrPasswordException(); } if (!ValidateUser(user, _passwordHasher.HashPassword(user.Salt, request.Password))) { throw new InvalidUsernameOrPasswordException(); } var profiles = _context.Profiles .Include(x => x.User) .Where(x => x.User.Username == request.Username) .ToList(); var claims = new List <Claim> { new Claim("UserId", $"{user.UserId}"), new Claim("PartitionKey", $"{user.TenantId}"), new Claim("CurrentUserName", $"{user.Username}") }; foreach (var profile in profiles) { claims.Add(new Claim("ProfileId", $"{profile.ProfileId}")); if (profile.Type == ProfileType.Customer) { claims.Add(new Claim(ClaimTypes.Role, nameof(ProfileType.Customer))); } if (profile.Type == ProfileType.Admin) { claims.Add(new Claim(ClaimTypes.Role, nameof(ProfileType.Admin))); } if (profile.Type == ProfileType.Driver) { claims.Add(new Claim(ClaimTypes.Role, nameof(ProfileType.Driver))); } } return(new Response() { AccessToken = _securityTokenFactory.Create(request.Username, claims), UserId = user.UserId }); }
public Task <Response> Handle(Request request, CancellationToken cancellationToken) { var user = _eventStore.Query <User>("Username", request.Username); user.SignIn(_passwordHasher.HashPassword(user.Salt, request.Password)); _eventStore.Save(user); return(Task.FromResult(new Response() { AccessToken = _securityTokenFactory.Create(request.Username), UserId = user.UserId })); }
public Task <Response> Handle(Request request, CancellationToken cancellationToken) { var user = _eventStore.Query <User>("Username", request.Username); if (user.Password != _passwordHasher.HashPassword(user.Salt, request.Password)) { throw new System.Exception(); } return(Task.FromResult(new Response() { AccessToken = _securityTokenFactory.Create(request.Username), UserId = user.UserId })); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _connection = new HubConnectionBuilder() .WithUrl("https://localhost:44337/hubs/connectionManagement", options => { options.AccessTokenProvider = () => Task.FromResult(_securityTokenFactory.Create(Strings.System)); }) .Build(); _connection.On <Dictionary <string, string> >(Strings.ConnectionsChanged, connections => _hubService.Connections = new ConcurrentDictionary <string, string>(connections)); _hubService.HubConnection = _connection; await StartConnectionAsync(); }
public async Task <string> ExecuteAsync(SignInValidQuery query) { User user = await _userReader.ByEmail(query.Email); if (user == null) { throw new ValidationException("User not found!"); } bool isValid = _passwordStorage.Match(query.Password, user.PasswordHash); if (isValid) { return(_securityTokenFactory.Create(user)); } throw new ValidationException("Password invalid!"); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { var user = await _context.Users .SingleOrDefaultAsync(x => x.Username.ToLower() == request.Username.ToLower()); if (user == null) { throw new Exception("Invalid username or password"); } if (!ValidateUser(user, _passwordHasher.HashPassword(user.Salt, request.Password))) { throw new Exception("Invalid username or password"); } return(new Response() { AccessToken = _securityTokenFactory.Create(user.UserId, request.Username), UserId = user.UserId }); }
public async Task Invoke(HttpContext httpContext) { using (var scope = _serviceScopeFactory.CreateScope()) { var repository = scope.ServiceProvider.GetService <IAccessTokenRepository>(); var username = "******"; var token = _tokenProvider.Create(username, new List <string>() { "Admin" }); httpContext.Request.Headers.Add("Authorization", $"Bearer {token}"); repository.Add(new AccessToken() { Value = token, Username = username, IsValid = true }); await repository.SaveChangesAsync(default(CancellationToken)); await _next.Invoke(httpContext); } }
public Task <Response> Handle(Request request, CancellationToken cancellationToken) { var user = _repository.Query <User>().Single(x => x.Username == request.Username); var roles = new List <string>(); if (user.Password != _passwordHasher.HashPassword(user.Salt, request.Password)) { throw new System.Exception(); } foreach (var roleId in user.RoleIds) { roles.Add(_repository.Query <Role>(roleId).Name); } return(Task.FromResult(new Response() { AccessToken = _securityTokenFactory.Create(user.UserId, request.Username, roles), UserId = user.UserId, Roles = roles, Username = request.Username })); }
public async Task <IActionResult> SignIn(SignInRequest request) { var userId = $"{Guid.NewGuid()}"; var tenantId = $"{new Guid("f0f54a28-0714-4b1a-9012-b758213bff99")}"; if (_hubService.IsConnected($"{tenantId}-{request.Username}")) { return(new BadRequestObjectResult(new ProblemDetails { Title = "Login Failed", Type = "https://api.areyouconnected.com/errors/useralreadyloggedin", Detail = "User already logged in.", Status = StatusCodes.Status400BadRequest })); } if (_hubService.Count(tenantId) > 1) { return(new BadRequestObjectResult(new ProblemDetails { Title = "Login Failed", Type = "https://api.areyouconnected.com/errors/connectionlimitreached", Detail = "Connections limit reached.", Status = StatusCodes.Status400BadRequest })); } return(await Task.FromResult(new OkObjectResult(new SignInResponse { AccessToken = _securityTokenFactory.Create(tenantId, userId, request.Username), Username = request.Username, UserId = userId, TenantId = tenantId }))); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { var customer = await _context.Customers.FindAsync(request.Customer.CustomerId); if (customer == null) { if (await _context.Customers.AnyAsync(x => x.Email == request.Customer.Email)) { throw new CustomerExistsWithEmailException(); } if (!request.AcceptedTermsAndConditions) { throw new CustomerFailedToAcceptTermsAndConditionsException(); } customer = new Customer(); customer.CustomerTermsAndConditions.Add(new CustomerTermsAndConditions { Accepted = DateTime.UtcNow }); customer.RaiseDomainEvent(new CustomerCreated(customer)); _context.Customers.Add(customer); } customer.FirstName = request.Customer.FirstName; customer.LastName = request.Customer.LastName; customer.PhoneNumber = request.Customer.PhoneNumber; customer.Email = request.Customer.Email; if (request.Customer.Address != null) { customer.Address = new Address( request.Customer.Address.Street, request.Customer.Address.City, request.Customer.Address.Province, request.Customer.Address.PostalCode); } customer.CustomerLocations.Clear(); foreach (var customerLocationDto in request.Customer.CustomerLocations) { var customerLocation = await _context.CustomerLocations.FindAsync(customerLocationDto.CustomerLocationId); if (customerLocation == null) { customerLocation = new CustomerLocation(); } customerLocation.Location = await _context.Locations.FindAsync(customerLocationDto.LocationId); if (customerLocation.Location == null) { customerLocation.Location = new Location(); } customerLocation.Name = customerLocationDto.Name; customerLocation.Location = new Location(); customerLocation.LocationId = customerLocationDto.LocationId; customerLocation.Location.Type = customerLocationDto.Location.Type; customerLocation.Location.Adddress = new Address( customerLocationDto.Location.Address.Street, customerLocationDto.Location.Address.City, customerLocationDto.Location.Address.Province, customerLocationDto.Location.Address.PostalCode); customer.CustomerLocations.Add(customerLocation); } await _context.SaveChangesAsync(cancellationToken); var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == customer.Email); if (user == null) { user = new User { Username = customer.Email }; //TODO: Make random passwords user.Password = _passwordHasher.HashPassword(user.Salt, "P@ssw0rd"); await _context.Users.AddAsync(user); } user.Profiles.Add(new Profile { Name = $"{customer.FirstName} {customer.LastName}", Type = ProfileType.Customer }); await _context.SaveChangesAsync(cancellationToken); return(new Response() { CustomerId = customer.CustomerId, Version = customer.Version, AccessToken = _securityTokenFactory.Create(user.Username, new List <Claim>() { new Claim("UserId", $"{user.UserId}"), new Claim("PartitionKey", $"{user.TenantId}"), new Claim($"{nameof(customer.CustomerId)}", $"{customer.CustomerId}"), new Claim(ClaimTypes.Role, nameof(ProfileType.Customer)), new Claim("CurrentUserName", $"{user.Username}") }) }); }