Exemplo n.º 1
0
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var organisation = UnitOfWork.OrganisationRepository.FindByName(model.OrganisationName);

            if (organisation == null)
            {
                ModelState.AddModelError("Organisation", "Organisation was not found!");
                return(BadRequest(ModelState));
            }

            var user = new OrgUser()
            {
                FirstName      = model.FirstName,
                Surname        = model.Surname,
                UserName       = model.Email,
                Email          = model.Email,
                OrganisationId = organisation.Id,
                IsRootUser     = false,
                IsActive       = true,
                TypeId         = OrgUserTypesRepository.TeamUser.Id,
                IsMobileUser   = true,
                IsWebUser      = true, // this should be 'false' in live production.
                IsSubscribed   = false,
                AccountType    = AccountType.MobileAccount
            };

            if (!string.IsNullOrEmpty(model.Address))
            {
                user.Address = model.Address;
            }

            if (!string.IsNullOrEmpty(model.Gender))
            {
                user.Gender = (User.GenderType)Enum.Parse(typeof(User.GenderType), model.Gender);
            }

            if (model.Birthdate.HasValue)
            {
                var localValue = TimeZone.CurrentTimeZone.ToLocalTime(model.Birthdate.Value);
                user.Birthdate = new DateTime(localValue.Year, localValue.Month, localValue.Day, 0, 0, 0, DateTimeKind.Utc);
            }

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            user.Type = UnitOfWork.OrgUserTypesRepository.Find(user.TypeId);
            UnitOfWork.UserManager.AssignRolesByUserType(user);

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

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

            // assign this user to their project.
            var assignment = new Assignment()
            {
                ProjectId    = project.Id,
                OrgUserId    = user.Id,
                CanView      = true,
                CanAdd       = true,
                CanEdit      = false,
                CanDelete    = false,
                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(user.Id);

            _orgUser.CurrentProjectId = project.Id;

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

            // subscribe this user under OnRecord with full access.
            if (_orgUser.AccountType == AccountType.MobileAccount && !_orgUser.Subscriptions.Any())
            {
                var onrecord = UnitOfWork.OrganisationRepository.AllAsNoTracking
                               .Where(x => x.Name == "OnRecord")
                               .SingleOrDefault();

                var subscription = new Subscription
                {
                    IsActive       = true,
                    Type           = UserSubscriptionType.Organisation,
                    StartDate      = DateTimeService.UtcNow,
                    EndDate        = null,
                    Note           = $"Joined organisation - OnRecord",
                    OrgUserId      = user.Id,
                    OrganisationId = onrecord.Id
                };

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

                UnitOfWork.Save();
            }

            // send account confirmation email
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.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={user.Id}&code={encodedCode}";

            var content = @"<p>Your new account has been created. To complete your registration please confirm your email address by clicking the link below.</p>
                            <p><a href='" + callbackUrl + @"'>Verify Email Address</a></p>";

            var messageBody = WebHelpers.GenerateEmailTemplate(content, "Confirm your registration");
            await UserManager.SendEmailAsync(user.Id, "Confirm your account", messageBody);

            // find email recipients
            var recipients = UnitOfWork.EmailRecipientsRepository.AllAsNoTracking
                             .Where(x => x.NewMobileUsers == true)
                             .ToList();

            var url = $"{Request.RequestUri.Scheme}://{Request.RequestUri.Authority}/{WebHelpers.GetRootIndexPath()}#!/users/mobile/";

            foreach (var recipient in recipients)
            {
                var emailContent = $"<p>First name: {model.FirstName}</p>" +
                                   $"<p>Surname: {model.Surname}</p>" +
                                   $"<p>Email: {model.Email}</p><br>" +
                                   $"<p>View <a href='{url}'>mobile users</a> on the dashboard.</p>";

                var recipientEmail = new Email
                {
                    To      = recipient.OrgUser.Email,
                    Subject = "A new mobile user has joined OnRecord",
                    Content = WebHelpers.GenerateEmailTemplate(emailContent, "A new mobile user has joined OnRecord")
                };

                UnitOfWork.EmailsRepository.InsertOrUpdate(recipientEmail);
            }

            try
            {
                UnitOfWork.Save();
                return(Ok());
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }