Exemplo n.º 1
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                if (await _context.Persons.Where(x => x.Username == message.User.Username).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Username = Constants.IN_USE });
                }

                if (await _context.Persons.Where(x => x.Email == message.User.Email).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Email = Constants.IN_USE });
                }

                var salt   = Guid.NewGuid().ToByteArray();
                var person = new Person
                {
                    Username = message.User.Username,
                    Email    = message.User.Email,
                    Hash     = await _passwordHasher.Hash(message.User.Password, salt),
                    Salt     = salt
                };

                await _context.Persons.AddAsync(person, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var user = _mapper.Map <Person, User>(person);

                user.Token = _jwtTokenGenerator.CreateToken(person.Username);
                return(new UserEnvelope(user));
            }
Exemplo n.º 2
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                if (await _context.Persons.Where(u => u.Email == message.User.Email).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, "Email already in use");
                }

                var salt   = Guid.NewGuid().ToByteArray();
                var person = new Person
                {
                    Email        = message.User.Email,
                    DisplayName  = message.User.DisplayName,
                    PasswordHash = _passwordHasher.Hash(message.User.Password, salt),
                    PasswordSalt = salt
                };

                _context.Persons.Add(person);
                await _context.SaveChangesAsync(cancellationToken);

                var user = _mapper.Map <Person, User>(person);

                user.Token = await _jwtTokenGenerator.CreateToken(person.PersonId);

                return(new UserEnvelope(user));
            }
Exemplo n.º 3
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                if (await _context.Users.AnyAsync(x => x.Email.Equals(message.User.Email), cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Email = $"The Email '{message.User.Email}' is already taken" });
                }

                var salt = Guid.NewGuid().ToByteArray();
                var user = new User
                {
                    Name  = message.User.Name,
                    Email = message.User.Email,
                    Hash  = _passwordHasher.Hash(message.User.Password, salt),
                    Salt  = salt
                };

                _context.Users.Add(user);
                await _context.SaveChangesAsync(cancellationToken);

                var person = _mapper.Map <User, PublicUser>(user);

                person.Token = await _jwtTokenGenerator.CreateToken(person.Name);

                return(new UserEnvelope(person));
            }
Exemplo n.º 4
0
            public async Task <AuthenticatedUser> Handle(LoginData message, CancellationToken cancellationToken)
            {
                LoginDataValidator validator = new LoginDataValidator();
                var results = validator.Validate(message);

                // null or empty fields
                if (results.IsValid == false)
                {
                    throw new RestException(HttpStatusCode.BadRequest, results.Errors);
                }

                User user = await _context.Users.Where(u => u.EmailAddress == message.EmailAddress).SingleOrDefaultAsync();

                // not found
                if (user == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, "User with email address not found");
                }

                // wrong password
                if (!user.Password.Equals(message.Password))
                {
                    throw new RestException(HttpStatusCode.Forbidden, "Password or email does not match");
                }

                return(new AuthenticatedUser
                {
                    Token = await _jwtTokenGenerator.CreateToken(user.EmailAddress),
                    Username = user.Username
                });
            }
Exemplo n.º 5
0
            public async Task <UserEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                if (_currentUserAccessor.GetCurrentUserType().Equals(UserConstants.User))
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Username = Constants.UNAUTHERIZE });
                }
                if (await _context.Persons.Where(x => x.Username == request.User.Username).AsNoTracking().AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Username = Constants.IN_USE });
                }

                var person = new Person
                {
                    Username    = request.User.Username,
                    ProfileUrl  = request.User.ProfileUrl,
                    Phone       = request.User.Phone,
                    UserType    = request.User.UserType,
                    Password    = _passwordHasher.Hash(request.User.Password),
                    CreatedDate = DateTime.Now
                };
                await _context.Persons.AddAsync(person, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var auditId = _currentUserAccessor.GetAuditId();

                var user = _mapper.Map <Person, User>(person);

                user.Type  = UserConstants.GetUserTypeString(person.UserType);
                user.Token = _jwtTokenGenerator.CreateToken(user.Username, user.Type, auditId.ToString());
                return(new UserEnvelope(user));
            }
