예제 #1
0
        public IHttpActionResult Put(Guid id, [FromBody] OrgUserDTO value)
        {
            if (id == Guid.Empty)
            {
                return(BadRequest("id is empty"));
            }

            var orguser = UnitOfWork.OrgUsersRepository.Find(id);

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

            orguser.Email          = value.Email;
            orguser.EmailConfirmed = value.EmailConfirmed;
            orguser.FirstName      = value.FirstName;
            orguser.Surname        = value.Surname;
            orguser.TypeId         = value.Type.Id;
            orguser.IsWebUser      = value.IsWebUser;
            orguser.IsMobileUser   = value.IsMobileUser;
            orguser.Gender         = value.Gender;
            orguser.Birthdate      = value.Birthdate;
            orguser.Address        = value.Address;

            if (!orguser.PhoneNumberConfirmed)
            {
                orguser.PhoneNumber = string.IsNullOrEmpty(value.PhoneNumber) ? null : value.PhoneNumber;
            }

            if (CurrentUser is SuperUser || CurrentUser is PlatformUser)
            {
                if (value.CurrentProject != null)
                {
                    if (Guid.Parse(value.CurrentProject.Organisation.Id) != orguser.Organisation.Id)
                    {
                        return(BadRequest("The selected current project does not belong to this user's organisation"));
                    }

                    orguser.CurrentProjectId = value.CurrentProject.Id;
                }
            }

            try
            {
                var result = UnitOfWork.UserManager.UpdateSync(orguser);
                if (result.Succeeded)
                {
                    MemoryCacher.DeleteStartingWith(CACHE_KEY);
                    return(Ok());
                }
                else
                {
                    return(BadRequest(result.Errors.ToString(", ")));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
예제 #2
0
        public async Task <IHttpActionResult> Post([FromBody] OrgUserDTO value)
        {
            // not necessary to validate password,
            // because we generate a random password and
            // send it as part of the account confirmation email.
            //if (string.IsNullOrEmpty(value.Password))
            //    ModelState.AddModelError("Password", "Please provide password.");

            //if (value.Password != value.ConfirmPassword)
            //    ModelState.AddModelError("ConfirmPassword", "'Password' and 'Confirm password' must be the same.");

            if (value.AccountType == AccountType.MobileAccount)
            {
                // the OrgUserType property is hidden in mobile-users' edit form.
                // so the Type is null at this point. fetch and populate.
                // TeamUser Type ID: 379c989a-9919-4338-a468-a7c20eb76e28

                var teamUserType = UnitOfWork.OrgUserTypesRepository
                                   .AllAsNoTracking
                                   .Where(x => x.SystemName == "TeamUser")
                                   .SingleOrDefault();

                value.Type = Mapper.Map <OrgUserTypeDTO>(teamUserType);
            }

            var orguser = Mapper.Map <OrgUser>(value);

            orguser.UserName = orguser.Email;

            if (CurrentUser is SuperUser || CurrentUser is PlatformUser)
            {
                orguser.OrganisationId = Guid.Parse(value.Organisation.Id);
                orguser.Organisation   = null;
            }
            else if (CurrentUser is OrgUser)
            {
                orguser.OrganisationId = CurrentOrgUser.OrganisationId.Value;
            }

            // generate a random password
            var randomPassword = System.Web.Security.Membership.GeneratePassword(12, 1);
            var identityResult = ServiceContext.UserManager.CreateSync(orguser, randomPassword);

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.ToString(". "));
            }

            // assign roles by type.
            orguser.Type = UnitOfWork.OrgUserTypesRepository.Find(orguser.TypeId);
            UnitOfWork.UserManager.AssignRolesByUserType(orguser);

            var organisation = UnitOfWork.OrganisationRepository.Find(orguser.OrganisationId.Value);

            if (value.Type.Name.ToLower() == "administrator")
            {
                var projects = UnitOfWork.ProjectsRepository
                               .AllAsNoTracking
                               .Where(p => p.OrganisationId == orguser.OrganisationId.Value)
                               .Select(x => x.Id)
                               .ToList();

                foreach (var projectId in projects)
                {
                    var orgUserAssignment = new Assignment
                    {
                        ProjectId    = projectId,
                        OrgUserId    = orguser.Id,
                        CanView      = true,
                        CanAdd       = true,
                        CanEdit      = true,
                        CanDelete    = true,
                        CanExportPdf = true,
                        CanExportZip = true
                    };

                    UnitOfWork.AssignmentsRepository.InsertOrUpdate(orgUserAssignment);
                }

                UnitOfWork.Save();
            }

            // create a project for this user
            var project = new Project()
            {
                Name           = $"{orguser.FirstName} {orguser.Surname}",
                StartDate      = DateTimeService.UtcNow,
                OrganisationId = organisation.Id,
                CreatedById    = orguser.Id
            };

            UnitOfWork.ProjectsRepository.InsertOrUpdate(project);
            UnitOfWork.Save();

            // assign this user to their project.
            var assignment = new Assignment()
            {
                ProjectId    = project.Id,
                OrgUserId    = orguser.Id,
                CanView      = true,
                CanAdd       = true,
                CanEdit      = true,
                CanDelete    = true,
                CanExportPdf = true,    // temporary. turn off in production.
                CanExportZip = true     // temporary. turn off in production.
            };

            UnitOfWork.AssignmentsRepository.InsertOrUpdate(assignment);

            // assign organisation admin to this project
            if (organisation.RootUser != null)
            {
                UnitOfWork.AssignmentsRepository.InsertOrUpdate(new Assignment
                {
                    ProjectId    = project.Id,
                    OrgUserId    = organisation.RootUserId.Value,
                    CanView      = true,
                    CanAdd       = true,
                    CanEdit      = true,
                    CanDelete    = true,
                    CanExportPdf = true,
                    CanExportZip = true
                });
            }

            UnitOfWork.Save();

            // set user's current project
            var _orgUser = UnitOfWork.OrgUsersRepository.Find(orguser.Id);

            _orgUser.CurrentProjectId = project.Id;

            UnitOfWork.OrgUsersRepository.InsertOrUpdate(_orgUser);
            UnitOfWork.Save();

            // subscribe this user to the current organization
            if (!_orgUser.Subscriptions.Any())
            {
                var subscription = new Subscription
                {
                    IsActive       = true,
                    Type           = UserSubscriptionType.Organisation,
                    StartDate      = DateTimeService.UtcNow,
                    EndDate        = null,
                    Note           = $"Joined organisation - {organisation.Name}",
                    OrgUserId      = _orgUser.Id,
                    OrganisationId = organisation.Id
                };

                UnitOfWork.SubscriptionsRepository.InsertOrUpdate(subscription);
                _orgUser.IsSubscribed = true;

                UnitOfWork.Save();
            }

            // send account confirmation email
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(orguser.Id);

            var encodedCode = HttpUtility.UrlEncode(code);

            var rootIndex   = WebHelpers.GetRootIndexPath();
            var baseUrl     = $"{Request.RequestUri.Scheme}://{Request.RequestUri.Authority}/{rootIndex}";
            var callbackUrl = $"{baseUrl}#!/verify-email?userId={orguser.Id}&code={encodedCode}";

            var content = @"<p>Complete your registration by verifying your email address. Click the link below to continue.</p>
                            <p><a href='" + callbackUrl + @"'>Verify Email Address</a></p><br>
                            <p>Your password is <strong>" + randomPassword + @"</strong></p>
                            <p>Make sure to change your password after you've signed in.</p>
                            <p>For more information please read our <a href='https://onrecord.tech/privacy-policy/' target='_blank'>privacy policy</a> guide.</p>";

            var emailBody = WebHelpers.GenerateEmailTemplate(content, "Welcome to OnRecord");

            await UserManager.SendEmailAsync(orguser.Id, "Confirm your account", emailBody);

            MemoryCacher.DeleteStartingWith(CACHE_KEY);

            return(Ok());
        }