Example #1
0
        /// <summary>
        /// Author: BOS Framework, Inc
        /// Description: Triggers when the Register button is clicked
        /// </summary>
        /// <param name="forgotPasswordObj"></param>
        /// <returns></returns>
        public async Task <ActionResult> ForgotPasswordAction(ForgotPassword forgotPasswordObj)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    string emailAddress = forgotPasswordObj.EmailAddress.Trim();                         //Trimming the email input

                    var userResponse = await _bosAuthClient.GetUserByEmailAsync <BOSUser>(emailAddress); //Mkaing a call to the BOS API to validate the entered email address

                    if (userResponse != null && userResponse.Users != null && userResponse.Users.Count > 0)
                    {
                        var slugResponse = await _bosAuthClient.CreateSlugAsync(emailAddress); //On success, creating a slug object that will be used while resetting the password

                        if (slugResponse != null && slugResponse.IsSuccessStatusCode)
                        {
                            var slug = slugResponse.Slug;

                            //Creating the email object to send the email
                            Models.BOSModels.Email emailObj = new Models.BOSModels.Email
                            {
                                Deleted = false,
                                From    = new From
                                {
                                    Email = "*****@*****.**",
                                    Name  = "StarterCode Team",
                                },
                                To = new List <To>
                                {
                                    new To
                                    {
                                        Email = emailAddress,
                                        Name  = ""
                                    }
                                }
                            };
                            var templateResponse = await _bosEmailClient.GetTemplateAsync <Template>();

                            if (templateResponse != null && templateResponse.IsSuccessStatusCode)
                            {
                                emailObj.TemplateId = templateResponse.Templates.Where(i => i.Name == "ForgotPassword").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>();

                            if (spResponse != null && 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"));
                            }

                            emailObj.Substitutions = new List <Substitution>();
                            emailObj.Substitutions.Add(new Substitution {
                                Key = "companyUrl", Value = _configuration["PublicUrl"]
                            });
                            emailObj.Substitutions.Add(new Substitution {
                                Key = "companyLogo", Value = _configuration["PublicUrl"] + "/images/logo.png"
                            });
                            emailObj.Substitutions.Add(new Substitution {
                                Key = "usersName", Value = ""
                            });
                            emailObj.Substitutions.Add(new Substitution {
                                Key = "applicationName", Value = _configuration["ApplicationName"]
                            });
                            emailObj.Substitutions.Add(new Substitution {
                                Key = "resetUrl", Value = _configuration["PublicUrl"] + "/Password/Reset?slug=" + slug.Value + "&set=false"
                            });
                            emailObj.Substitutions.Add(new Substitution {
                                Key = "thanksCredits", Value = "Team StarterCode"
                            });

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

                            if (!emailResponse.IsSuccessStatusCode)
                            {
                                ModelState.AddModelError("CustomError", emailResponse.BOSErrors[0].Message);
                                return(View("Index"));
                            }
                        }
                    }
                }
                //Even if the email adrress entered is not a valid one, we show the same sucess message. This is a form of securing the user's information
                ViewBag.Message = "Check your inbox for an email with a link to reset your password.";
                return(View("Index"));
            }
            catch (Exception ex)
            {
                Logger.LogException("Auth", "ForgotPasswordAction", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
        }
Example #2
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
            {
                //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.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.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.IsSuccessStatusCode)
                                {
                                    var slugResponse = await _bosAuthClient.CreateSlugAsync(registerObj.EmailAddress); //Creating a Slug that will be used in the verification process

                                    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.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>();

                                        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"));
                                        }

                                        emailObj.Substitutions = new List <Substitution>();
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "companyUrl", Value = _configuration["PublicUrl"]
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "companyLogo", Value = _configuration["PublicUrl"] + "/images/logo.png"
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "usersName", Value = registerObj.FirstName + " " + registerObj.LastName
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "applicationName", Value = _configuration["ApplicationName"]
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "activationUrl", Value = _configuration["PublicUrl"] + "/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.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));
            }
        }