Exemplo n.º 6
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                if (await _context.Customers.Where(x => x.Email == message.User.Email).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Email = Constants.IN_USE });
                }

                var salt     = Guid.NewGuid().ToByteArray();
                var customer = new Customer
                {
                    FirstName = message.User.FirstName,
                    LastName  = message.User.LastName,
                    Email     = message.User.Email,
                    Hash      = _passwordHasher.Hash(message.User.Password, salt),
                    Salt      = salt
                };

                _context.Customers.Add(customer);
                await _context.SaveChangesAsync(cancellationToken);

                var user = _mapper.Map <Customer, User>(customer);

                user.Token = await _jwtTokenGenerator.CreateToken();

                return(new UserEnvelope(user));
            }
Exemplo n.º 7
0
            public async Task <UserEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                var appUser = await _userManager.FindByEmailAsync(request.User.Email);

                if (appUser == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized,
                                            new { Error = "Invalid email / password" });
                }

                var result = await _signInManager.CheckPasswordSignInAsync(appUser, request.User.Password, false);

                if (result.Succeeded)
                {
                    var user = _mapper.Map <AppUser, User>(appUser);
                    user.Token = await _jwtTokenGenerator.CreateToken(appUser);

                    return(new UserEnvelope(user));
                }
                else
                {
                    throw new RestException(HttpStatusCode.Unauthorized,
                                            new { Error = "Invalid email / password" });
                }
            }
Exemplo n.º 8
0
            public async Task <UserEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                // Getting user from db
                var user = await _context
                           .Users
                           .Where(u => u.Login == request.UserData.Login)
                           .SingleOrDefaultAsync(cancellationToken);

                // Validations
                if (user == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Invalid email / password." });
                }

                if (!user.Hash.SequenceEqual(_passwordHasher.Hash(request.UserData.Password, user.Salt)))
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Invalid email / password." });
                }

                // Mapping
                var userEnvelope = _mapper.Map <User, UserEnvelope>(user);

                userEnvelope.Token = await _jwtTokenGenerator.CreateToken(user.Login);

                return(userEnvelope);
            }
Exemplo n.º 9
0
            public async Task <UserEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                if (await _userManager.Users.Where(x => x.UserName == request.User.UserName).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { UserName = Constants.IN_USER });
                }

                if (await _userManager.Users.Where(x => x.Email == request.User.Email).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Email = Constants.IN_USER });
                }

                var appUser = new AppUser
                {
                    UserName = request.User.UserName,
                    Email    = request.User.Email
                };

                var result = await _userManager.CreateAsync(appUser, request.User.Password);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(request.User.UserName);

                    await _userManager.AddToRoleAsync(user, "Member");

                    var userToReturn = _mapper.Map <AppUser, User>(user);
                    userToReturn.Token = await _jwtTokenGenerator.CreateToken(user);

                    return(new UserEnvelope(userToReturn));
                }

                throw new Exception("Oops - something went wrong");
            }
Exemplo n.º 10
0
            public async Task <SigninResponse> Handle(SigninCommand request, CancellationToken cancellationToken)
            {
                if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Error = "Invalid Username Or Password." });
                }

                var user = await userRepository.GetBySpecAsync(new UserByUsernameSpec(request.Username), cancellationToken);

                if (user == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Error = $"User:{request.Username} Not Found" });
                }

                if (user.Password != request.Password)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Error = "Invalid Username Or Password." });
                }

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim(ClaimTypes.Role, "Demo Role 1"),
                    new Claim(ClaimTypes.Role, "Demo Role 2")
                };

                var token = jwtTokenGenerator.CreateToken(claims);

                return(new SigninResponse
                {
                    Token = token,
                    User = user
                });
            }
