Exemplo n.º 1
0
        public async Task <ActionResult> Register(RegisterViewModel Model)
        {
            var isAdmin = string.IsNullOrWhiteSpace(Model.InvitationCode);

            //if it is invited user, then company name will be null. Fill it to avoid false model error
            if (!isAdmin)
            {
                Model.CompanyDetails.CompanyName = "Company Name";
            }

            if (ModelState.IsValid)
            {
                AspNetUsers   aspNetUser         = new AspNetUsers();
                SiteUsers     siteUser           = new SiteUsers();
                SiteCompanies company            = new SiteCompanies();
                bool?         invitationAccepted = null;

                using (ePontiv2Entities db = new ePontiv2Entities())
                    using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        CommonRepository repo = new CommonRepository(db);

                        //Site Company
                        if (!isAdmin)
                        {
                            aspNetUser = db.AspNetUsers.AsNoTracking().Where(p => p.InvitationCode == Model.InvitationCode && p.InvitationAccepted != true).FirstOrDefault();
                            if (aspNetUser == null)
                            {
                                ModelState.AddModelError("", "Invitation code invalid or expired.");
                                return(View(Model));
                            }

                            siteUser = db.SiteUsers.Where(p => p.ASPNetUserID == aspNetUser.Id).FirstOrDefault();
                            if (siteUser == null)
                            {
                                ModelState.AddModelError("", "Invitation code invalid or expired.");
                                return(View(Model));
                            }

                            company = db.SiteCompanies.Where(p => p.SiteCoID == siteUser.SiteCoID).FirstOrDefault();
                            if (company == null)
                            {
                                ModelState.AddModelError("", "Invitation code invalid or expired.");
                                return(View(Model));
                            }

                            invitationAccepted             = true;
                            Model.CompanyDetails.CompanyID = company.SiteCoID;
                        }
                        else
                        {
                            #region Add New Company

                            var co = Model.CompanyDetails;

                            int status = repo.AddNewSiteCompany(new SiteCompanies()
                            {
                                CoName     = co.CompanyName,
                                CoAddress1 = co.Address1,
                                CoAddress2 = co.Address2,
                                CoCity     = co.City,
                                CoState    = co.State,
                                CoZip      = co.Zip,
                                CoCountry  = co.Country,
                                CoPhone    = co.Phone
                            });

                            if (status == -1)
                            {
                                ModelState.AddModelError("", "Company already registered. Please contact your company for invitation.");
                                return(View(Model));
                            }

                            Model.CompanyDetails.CompanyID = status;
                            db.InsertNewCoData(status);
                            db.SaveChanges();

                            //db.InsertFirstLicense(status,DateTime.Now,d)
                            #endregion
                        }

                        //ASP Net User
                        var emailAlreadyExists = db.AspNetUsers.Where(p => p.Email == Model.Email && //check for same email
                                                                      p.Id != aspNetUser.Id) // ignore user's own email - in case for invited user
                                                 .Any();
                        if (emailAlreadyExists)
                        {
                            ModelState.AddModelError("", "Email already registered.");
                            return(View(Model));
                        }

                        string aspNetUserID;
                        if (isAdmin)
                        {
                            var user = new ApplicationUser
                            {
                                UserName    = Model.Email,
                                Email       = Model.Email,
                                PhoneNumber = Model.Phone,
                                //siteuserid = Model.CompanyDetails.CompanyID
                            };

                            var userCreateStatus = await UserManager.CreateAsync(user, Model.Password);

                            if (userCreateStatus.Succeeded == false)
                            {
                                AddErrors(userCreateStatus);
                                return(View(Model));
                            }

                            aspNetUserID = user.Id;

                            //var roleStore = new Microsoft.AspNet.Identity.EntityFramework.RoleStore<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(context);
                            //var roleManager = new RoleManager<IdentityRole>(roleStore);

                            // UserManager.AddToRole(aspNetUserID, EnumWrapper.SiteUserRoles.admin.ToString());
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            db.InsertFirstUserBySiteID(Model.CompanyDetails.CompanyID, user.Id, string.Format("{0} {1}", Model.FirstName, Model.LastName), Model.FirstName, Model.LastName, "", user.Email, user.PasswordHash, user.SecurityStamp, user.PhoneNumber);
                            db.SaveChanges();
                        }
                        else
                        {
                            aspNetUserID           = aspNetUser.Id;
                            aspNetUser.UserName    = Model.Email;
                            aspNetUser.Email       = Model.Email;
                            aspNetUser.PhoneNumber = Model.Phone;

                            UserManager.AddToRole(aspNetUserID, EnumWrapper.SiteUserRoles.user.ToString());

                            //set password
                            string passwordResetCode = await UserManager.GeneratePasswordResetTokenAsync(aspNetUserID);

                            var result = await UserManager.ResetPasswordAsync(aspNetUserID, passwordResetCode, Model.Password);

                            if (!result.Succeeded)
                            {
                                ModelState.AddModelError("", "Some error occurred. Please retry.");
                                return(View(Model));
                            }


                            await SignInManager.SignInAsync(UserManager.FindById(aspNetUserID), isPersistent : false, rememberBrowser : false);
                        }


                        //site user
                        //if (isAdmin)
                        //{
                        //    siteUser = new SiteUsers();
                        //    db.SiteUsers.Add(siteUser);
                        //}
                        if (!isAdmin)
                        {
                            siteUser.ASPNetUserID    = aspNetUserID;
                            siteUser.SiteCoID        = Model.CompanyDetails.CompanyID;
                            siteUser.UserFirstName   = Model.FirstName;
                            siteUser.UserLastName    = Model.LastName;
                            siteUser.UserDisplayName = string.Format("{0} {1}", Model.FirstName, Model.LastName);
                            siteUser.UserStatus      = "Active";
                            siteUser.TimeZoneID      = 1;

                            db.SaveChanges();

                            aspNetUser = db.AspNetUsers.Where(p => p.Id == aspNetUserID).FirstOrDefault();
                            if (aspNetUser != null)
                            {
                                aspNetUser.siteuserid = siteUser.SiteUserID;
                                aspNetUser.sitecoid   = siteUser.SiteCoID ?? 0;
                                if (invitationAccepted.HasValue)
                                {
                                    aspNetUser.InvitationAccepted = invitationAccepted;
                                }
                                db.SaveChanges();
                            }
                        }

                        tran.Complete();

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        //return RedirectToAction("Index", "Home");
                    }
                if (isAdmin)
                {
                    return(RedirectToAction("Welcome"));
                }
                else
                {
                    return(RedirectToAction("Index", "Dashboard", new { area = "Sections" }));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(Model));
        }