Example #3
0
        public async Task <string> AddUser([FromBody] JObject data)
        {
            try
            {
                if (data != null)
                {
                    User        userObj       = data["User"]?.ToObject <User>();
                    List <Role> roleList      = data["Roles"]?.ToObject <List <Role> >();
                    bool        isEmailToSend = Convert.ToBoolean(data["IsEmailToSend"]?.ToString());
                    string      password      = data["Password"]?.ToString();
                    if (isEmailToSend)
                    {
                        password = CreatePassword();
                    }

                    if (userObj != null)
                    {
                        var result = await _bosAuthClient.AddNewUserAsync <BOSUser>(userObj.Username, userObj.Email, password);

                        if (result != null && result.IsSuccessStatusCode)
                        {
                            User user = userObj;
                            user.Id = result.User.Id;

                            var extendUserResponse = await _bosAuthClient.ExtendUserAsync(user);

                            if (extendUserResponse != null && extendUserResponse.IsSuccessStatusCode)
                            {
                                var roleResponse = await _bosAuthClient.AssociateUserToMultipleRolesAsync(result.User.Id, roleList);

                                if (roleResponse != null && roleResponse.IsSuccessStatusCode)
                                {
                                    if (isEmailToSend)
                                    {
                                        var slugResponse = await _bosAuthClient.CreateSlugAsync(userObj.Email);

                                        if (slugResponse != null && slugResponse.IsSuccessStatusCode)
                                        {
                                            var slug = slugResponse.Slug;

                                            Models.BOSModels.Email emailObj = new Models.BOSModels.Email
                                            {
                                                Deleted = false,
                                                From    = new From
                                                {
                                                    Email = "*****@*****.**",
                                                    Name  = "StarterCode Team",
                                                },
                                                To = new List <To>
                                                {
                                                    new To
                                                    {
                                                        Email = userObj.Email,
                                                        Name  = userObj.FirstName + " " + userObj.LastName
                                                    }
                                                }
                                            };
                                            var templateResponse = await _bosEmailClient.GetTemplateAsync <Template>();

                                            if (templateResponse != null && templateResponse.IsSuccessStatusCode)
                                            {
                                                emailObj.TemplateId = templateResponse.Templates.Where(i => i.Name == "UserAddedBySuperAdmin").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", await GetPageData()));
                                            }

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

                                            if (spResponse != null && 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", await GetPageData()));
                                            }

                                            emailObj.Substitutions = new List <Substitution>();
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "companyUrl", Value = _configuration["PublicUrl"]
                                            });
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "companyLogo", Value = _configuration["PublicUrl"] + "/wwwroot/images/logo.png"
                                            });
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "applicationName", Value = _configuration["ApplicationName"]
                                            });
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "applicationUrl", Value = _configuration["PublicUrl"] + "/Password/Reset?slug=" + slug.Value
                                            });
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "emailAddress", Value = user.Email
                                            });
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "password", Value = ""
                                            });
                                            emailObj.Substitutions.Add(new Substitution {
                                                Key = "thanksCredits", Value = "Team StarterCode"
                                            });

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

                                            if (!emailResponse.IsSuccessStatusCode)
                                            {
                                                ModelState.AddModelError("CustomError", emailResponse.BOSErrors[0].Message);
                                            }
                                        }
                                    }
                                    return("User added successfully");
                                }
                            }
                            return(result != null ? result.BOSErrors[0].Message : "We are unable to add users at this time. Please try again.");
                        }
                        else
                        {
                            return(result != null ? result.BOSErrors[0].Message : "We are unable to add users at this time. Please try again.");
                        }
                    }
                    else
                    {
                        return("User data cannot be null. Please check and try again.");
                    }
                }
                else
                {
                    return("The data inputted is inaccurate. Please try again.");
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Users", "AddUser", ex);

                dynamic model = new ExpandoObject();
                model.Message    = ex.Message;
                model.StackTrace = ex.StackTrace;
                return(View("ErrorPage", model));
            }
        }