Exemplo n.º 11
0
            public async Task <User> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.Unauthorized);
                }

                await context.Images.LoadAsync(cancellationToken : cancellationToken);

                var result = await SignInManager.PasswordSignInAsync(user, request.Password, request.RememberMe, false);

                if (result.Succeeded)
                {
                    var refreshToken = refreshTokenGenerator.GenerateRefreshToken(request.Ip);
                    user.RefreshTokens.Add(refreshToken);
                    await userManager.UpdateAsync(user);

                    return(new User()
                    {
                        ImageUrl = user.Photo == null ? "" : user.Photo.Url,
                        JwtToken = await jwtGenerator.CreateToken(user),
                        Username = user.UserName,
                        RefreshToken = refreshToken.Token
                    });
                }
                throw new RestException(System.Net.HttpStatusCode.Unauthorized);
            }
Exemplo n.º 12
0
            public async Task <UserEnvelope> Handle(Query message, CancellationToken cancellationToken)
            {
                var person = await _context.Persons.AsNoTracking()
                             .FirstOrDefaultAsync(p => p.PersonId == message.UserId, cancellationToken);

                if (message.UserId == null)
                {
                    throw new RedirectException($"user/{_currentUserAccessor.GetCurrentUserId()}", false);
                }

                if (person == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, "User does not exist");
                }

                var user = _mapper.Map <Person, User>(person);

                if (person.PersonId != _currentUserAccessor.GetCurrentUserId())
                {
                    user.Email = null;
                    user.Token = null;
                }
                else
                {
                    user.Token = await _jwtTokenGenerator.CreateToken(person.PersonId);
                }
                return(new UserEnvelope(user));
            }
Exemplo n.º 13
0
            public async Task <UserEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                // Getting if user exist
                var existUser = await _context
                                .Users
                                .Where(u => u.Login.Equals(request.UserData.Login, StringComparison.InvariantCultureIgnoreCase))
                                .AnyAsync(cancellationToken);

                // Validations
                if (existUser)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Error = $"El usuario {request.UserData.Login} ya se encuentra en uso." });
                }

                // Creating user
                var salt = Guid.NewGuid().ToByteArray();
                var user = new User
                {
                    Login = request.UserData.Login,
                    Hash  = _passwordHasher.Hash(request.UserData.Password, salt),
                    Salt  = salt
                };

                // Saving
                _context.Users.Add(user);
                await _context.SaveChangesAsync(cancellationToken);

                // Mapping
                var userEnvelope = _mapper.Map <User, UserEnvelope>(user);

                userEnvelope.Token = await _jwtTokenGenerator.CreateToken(user.Login);

                return(userEnvelope);
            }
Exemplo n.º 14
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                if (await _context.Users.Where(x => x.Username == message.User.Username).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Username = ErrorMessages.UserNameInUse });
                }

                if (await _context.Users.Where(x => x.Email == message.User.Email).AnyAsync(cancellationToken))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Email = ErrorMessages.EmailInUse });
                }

                var salt    = Guid.NewGuid().ToByteArray();
                var newUser = new Models.User
                {
                    Username = message.User.Username,
                    Email    = message.User.Email,
                    Role     = UserRole.User,
                    Hash     = _passwordHasher.Hash(message.User.Password, salt),
                    Salt     = salt
                };

                _context.Users.Add(newUser);
                await _context.SaveChangesAsync(cancellationToken);

                var user = _mapper.Map <Models.User, User>(newUser);

                user.Token = await _jwtTokenGenerator.CreateToken(newUser.Username);

                return(new UserEnvelope(user));
            }
Exemplo n.º 15
0
        public async Task <IActionResult> Login(UserLoginCredentials credentials)
        {
            var user = await _userService.GetOneByEmailAsync(credentials.Email);

            if (user == null)
            {
                return(NotFound());
            }

            if (user.Password != credentials.Password)
            {
                return(Unauthorized());
            }

            var token = await _jwtTokenGenerator.CreateToken(user.Id);

            return(Ok(token));
        }
Exemplo n.º 16
0
            public async Task <UserEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var appUser = await _userManager.FindByNameAsync(request.UserName);

                if (appUser == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { User = Constants.NOT_FOUND });
                }
                var user = _mapper.Map <AppUser, User>(appUser);

                user.Token = await _jwtTokenGenerator.CreateToken(appUser);

                return(new UserEnvelope(user));
            }
