Esempio n. 1
0
        public async Task <ServiceResponse> UserRegistration(UserRegistrationRequestDto request)
        {
            var response = new ServiceResponse {
                ErrorList = new List <ErrorMessage>()
            };

            request.FirstName = request.FirstName?.TitleCase();
            request.LastName  = request.LastName?.TitleCase();
            request.UserName  = request.UserName?.LowerCase();
            request.Password  = _encryptData.EncryptPassword(request.Password);
            request.UserEmail = request.UserEmail?.LowerCase();
            request.Remarks   = request.Remarks?.TitleCase();
            request.Active    = true;
            var user = _mapper.Map <IM_USERS>(request);

            // to fix an issue related to claims generation during login
            if (string.IsNullOrEmpty(user.LASTNAME))
            {
                user.LASTNAME = "";
            }

            user.CreatedBy   = "SYSTEM";
            user.CreatedDate = DateTime.Now;
            user.ID          = Guid.NewGuid().ToString();

            _transactionalUnitOfWork.SetIsActive(false);

            await _transactionalUnitOfWork.CommitAsync();

            _userRepository.Add(user);

            var contributorGroup = await _groupsRepository.GetReadOnlyAsync(x => x.NAME == "CONTRIBUTORS");

            if (contributorGroup == null)
            {
                throw new BadRequestException("Unable to assign access to user");
            }

            var addUserGroup = new IM_USERS_GROUPS
            {
                ID          = Guid.NewGuid().ToString(),
                CreatedBy   = "ADMIN",
                CreatedDate = DateTime.Now,
                GROUP_ID    = contributorGroup.ID,
                ACTIVE      = true,
                USER_NAME   = user.USERNAME
            };

            _transactionalUnitOfWork.SetIsActive(true);

            _usersGroupsRepository.Add(addUserGroup);

            var committedRows = await _transactionalUnitOfWork.CommitAsync();

            if (committedRows > 0)
            {
                response.Success = true;
                response.Msg     = "User registered successfully";
            }
            else
            {
                response.Success = false;
                response.Msg     = "Failed to register user";
            }

            var recipients = new List <EmailRecipientDto>
            {
                new EmailRecipientDto
                {
                    RecipientName         = $"{user.FIRSTNAME} {user.LASTNAME}",
                    RecipientEmailAddress = user.USEREMAIL
                }
            };

            var newUserRegistrationEmailTemplate =
                await _templateSettingRepository.GetReadOnlyAsync(x => x.KEY == "NEW_USER_TEMPLATE");

            if (newUserRegistrationEmailTemplate != null)
            {
                var emailTemplateString = newUserRegistrationEmailTemplate.VALUE;

                if (!string.IsNullOrEmpty(emailTemplateString))
                {
                    var emailHtmlBody = emailTemplateString.Replace("{username}", $"{user.FIRSTNAME} {user.LASTNAME}")
                                        // TODO: get application ui url from appsettings
                                        .Replace("{link}", "https://www.google.com");

                    await EmailNotificationHelper.SendEmailNotification(_configuration.GetSection("SendGridAPIKey").Value,
                                                                        newUserRegistrationEmailTemplate.NAME, emailHtmlBody, "", recipients);
                }
            }



            return(await Task.Run(() => response));
        }
        /// <summary>
        /// Method added to serve User Login request
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private async Task <LoginResponseDto> UserLogin(LoginRequestDto request)
        {
            var loginResponse = new LoginResponseDto();

            request.UserName = request.UserName.LowerCase();
            request.Password = _encryptData.EncryptPassword(request.Password);

            var getUser = await _userRepository.GetReadOnlyAsync(x =>
                                                                 x.ACTIVE == true &&
                                                                 x.USERNAME == request.UserName &&
                                                                 x.PASSWORD == request.Password);

            if (getUser == null)
            {
                throw new BadRequestException("Either username or password you have entered is incorrect!");
            }

            loginResponse.UserName = getUser.USERNAME;

            bool.TryParse(_config["AuthenticationMode:IsValidateOnlyLogin"], out var isValidateOnlyLogin);
            if (isValidateOnlyLogin)
            {
                loginResponse.IsUserAuthenticated = true;
                loginResponse.UserActive          = getUser.ACTIVE;
                loginResponse.FirstName           = getUser.FIRSTNAME;
                loginResponse.LastName            = getUser.LASTNAME;
                loginResponse.Email = getUser.USEREMAIL;
                return(await Task.Run(() => loginResponse));
            }

            var userGroups = new List <string>();

            var selectedGroupIds = _usersGroupsRepository
                                   .GetAllReadOnly(x => x.ACTIVE == true && x.USER_NAME == request.UserName).Select(x => x.GROUP_ID)
                                   .ToArray();

            foreach (var res in selectedGroupIds)
            {
                string groupName = (await _groupsRepository.GetReadOnlyAsync(x => x.ID == res)).NAME;
                userGroups.Add(groupName);
            }

            if (!userGroups.Any())
            {
                throw new UnauthorizedAccessException("Not authorized to access");
            }

            var orgUnitQuery = _groupsOuRepository.GetAllReadOnly(
                port => userGroups.Contains(port.Group.NAME) && port.ACTIVE, null, null, null, nameof(IM_GROUPS_OU.Group), nameof(IM_GROUPS_OU.Ou));

            var orgUnitList = orgUnitQuery.Select(p => new OUResponseDto {
                Code = p.Ou.CODE, Name = p.Ou.NAME
            })
                              .Distinct().ToList();

            var userOrganization = _companyRepository
                                   .GetAllReadOnly(
                item => item.ImOus.Any(a => orgUnitList.Select(b => b.Code).Contains(a.CODE)) &&
                item.ACTIVE == true, null, null, null, nameof(IM_COMPANY.ImOus))
                                   .Select(a => new CompanyResponseDto {
                Name = a.NAME, Code = a.DOMAIN
            }).ToList();

            loginResponse.IsUserAuthenticated = userGroups.Any() ? true : false;
            loginResponse.UserGroup           = userGroups.ToArray();
            loginResponse.UserActive          = getUser.ACTIVE;
            loginResponse.FirstName           = getUser.FIRSTNAME;
            loginResponse.LastName            = getUser.LASTNAME;
            loginResponse.OrganizationUnits   = orgUnitList;
            loginResponse.Email         = getUser.USEREMAIL;
            loginResponse.Organizations = userOrganization;
            return(await Task.Run(() => loginResponse));
        }