public async Task <IActionResult> CreateSubAdministrator([FromBody] UserRequest userRequest)
        {
            if (userRequest == null)
            {
                _logger.LogError("CreateSubAdministrator: userRequest object sent from client is null.");
                return(BadRequest("userRequest object is null"));
            }
            if (!ModelState.IsValid)
            {
                _logger.LogError("CreateSubAdministrator: Invalid userRequest object sent from client.");
                return(BadRequest("Invalid userRequest object"));
            }
            var user = await _userManager.FindByNameAsync(userRequest.UserName);

            if (user != null)
            {
                _logger.LogError("CreateSubAdministrator: username already exists.");
                return(BadRequest("Username already exists"));
            }
            user = new IdentityUser {
                UserName = userRequest.UserName
            };
            var passwordValidator = new PasswordValidator <IdentityUser>();

            if (!(await passwordValidator.ValidateAsync(_userManager, null, userRequest.Password)).Succeeded)
            {
                _logger.LogError("CreateSubAdministrator: Provided password is not strong enough.");
                return(BadRequest("Provided password is not strong enough"));
            }
            await _userManager.CreateAsync(user, userRequest.Password);

            var subAdministrator = new SubAdministrator {
                UserId = user.Id
            };

            _coadaptService.SubAdministrator.CreateSubAdministrator(subAdministrator);
            await _coadaptService.SaveAsync();

            if (!await _roleManager.RoleExistsAsync(Role.SubAdministratorRole))
            {
                await _roleManager.CreateAsync(new IdentityRole(Role.SubAdministratorRole));
            }
            await _userManager.AddToRoleAsync(user, Role.SubAdministratorRole);

            return(CreatedAtRoute("SubAdministratorById", new { id = subAdministrator.Id }, subAdministrator));
        }