Exemplo n.º 17
0
            public async Task <AuthUserDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users
                           .Include(x => x.Roles)
                           .ThenInclude(x => x.Role)
                           .SingleOrDefaultAsync(
                    x => x.UserName == request.UserName && !x.Archived,
                    cancellationToken);

                if (user == null)
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                if (!user.Hash.SequenceEqual(
                        _passwordHasher.Hash(
                            request.Password,
                            user.Salt)))
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                // generate refresh token
                var refreshToken = _jwtTokenGenerator.GenerateRefreshToken();

                user.AddRefreshToken(
                    refreshToken,
                    user.Id);

                var token = await _jwtTokenGenerator.CreateToken(
                    user.Id.ToString(),
                    user.FullName,
                    user.Email,
                    user.Roles.SelectMany(x => x.Role.PermissionsInRole));

                await _context.SaveChangesAsync(cancellationToken);

                return(new AuthUserDto(
                           user.Id,
                           user.FullName,
                           user.Email,
                           token,
                           refreshToken));
            }
Exemplo n.º 18
0
            public async Task <AuthUserDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var userId = GetIdentifierFromExpiredToken(request.Token).Value;

                var user = await _context.Users
                           .Include(u => u.RefreshTokens)
                           .Include(u => u.Roles)
                           .ThenInclude(x => x.Role)
                           .SingleAsync(
                    x => x.Id.ToString() == userId && !x.Archived,
                    cancellationToken);

                if (user == null)
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                if (!user.IsValidRefreshToken(request.RefreshToken))
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                var refreshToken = _jwtTokenGenerator.GenerateRefreshToken();

                user.RemoveRefreshToken(request.RefreshToken);
                user.AddRefreshToken(
                    refreshToken,
                    user.Id);
                var token = await _jwtTokenGenerator.CreateToken(
                    user.Id.ToString(),
                    user.UserName,
                    user.Email,
                    user.Roles.SelectMany(x => x.Role.PermissionsInRole));

                await _context.SaveChangesAsync(cancellationToken);

                return(new AuthUserDto(
                           user.Id,
                           user.FullName,
                           user.Email,
                           token,
                           refreshToken));
            }
Exemplo n.º 19
0
        /// <summary>
        /// Creates an Jwt for an employee if credentials are correct
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>token or null when credentials are invalid</returns>
        public async Task <TokenResponse> Handle(EmployeeLoginRequest request, CancellationToken cancellationToken)
        {
            // Load only the needed data from employee for initial check (without roles etc)
            Employee requestedEmployee = await _context.Employees
                                         .Select(e => new Employee()
            {
                Guid     = e.Guid,
                Username = e.Username,
                Password = e.Password
            })
                                         .FirstOrDefaultAsync(e => string.Equals(request.Username, e.Username, StringComparison.InvariantCultureIgnoreCase), cancellationToken);

            if (requestedEmployee == null)
            {
                _logger.LogWarning($"Failed login attempt with username: {request.Username}");

                throw new BadRequestException("The provided username or password is invalid");
            }

            if (!_hasher.PasswordMatches(request.Password, requestedEmployee.Password))
            {
                _logger.LogWarning($"Failed login attempt with username: {request.Username}");

                throw new BadRequestException("The provided username or password is invalid");
            }

            // Reload the employee with all his roles (department and self asigned)
            requestedEmployee = _context.Employees
                                .Include(e => e.Roles)
                                .ThenInclude(r => r.Role)
                                .Include(e => e.Department)
                                .ThenInclude(d => d.Roles)
                                .ThenInclude(r => r.Role)
                                .FirstOrDefault(e => e.Guid == requestedEmployee.Guid);

            var rolesFromUser       = requestedEmployee.Roles.Select(r => r.Role);
            var rolesFromDepartment = requestedEmployee.Department?.Roles?.Select(r => r?.Role);

            // add roles from employees department
            rolesFromUser = rolesFromDepartment != null &&
                            rolesFromDepartment.Count() > 0 ? rolesFromUser.Concat(rolesFromDepartment) : rolesFromUser;

            var token = _tokenGenerator.CreateToken(requestedEmployee, rolesFromUser);

            return(new TokenResponse()
            {
                Token = token
            });
        }
