Beispiel #1
0
        /// <summary>
        /// Author: BOS Framework, Inc
        /// Description: Triggers when the Register button is clicked
        /// </summary>
        /// <param name="registerObj"></param>
        /// <returns></returns>
        public async Task <ActionResult> RegisterUser(RegistrationModel registerObj)
        {
            try
            {
                if (HttpContext != null && !HttpContext.Request.Cookies.ContainsKey(".AspNet.Consent"))
                {
                    if (_bosAuthClient == null)
                    {
                        var response = await _multitenantService.GetGeneratedToken();

                        SetAuthClient();
                    }
                    ModelState.AddModelError("CustomError", "Before proceeding, please 'Accept' our Cookies' terms.");
                    return(View("Register"));
                }
                //Removing the whitespaces in the form-data
                registerObj.EmailAddress = registerObj.EmailAddress.Trim();
                registerObj.FirstName    = registerObj.FirstName.Trim();
                registerObj.LastName     = registerObj.LastName.Trim();
                var password = CreatePassword();

                /* --------- LOGIC
                 * Make a call to the BOS Auth API to create a new user record
                 * Then extend the user's attributes with demographic information like FirstName and the like
                 * On success, set-up the user's role to the default "user" role
                 * After this, send an email to the user with a link to verify his email and setup a new password to the application
                 *       - Get the templatedID from BOS that will be used in the email
                 *       - Get the Service ProviderId that will be used to send the email
                 *       - Prepare the EmailObj that will be used to send the email
                 */

                var result = await _bosAuthClient.AddNewUserAsync <BOSUser>(registerObj.EmailAddress, registerObj.EmailAddress, password); //Making the BOS API Call to add the user's record

                if (result != null)
                {
                    if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(RedirectToAction("SignOut", "Auth"));
                    }
                    if (result.IsSuccessStatusCode)
                    {
                        /* Preparing the user's object with any required information. This can be customised to any properties per the application requirement
                         * An Example -
                         * User user = new User
                         * {
                         *  Id = result.User.Id,
                         *  CreatedOn = DateTime.UtcNow,
                         *  Email = registerObj.EmailAddress,
                         *  FName = registerObj.FirstName,
                         *  LName = registerObj.LastName,
                         *  Gender = 'M',
                         *  PhoneNumber = "123-555-1234"
                         * };
                         */
                        User user = new User
                        {
                            Id             = result.User.Id,
                            CreatedOn      = DateTime.UtcNow,
                            Deleted        = false,
                            Email          = registerObj.EmailAddress,
                            FirstName      = registerObj.FirstName,
                            LastModifiedOn = DateTime.UtcNow,
                            LastName       = registerObj.LastName,
                            Username       = registerObj.EmailAddress,
                            Active         = true
                        };
                        var extendUserResponse = await _bosAuthClient.ExtendUserAsync(user); //Making a calling to the BOS API, to update the user's information

                        if (extendUserResponse.IsSuccessStatusCode)
                        {
                            List <Role> roleList = new List <Role>();

                            var availableRoles = await _bosAuthClient.GetRolesAsync <Role>();

                            if (availableRoles != null && availableRoles.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                            {
                                return(RedirectToAction("SignOut", "Auth"));
                            }
                            if (availableRoles.IsSuccessStatusCode)
                            {
                                Role defaultRole = availableRoles.Roles.FirstOrDefault(i => i.Name == "User"); //Setting the registered user's role to the BOS default "User" role
                                roleList.Add(defaultRole);
                                var roleResponse = await _bosAuthClient.AssociateUserToMultipleRolesAsync(result.User.Id, roleList);

                                if (roleResponse != null && roleResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                {
                                    return(RedirectToAction("SignOut", "Auth"));
                                }
                                if (roleResponse.IsSuccessStatusCode)
                                {
                                    var slugResponse = await _bosAuthClient.CreateSlugAsync(registerObj.EmailAddress); //Creating a Slug that will be used in the verification process

                                    if (slugResponse != null && slugResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                    {
                                        return(RedirectToAction("SignOut", "Auth"));
                                    }
                                    if (slugResponse.IsSuccessStatusCode)
                                    {
                                        var slug = slugResponse.Slug;

                                        //Preparing the Email object to send the registered user an email with verification link using BOS Email API
                                        Models.BOSModels.Email emailObj = new Models.BOSModels.Email
                                        {
                                            Deleted = false,
                                            From    = new From
                                            {
                                                Email = "*****@*****.**",
                                                Name  = "StarterCode Team",
                                            },
                                            To = new List <To>
                                            {
                                                new To
                                                {
                                                    Email = registerObj.EmailAddress,
                                                    Name  = registerObj.FirstName + " " + registerObj.LastName
                                                }
                                            }
                                        };

                                        var templateResponse = await _bosEmailClient.GetTemplateAsync <Template>();

                                        if (templateResponse != null && templateResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                        {
                                            return(RedirectToAction("SignOut", "Auth"));
                                        }
                                        if (templateResponse.IsSuccessStatusCode)
                                        {
                                            emailObj.TemplateId = templateResponse.Templates.Where(i => i.Name == "UserRegistration").Select(i => i.Id).ToList()[0];
                                        }
                                        else
                                        {
                                            ModelState.AddModelError("CustomError", "Sorry! We could not send you an email. Please try again later");
                                            return(View("Index"));
                                        }

                                        var spResponse = await _bosEmailClient.GetServiceProviderAsync <ServiceProvider>(true);

                                        if (spResponse != null && spResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                        {
                                            return(RedirectToAction("SignOut", "Auth"));
                                        }
                                        if (spResponse.IsSuccessStatusCode)
                                        {
                                            emailObj.ServiceProviderId = spResponse.ServiceProvider[0].Id;
                                        }
                                        else
                                        {
                                            ModelState.AddModelError("CustomError", "Sorry! We could not send you an email. Please try again later");
                                            return(View("Index"));
                                        }
                                        string hostUrl          = _contextAccessor.HttpContext.Request.Host.ToString();
                                        string baseUrl          = string.Format("{0}://{1}", hostUrl.Contains("localhost") ? "http" : "https", hostUrl);
                                        string logoUrl          = baseUrl + "/images/logo.png";
                                        string appName          = _configuration["ApplicationName"];
                                        var    appConfigSession = _contextAccessor.HttpContext.Session.GetString("ApplicationConfig");
                                        if (appConfigSession != null)
                                        {
                                            var appconfig = JsonConvert.DeserializeObject <WhiteLabel>(appConfigSession);
                                            if (appconfig != null)
                                            {
                                                baseUrl = appconfig.URL;
                                                logoUrl = appconfig.Logo;
                                                appName = appconfig.Name;
                                            }
                                        }
                                        emailObj.Substitutions = new List <Substitution>();
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "companyUrl", Value = baseUrl
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "companyLogo", Value = logoUrl
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "usersName", Value = registerObj.FirstName + " " + registerObj.LastName
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "applicationName", Value = appName
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "activationUrl", Value = baseUrl + "/Password/Reset?slug=" + slug.Value + "&set=true"
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "thanksCredits", Value = "Team StarterCode"
                                        });

                                        var emailResponse = await _bosEmailClient.SendEmailAsync <IEmail>(emailObj);

                                        if (emailResponse != null && emailResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                        {
                                            return(RedirectToAction("SignOut", "Auth"));
                                        }
                                        if (!emailResponse.IsSuccessStatusCode)
                                        {
                                            ModelState.AddModelError("CustomError", emailResponse.BOSErrors[0].Message);
                                        }

                                        ViewBag.Message = "Welcome! You've been successfully registered with us. Check you inbox for an activation link.";
                                        return(View("Index")); //On sucess, redirecting the user back to the Login Page
                                    }
                                }
                            }
                        }
                        //Else, return an error message and stay on the same View
                        ModelState.AddModelError("CustomError", result.BOSErrors[0].Message);
                        return(View("Register"));
                    }
                    else
                    {
                        ModelState.AddModelError("CustomError", result.BOSErrors[0].Message);
                        return(View("Register"));
                    }
                }
                else
                {
                    ModelState.AddModelError("CustomError", "Something went wrong. We are currently unable to register you. Please try again later.");
                    return(View("Register"));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Auth", "RegisterUser", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
        }