Example #4
0
        public async Task <string> AddUser([FromBody] JObject data)
        {
            try
            {
                if (data != null) //Confirm non-null input data
                {
                    /*--------LOGIC----------
                     * Validate the data sent across the wire
                     * Convert it to the "User" object
                     * Create a new User record in BOS
                     * Update the user's info by making another BOS API call by ID (received as a respoonse from the previous API call)
                     * Associate roles to the user
                     * Send email with the verification link (if selected in the View)
                     *      • Generate a slug
                     *      • Get the TemplateId via BOS Email API
                     *      • Get the ServiceProviderId via BOS Email API
                     *      • Create the email object
                     *      • Make the BOS API call to send the Email
                     * Return a success message
                     */
                    User        userObj       = data["User"]?.ToObject <User>();                      //Convert the input data into a user object
                    List <Role> roleList      = data["Roles"]?.ToObject <List <Role> >();             //Get the list of roles the user is assigned to
                    bool        isEmailToSend = Convert.ToBoolean(data["IsEmailToSend"]?.ToString()); //Check if the Verification email has to be sent
                    string      password      = data["Password"]?.ToString();

                    if (isEmailToSend) //If Email is to be sent, then the password is the be auto-created, else, the password is to be set by the user who is creating the record
                    {
                        password = CreatePassword();
                    }
                    else
                    {
                        if (userObj != null) //Checking for a non-null userObj
                        {
                            userObj.EmailConfirmed = true;
                        }
                    }

                    //Have different level of if conditions so that the returned message is more accurate, given the fail of condition
                    if (userObj != null)                                                                                                //Checking for a non-null userObj
                    {
                        if (userObj.Username != null && userObj.Email != null && password != null)                                      //Non-null values
                        {
                            if (roleList != null && roleList.Count > 0)                                                                 //Non-null role List and with at least one record
                            {
                                var result = await _bosAuthClient.AddNewUserAsync <BOSUser>(userObj.Username, userObj.Email, password); //Making a BOS API call to add a new user record

                                if (result != null && result.IsSuccessStatusCode)
                                {
                                    User user = userObj;
                                    user.Id = result.User.Id;                                            //On successful, the response's userId is taken into account

                                    var extendUserResponse = await _bosAuthClient.ExtendUserAsync(user); //Updating the user's inforamation through a BOS API call

                                    if (extendUserResponse != null && extendUserResponse.IsSuccessStatusCode)
                                    {
                                        //On successful updation of information of the user, we then update the roles
                                        var roleResponse = await _bosAuthClient.AssociateUserToMultipleRolesAsync(result.User.Id, roleList); //Making a BOS API call to associate the user with role(s)

                                        if (roleResponse != null && roleResponse.IsSuccessStatusCode)
                                        {
                                            //On success of the API call, we finally send the user an email with the verification link, if it is set to true
                                            if (isEmailToSend)
                                            {
                                                var slugResponse = await _bosAuthClient.CreateSlugAsync(userObj.Email); //Making a BOS API call to generate a slug

                                                if (slugResponse != null && slugResponse.IsSuccessStatusCode)
                                                {
                                                    var slug = slugResponse.Slug;

                                                    //Preparing the email object that's used as an input to the 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 = userObj.Email,
                                                                Name  = userObj.FirstName + " " + userObj.LastName
                                                            }
                                                        }
                                                    };
                                                    var templateResponse = await _bosEmailClient.GetTemplateAsync <Template>(); //Making the BOS API call to get the list of all the templates

                                                    if (templateResponse != null && templateResponse.IsSuccessStatusCode)
                                                    {
                                                        //Selecting the templateID where the templatename is UserAddedBySuperAdmin
                                                        emailObj.TemplateId = templateResponse.Templates.Where(i => i.Name == "UserAddedBySuperAdmin").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", await GetPageData()));
                                                    }

                                                    var spResponse = await _bosEmailClient.GetServiceProviderAsync <ServiceProvider>(); //Making a BOS API call to get the ServiceProviderId

                                                    if (spResponse != null && 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", await GetPageData()));
                                                    }

                                                    //This is the list of key-value pair where the content will be replace with the 'Value' where the 'Key' matches in the content of the template
                                                    emailObj.Substitutions = new List <Substitution>();
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "usersName", Value = user.FirstName + " " + user.LastName
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "companyUrl", Value = _configuration["PublicUrl"]
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "companyLogo", Value = _configuration["PublicUrl"] + "/images/logo.png"
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "applicationName", Value = _configuration["ApplicationName"]
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "applicationUrl", Value = _configuration["PublicUrl"] + "/Password/Reset?slug=" + slug.Value + "&set=true"
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "emailAddress", Value = user.Email
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "password", Value = ""
                                                    });
                                                    emailObj.Substitutions.Add(new Substitution {
                                                        Key = "thanksCredits", Value = "Team StarterCode"
                                                    });

                                                    var emailResponse = await _bosEmailClient.SendEmailAsync <IEmail>(emailObj); //Making an API call to send Email

                                                    if (!emailResponse.IsSuccessStatusCode)
                                                    {
                                                        ModelState.AddModelError("CustomError", emailResponse.BOSErrors[0].Message);
                                                    }
                                                }
                                            }
                                            return("User added successfully"); //On success of all the APIs, we return an appropriate message
                                        }
                                    }
                                    return(result != null ? result.BOSErrors[0].Message : "We are unable to add users at this time. Please try again.");
                                }

                                else
                                {
                                    return(result != null ? result.BOSErrors[0].Message : "We are unable to add users at this time. Please try again.");
                                }
                            }
                            else
                            {
                                return("User has to be associated with at least one role");
                            }
                        }
                        else
                        {
                            return("Required data is missing. Please try again");
                        }
                    }
                    else
                    {
                        return("User data cannot be null. Please check and try again.");
                    }
                }
                else
                {
                    return("Data cannot be null. Please try again.");
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Users", "AddUser", ex);
                return(ex.Message);
            }
        }
        /// <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
            {
                registerObj.EmailAddress = registerObj.EmailAddress.Trim();
                registerObj.FirstName    = registerObj.FirstName.Trim();
                registerObj.LastName     = registerObj.LastName.Trim();

                var result = await _bosAuthClient.AddNewUserAsync <BOSUser>(registerObj.EmailAddress, registerObj.EmailAddress, CreatePassword());

                if (result != null)
                {
                    if (result.IsSuccessStatusCode)
                    {
                        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
                        };

                        var extendUserResponse = await _bosAuthClient.ExtendUserAsync(user);

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

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

                            if (availableRoles.IsSuccessStatusCode)
                            {
                                Role defaultRole = availableRoles.Roles.FirstOrDefault(i => i.Name == "User");
                                roleList.Add(defaultRole);
                                var roleResponse = await _bosAuthClient.AssociateUserToMultipleRolesAsync(result.User.Id, roleList);

                                if (roleResponse.IsSuccessStatusCode)
                                {
                                    var slugResponse = await _bosAuthClient.CreateSlugAsync(registerObj.EmailAddress);

                                    if (slugResponse.IsSuccessStatusCode)
                                    {
                                        var slug = slugResponse.Slug;

                                        ViewBag.Message = "Welcome! You've been successfully registered with us. Check you inbox for an activation link.";

                                        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.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>();

                                        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"));
                                        }

                                        emailObj.Substitutions = new List <Substitution>();
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "companyUrl", Value = _configuration["PublicUrl"]
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "companyLogo", Value = _configuration["PublicUrl"] + "/wwwroot/images/logo.png"
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "usersName", Value = registerObj.FirstName + " " + registerObj.LastName
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "applicationName", Value = _configuration["ApplicationName"]
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "activationUrl", Value = _configuration["PublicUrl"] + "/Password/Reset?slug=" + slug.Value
                                        });
                                        emailObj.Substitutions.Add(new Substitution {
                                            Key = "thanksCredits", Value = "Team StarterCode"
                                        });

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

                                        if (!emailResponse.IsSuccessStatusCode)
                                        {
                                            ModelState.AddModelError("CustomError", emailResponse.BOSErrors[0].Message);
                                        }
                                        return(View("Index"));
                                    }
                                }
                            }
                        }
                        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));
            }
        }