Exemplo n.º 20
0
            public async Task <UserEnvelope> Handle(Query message, CancellationToken cancellationToken)
            {
                var person = await _context.Persons
                             .AsNoTracking()
                             .FirstOrDefaultAsync(x => x.Username == message.Username, cancellationToken);

                if (person == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { User = Constants.NOT_FOUND });
                }
                var user = _mapper.Map <Domain.Person, User>(person);

                user.Token = await _jwtTokenGenerator.CreateToken(person.Username);

                return(new UserEnvelope(user));
            }
Exemplo n.º 21
0
            public async Task <UserDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var email = GetIdentifierFromExpiredToken(request.Token).Value;

                var user = await _context.Users.Include(u => u.RefreshTokens)
                           .SingleAsync(
                    x => x.Email == email && !x.Archived,
                    cancellationToken);

                if (user == null)
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                if (!user.IsValidRefreshToken(request.RefreshToken))
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                var refreshToken = _jwtTokenGenerator.GenerateRefreshToken();

                user.RemoveRefreshToken(request.RefreshToken);
                user.AddRefreshToken(
                    refreshToken,
                    user.Id);
                var token = await _jwtTokenGenerator.CreateToken(user.Email);

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserDto(
                           user.FirstName,
                           user.LastName,
                           user.FullName,
                           user.SystemName,
                           user.Email,
                           token,
                           refreshToken,
                           user.CurrencyRegionName,
                           user.UseDarkMode));
            }
Exemplo n.º 22
0
            public async Task <User> Handle(Query request, CancellationToken cancellationToken)
            {
                if (string.IsNullOrEmpty(request.Token))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Message = "Token must not be empty" });
                }

                var user = await context.AppUsers
                           .Include(x => x.RefreshTokens)
                           .Include(x => x.Photo)
                           .SingleOrDefaultAsync(u => u.RefreshTokens.Any(t => t.Token == request.Token),
                                                 cancellationToken: cancellationToken);

                if (user == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.NotFound);
                }

                var refreshToken = user.RefreshTokens.Single(x => x.Token == request.Token);

                if (!refreshToken.IsActive)
                {
                    throw new RestException(System.Net.HttpStatusCode.Forbidden);
                }

                var newRefreshToken = refreshTokenGenerator.GenerateRefreshToken(request.Ip);

                refreshToken.Revoked         = DateTime.Now;
                refreshToken.RevokedByIp     = request.Ip;
                refreshToken.ReplacedByToken = newRefreshToken.Token;
                user.RefreshTokens.Add(newRefreshToken);

                context.Update(user);
                await context.SaveChangesAsync(cancellationToken);

                var jwtToken = await jwtGenerator.CreateToken(user);

                return(new User()
                {
                    Username = user.UserName,
                    ImageUrl = user.Photo.Url,
                    JwtToken = jwtToken,
                    RefreshToken = newRefreshToken.Token
                });
            }
Exemplo n.º 23
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var person = await _context.Persons.Where(x => x.Email == message.User.Email).SingleOrDefaultAsync(cancellationToken);

                if (person == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.Unauthorized);
                }
                if (!person.Hash.SequenceEqual(_passwordHasher.Hash(message.User.Password, person.Salt)))
                {
                    throw new RestException(System.Net.HttpStatusCode.Unauthorized);
                }
                var user = _mapper.Map <Domain.Person, User>(person);

                user.Token = await _jwtTokenGenerator.CreateToken(person.Username);

                return(new UserEnvelope(user));
            }