Exemple #2
0
        private static async Task <IdentityUser> CreateUser(IServiceProvider serviceProvider,
                                                            string testUserPw, string userName, string role, string code = "")
        {
            var logger      = serviceProvider.GetRequiredService <ILoggerManager>();
            var userManager = serviceProvider.GetService <UserManager <IdentityUser> >();

            if (userManager == null)
            {
                throw new Exception("User manager is null");
            }
            var user = await userManager.FindByNameAsync(userName);

            if (user == null)
            {
                user = new IdentityUser {
                    UserName = userName
                };
                await userManager.CreateAsync(user, testUserPw);

                logger.LogInfo($"User {user.UserName} created");
                var coadaptService = serviceProvider.GetRequiredService <IRepositoryWrapper>();
                if (role.Equals(Role.AdministratorRole))
                {
                    var adminUser = new Administrator {
                        UserId = user.Id
                    };
                    coadaptService.Administrator.CreateAdministrator(adminUser);
                    await coadaptService.SaveAsync();

                    logger.LogInfo($"Administrator entry with ID {adminUser.Id} created on {adminUser.CreatedOn}");
                }
                else if (role.Equals(Role.SubAdministratorRole))
                {
                    var subAdminUser = new SubAdministrator {
                        UserId = user.Id
                    };
                    coadaptService.SubAdministrator.CreateSubAdministrator(subAdminUser);
                    await coadaptService.SaveAsync();

                    logger.LogInfo($"Sub-administrator entry with ID {subAdminUser.Id} created on {subAdminUser.CreatedOn}");
                }
                else if (role.Equals(Role.SupervisorRole))
                {
                    var supervisorUser = new Supervisor {
                        UserId = user.Id
                    };
                    coadaptService.Supervisor.CreateSupervisor(supervisorUser);
                    await coadaptService.SaveAsync();

                    logger.LogInfo($"Supervisor entry with ID {supervisorUser.Id} created on {supervisorUser.CreatedOn}");
                }
                else if (role.Equals(Role.TherapistRole))
                {
                    var therapistUser = new Therapist {
                        UserId = user.Id
                    };
                    coadaptService.Therapist.CreateTherapist(therapistUser);
                    await coadaptService.SaveAsync();

                    logger.LogInfo($"Therapist entry with ID {therapistUser.Id} created on {therapistUser.CreatedOn}");
                }
                else if (role.Equals(Role.ParticipantRole))
                {
                    var participantUser = new Participant {
                        UserId = user.Id, Code = code
                    };
                    coadaptService.Participant.CreateParticipant(participantUser);
                    await coadaptService.SaveAsync();

                    coadaptService.Participant.DetachParticipant(participantUser);
                    logger.LogInfo($"Participant entry with ID {participantUser.Id} created on {participantUser.CreatedOn}");
                }
                var roleManager = serviceProvider.GetService <RoleManager <IdentityRole> >();
                if (roleManager == null)
                {
                    throw new Exception("Role manager is null");
                }
                if (!await roleManager.RoleExistsAsync(role))
                {
                    await roleManager.CreateAsync(new IdentityRole(role));

                    logger.LogInfo($"{role} role created");
                }
                else
                {
                    logger.LogWarn($"{role} role already exists!");
                }
                await userManager.AddToRoleAsync(user, role);
            }
            else
            {
                logger.LogWarn($"User {userName} already exists!");
            }
            return(user);
        }
        public async Task <IActionResult> UpdateSite(int id, [FromBody] SiteRequest siteRequest)
        {
            if (siteRequest == null)
            {
                _logger.LogError("UpdateSite: SiteRequest object sent from client is null.");
                return(BadRequest("SiteRequest object is null"));
            }
            if (!ModelState.IsValid)
            {
                _logger.LogError("UpdateSite: Invalid SiteRequest object sent from client.");
                return(BadRequest("Invalid SiteRequest object"));
            }
            var dbSite = await _coadaptService.Site.GetSiteByIdAsync(id);

            if (dbSite.IsEmptyObject())
            {
                _logger.LogError($"UpdateSite: Site with ID {id} not found.");
                return(NotFound("Site with requested ID does not exist"));
            }
            string           userId           = HttpContext.User.Claims.Single(x => x.Type == "id").Value;
            string           role             = HttpContext.User.Claims.Single(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Value;
            SubAdministrator subAdministrator = new SubAdministrator();
            Organization     organization     = new Organization();
            Supervisor       supervisor       = new Supervisor();
            var originalStudy = await _coadaptService.Study.GetStudyByIdAsync(dbSite.StudyId);

            if (role == Role.SubAdministratorRole)
            {
                subAdministrator = await _coadaptService.SubAdministrator.GetSubAdministratorByUserIdAsync(userId);

                organization = await _coadaptService.Organization.GetOrganizationBySubAdministratorIdAsync(subAdministrator.Id);

                if (organization.IsEmptyObject())
                {
                    _logger.LogWarn($"UpdateSite: Currently logged in sub-administrator is not assigned to any organization!");
                    return(BadRequest("Currently logged in sub-administrator is not assigned to any organization"));
                }
                if (originalStudy.OrganizationId != organization.Id)
                {
                    _logger.LogWarn($"UpdateSite: Study of updated site does not belong to the organization of the currently logged in sub-administrator!");
                    return(BadRequest("Study of updated site does not belong to the organization of the currently logged in sub-administrator"));
                }
            }
            else if (role == Role.SupervisorRole)
            {
                supervisor = await _coadaptService.Supervisor.GetSupervisorByUserIdAsync(userId);

                if (originalStudy.SupervisorId != supervisor.Id)
                {
                    _logger.LogWarn($"UpdateSite: Study of updated site does not belong to the currently logged in supervisor!");
                    return(BadRequest("Study of updated site does not belong to the currently logged in supervisor"));
                }
            }
            if (siteRequest.StudyId == 0)
            {
                siteRequest.StudyId = dbSite.StudyId;
            }
            if (siteRequest.StudyId != dbSite.StudyId)
            {
                var study = await _coadaptService.Study.GetStudyByIdAsync(siteRequest.StudyId);

                if (study.IsEmptyObject())
                {
                    _logger.LogError($"UpdateSite: Study with ID {siteRequest.StudyId} not found.");
                    return(BadRequest("Study with requested ID does not exist"));
                }
                if (role == Role.SubAdministratorRole)
                {
                    if (study.OrganizationId != organization.Id)
                    {
                        _logger.LogWarn($"UpdateSite: Requested study does not belong to the organization of the currently logged in sub-administrator!");
                        return(BadRequest("Requested study does not belong to the organization of the currently logged in sub-administrator"));
                    }
                }
                else if (role == Role.SupervisorRole)
                {
                    if (study.SupervisorId != supervisor.Id)
                    {
                        _logger.LogWarn($"UpdateSite: Requested study does not belong to the currently logged in supervisor!");
                        return(BadRequest("Requested study does not belong to the currently logged in supervisor"));
                    }
                }
            }
            if (siteRequest.Shortname == "")
            {
                siteRequest.Shortname = dbSite.Shortname;
            }
            if (siteRequest.Shortname != dbSite.Shortname)
            {
                var siteOfSameShortname = await _coadaptService.Site.GetSiteOfStudyByShortnameAsync(siteRequest.Shortname, siteRequest.StudyId);

                if (!siteOfSameShortname.IsEmptyObject())
                {
                    _logger.LogError($"UpdateSite: Site with same short name already exists in study!");
                    return(BadRequest("Site with same short name already exists in study"));
                }
            }
            if (siteRequest.Name == "")
            {
                siteRequest.Name = dbSite.Name;
            }
            var site = new Site {
                Name = siteRequest.Name, Shortname = siteRequest.Shortname, StudyId = siteRequest.StudyId
            };

            _coadaptService.Site.UpdateSite(dbSite, site);
            await _coadaptService.SaveAsync();

            return(NoContent());
        }
 public static void Map(this SubAdministrator dbSubAdministrator, SubAdministrator subAdministrator)
 {
     dbSubAdministrator.UserId    = subAdministrator.UserId;
     dbSubAdministrator.CreatedOn = subAdministrator.CreatedOn;
 }