Example #6
0
        /// <summary>
        /// Author: BOS Framework, Inc
        /// Description: Triggers when the Register button is clicked
        /// </summary>
        /// <param name="forgotPasswordObj"></param>
        /// <returns></returns>
        public async Task <ActionResult> ForgotPasswordAction(ForgotPassword forgotPasswordObj)
        {
            try
            {
                if (HttpContext != null && !HttpContext.Request.Cookies.ContainsKey(".AspNet.Consent"))
                {
                    if (_bosAuthClient == null)
                    {
                        var response = await _multitenantService.GetGeneratedToken();
                    }
                    ModelState.AddModelError("CustomError", "Before proceeding, please 'Accept' our Cookies' terms.");
                    return(View("ForgotPassword"));
                }

                if (ModelState.IsValid)
                {
                    string emailAddress = forgotPasswordObj.EmailAddress.Trim(); //Trimming the email input
                    if (forgotPasswordObj != null)
                    {
                        if (_bosAuthClient == null)
                        {
                            var response = await _multitenantService.GetGeneratedToken();

                            return(RedirectToAction("ForgotPassword"));
                        }
                        var userResponse = await _bosAuthClient.GetUserByEmailAsync <BOSUser>(emailAddress); //Mkaing a call to the BOS API to validate the entered email address

                        if (userResponse != null && userResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            return(RedirectToAction("SignOut", "Auth"));
                        }
                        if (userResponse != null && userResponse.Users != null && userResponse.Users.Count > 0)
                        {
                            var slugResponse = await _bosAuthClient.CreateSlugAsync(emailAddress); //On success, creating a slug object that will be used while resetting the password

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

                                //Creating the email object to send the email
                                Models.BOSModels.Email emailObj = new Models.BOSModels.Email
                                {
                                    Deleted = false,
                                    From    = new From
                                    {
                                        Email = "*****@*****.**",
                                        Name  = "StarterCode Team",
                                    },
                                    To = new List <To>
                                    {
                                        new To
                                        {
                                            Email = emailAddress,
                                            Name  = ""
                                        }
                                    }
                                };
                                var templateResponse = await _bosEmailClient.GetTemplateAsync <Template>();

                                if (templateResponse != null && templateResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                {
                                    return(RedirectToAction("SignOut", "Auth"));
                                }
                                if (templateResponse != null && templateResponse.IsSuccessStatusCode)
                                {
                                    emailObj.TemplateId = templateResponse.Templates.Where(i => i.Name == "ForgotPassword").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 != null && 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;
                                    }
                                }

                                var userDetails = userResponse.Users.FirstOrDefault();
                                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 = userDetails != null ? userDetails.Username.Split("@")[0] : ""
                                });
                                emailObj.Substitutions.Add(new Substitution {
                                    Key = "applicationName", Value = appName
                                });
                                emailObj.Substitutions.Add(new Substitution {
                                    Key = "resetUrl", Value = baseUrl + "/Password/Reset?slug=" + slug.Value + "&set=false"
                                });
                                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);
                                    return(View("Index"));
                                }
                            }
                        }
                    }
                    else
                    {
                    }
                }
                //Even if the email adrress entered is not a valid one, we show the same sucess message. This is a form of securing the user's information
                ViewBag.Message = "Check your inbox for an email with a link to reset your password.";
                return(View("Index"));
            }
            catch (Exception ex)
            {
                Logger.LogException("Auth", "ForgotPasswordAction", ex);

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