Exemplo n.º 24
0
            public async Task <UserDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleOrDefaultAsync(
                    x => x.Email == request.Email && !x.Archived,
                    cancellationToken);

                if (user == null)
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                if (!user.Hash.SequenceEqual(
                        _passwordHasher.Hash(
                            request.Password,
                            user.Salt)))
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }
                // generate refresh token
                var refreshToken = _jwtTokenGenerator.GenerateRefreshToken();

                user.AddRefreshToken(refreshToken, user.Id);

                var token = await _jwtTokenGenerator.CreateToken(request.Email);

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserDto(
                           user.FirstName,
                           user.LastName,
                           user.FullName,
                           user.SystemName,
                           user.Email,
                           token,
                           refreshToken,
                           user.CurrencyRegionName,
                           user.UseDarkMode));
            }
Exemplo n.º 25
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleOrDefaultAsync(x => x.Email == message.User.Email, cancellationToken);

                if (user == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Invalid email / password." });
                }

                if (!user.Hash.SequenceEqual(_passwordHasher.Hash(message.User.Password, user.Salt)))
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Invalid email / password." });
                }

                var person = _mapper.Map <User, PublicUser>(user);

                person.Token = await _jwtTokenGenerator.CreateToken(person.Email);

                return(new UserEnvelope(person));
            }
Exemplo n.º 26
0
            protected override async Task <Result <User> > HandleCore(Command message)
            {
                var user = await SingleAsync(message.Email);

                if (await SingleAsync(message.Email) == null)
                {
                    return(Result.Fail <User> ("User does not exist"));
                }

                if (!user.HashedPassword.SequenceEqual(_passwordHasher.Hash(message.Password, user.Salt)))
                {
                    return(Result.Fail <User> ("User is not authorized"));
                }

                var loggedInUser = _mapper.Map <ApplicationUser, User> (user);

                loggedInUser.Token = await _jwtTokenGenerator.CreateToken(user.Username);

                return(Result.Ok(loggedInUser));
            }
Exemplo n.º 27
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var person = await _context.Persons.Where(p => p.Email == message.User.Email)
                             .SingleOrDefaultAsync(cancellationToken);

                if (person == null)
                {
                    throw new RestException(HttpStatusCode.BadRequest, "Invalid Email");
                }

                if (!person.PasswordHash.SequenceEqual(_passwordHasher.Hash(message.User.Password, person.PasswordSalt)))
                {
                    throw new RestException(HttpStatusCode.BadRequest, "Invalid password");
                }

                var user = _mapper.Map <Person, User>(person);

                user.Token = await _jwtTokenGenerator.CreateToken(person.PersonId);

                return(new UserEnvelope(user));
            }
Exemplo n.º 28
0
            public async Task <UserEnvelope> Handle(Query message, CancellationToken cancellationToken)
            {
                // Getting user
                var user = await _context
                           .Users
                           .AsNoTracking()
                           .FirstOrDefaultAsync(u => u.Login.Equals(message.Login, StringComparison.InvariantCultureIgnoreCase), cancellationToken);

                // Validations
                if (user == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Error = $"El usuario '{message.Login}' no existe." });
                }

                // Mapping
                var userEnvelope = _mapper.Map <User, UserEnvelope>(user);

                userEnvelope.Token = await _jwtTokenGenerator.CreateToken(user.Login);

                return(userEnvelope);
            }
Exemplo n.º 29
0
            public async Task <LoginUser> Handle(Command message, CancellationToken cancellationToken)
            {
                var user = await _context.Users.Where(x => x.Username == message.User.UserName).SingleOrDefaultAsync(cancellationToken);

                if (user == null)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Error = ErrorMessages.UserNameNotExists });
                }

                if (!user.Hash.SequenceEqual(_passwordHasher.Hash(message.User.Password, user.Salt)))
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Error = ErrorMessages.IncorrectPassword });
                }
                var noticeCount = await _context.Alerts.CountAsync(x => x.Status == AlertStatus.New, cancellationToken);

                var newUser = _mapper.Map <Models.User, LoginUser>(user);

                newUser.Token = await _jwtTokenGenerator.CreateToken(user.Username);

                newUser.NoticeCount = noticeCount;

                return(newUser);
            }