public async Task <ActionResult> SocialMediaHandle(OstSocialModel model)
        {
            if (string.IsNullOrEmpty(model.Email))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Email cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Name cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Id))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Id cannot be set to null or empty." }));
            }

            if (!string.IsNullOrEmpty(model.IdToken))
            {
                // TODO: Verify the integrity of the ID token
                // Phase 2
                if (model.Brand.Equals("facebook"))
                {
                }
                if (model.Brand.Equals("google"))
                {
                }
            }

            var username = Membership.GetUserNameByEmail(model.Email);

            if (null == username)
            {
                //register
                string strippedName = new string(model.Name.ToCharArray()
                                                 .Where(c => !char.IsWhiteSpace(c))
                                                 .ToArray()).ToLower();
                Random rnd         = new Random();
                int    rndTail     = rnd.Next(1000, 10000);
                var    newUserName = strippedName + rndTail.ToString();
                string password    = Membership.GeneratePassword(8, 1);

                var registerModel = new OstRegisterModel
                {
                    UserName        = newUserName,
                    FullName        = model.Name,
                    Email           = model.Email,
                    Password        = password,
                    ConfirmPassword = password,
                    Designation     = "No contract customer"
                };
                var result = await CreateAccount(registerModel);

                if (!result.Success)
                {
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return(Json(new { success = result.Success, status = "ERROR", message = result.Status }));
                }

                var emailModel = new OstCreateEmailModel
                {
                    UserEmail    = registerModel.Email,
                    UserName     = registerModel.UserName,
                    EmailSubject = "Verify your email address",
                    EmailBody    = $"To finish setting up this {ConfigurationManager.ApplicationFullName} account, we just need to make sure this email address is yours."
                };
                await SendVerificationEmail(emailModel);

                //create user details
                var context    = new SphDataContext();
                var userDetail = new Bespoke.Ost.UserDetails.Domain.UserDetail();
                var guid       = Guid.NewGuid().ToString();
                userDetail.Id     = guid;
                userDetail.UserId = registerModel.UserName;
                userDetail.Profile.ContactPerson            = registerModel.FullName;
                userDetail.ProfilePictureUrl                = model.PictureUrl;
                userDetail.Profile.ContactInformation.Email = registerModel.Email;
                userDetail.Profile.Address.Country          = "MY";
                using (var session = context.OpenSession())
                {
                    session.Attach(userDetail);
                    await session.SubmitChanges("Default");
                }

                Response.StatusCode = (int)HttpStatusCode.OK;
                return(Json(new { success = true, status = "OK", message = $"User {registerModel.UserName} with email {registerModel.Email} has been registered." }));
            }
            else
            {
                //login
                var logger   = ObjectBuilder.GetObject <ILogger>();
                var identity = new ClaimsIdentity(ConfigurationManager.ApplicationName + "Cookie");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username));
                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                var roles = Roles.GetRolesForUser(username).Select(x => new Claim(ClaimTypes.Role, x));
                identity.AddClaims(roles);


                var context = new SphDataContext();
                var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == username);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                if (null != profile)
                {
                    // user email address verification pending
                    if (!profile.HasChangedDefaultPassword)
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return(Json(new { success = false, status = "ERROR", message = "Email verification pending. Please check your inbox for a verification email. You will be allowed to sign in after verification is complete." }));
                    }

                    var claims = profile.GetClaims();
                    identity.AddClaims(claims);

                    var designation = context.LoadOneFromSources <Designation>(x => x.Name == profile.Designation);
                    if (null != designation && designation.EnforceStartModule)
                    {
                        profile.StartModule = designation.StartModule;
                    }

                    HttpContext.GetOwinContext().Authentication.SignIn(identity);

                    Response.StatusCode = (int)HttpStatusCode.OK;
                    return(Json(new { success = true, status = "OK", message = $"User {profile.UserName} with email {profile.Email} has been authenticated." }));
                }
                HttpContext.GetOwinContext().Authentication.SignIn(identity);

                Response.StatusCode = (int)HttpStatusCode.OK;
                return(Json(new { success = true, status = "OK", message = $"User {profile.UserName} with email {profile.Email} has been authenticated." }));
            }
        }
        public async Task <ActionResult> Login(OstLoginModel model, string returnUrl = "/")
        {
            if (string.IsNullOrEmpty(model.UserName))
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "Username cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Password))
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "Password cannot be set to null or empty." }));
            }

            var logger = ObjectBuilder.GetObject <ILogger>();

            var directory = ObjectBuilder.GetObject <IDirectoryService>();

            if (await directory.AuthenticateAsync(model.UserName, model.Password))
            {
                var identity = new ClaimsIdentity(ConfigurationManager.ApplicationName + "Cookie");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Name, model.UserName));
                var roles = Roles.GetRolesForUser(model.UserName).Select(x => new Claim(ClaimTypes.Role, x));
                identity.AddClaims(roles);


                var context = new SphDataContext();
                var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == model.UserName);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                if (null != profile)
                {
                    // user email address verification pending
                    if (!profile.HasChangedDefaultPassword)
                    {
                        return(RedirectToAction("login", "ost-account", new { success = false, status = "Email verification pending. Please check your inbox for a verification email. You will be allowed to sign in after verification is complete." }));
                    }

                    var claims = profile.GetClaims();
                    identity.AddClaims(claims);

                    var designation = context.LoadOneFromSources <Designation>(x => x.Name == profile.Designation);
                    if (null != designation && designation.EnforceStartModule)
                    {
                        profile.StartModule = designation.StartModule;
                    }

                    HttpContext.GetOwinContext().Authentication.SignIn(identity);

                    if (!string.IsNullOrEmpty(profile.Designation))
                    {
                        if (profile.Designation.Equals("No contract customer") ||
                            profile.Designation.Equals("Contract customer"))
                        {
                            if (returnUrl == "/" ||
                                returnUrl.Equals("/ost", StringComparison.InvariantCultureIgnoreCase) ||
                                returnUrl.Equals("/ost#", StringComparison.InvariantCultureIgnoreCase) ||
                                returnUrl.Equals("/ost/", StringComparison.InvariantCultureIgnoreCase) ||
                                returnUrl.Equals("/ost/#", StringComparison.InvariantCultureIgnoreCase) ||
                                string.IsNullOrWhiteSpace(returnUrl))
                            {
                                return(Redirect("/ost#" + profile.StartModule));
                            }
                        }
                    }
                    return(Redirect("/sph"));
                }
                HttpContext.GetOwinContext().Authentication.SignIn(identity);
                if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                return(RedirectToAction("Default", "OstHome"));
            }
            var user = await directory.GetUserAsync(model.UserName);

            await logger.LogAsync(new LogEntry { Log = EventLog.Security, Message = "Login Failed" });

            if (null != user && user.IsLockedOut)
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "Your acount has beeen locked, Please contact your administrator." }));
            }
            else
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "The user name or password provided is incorrect." }));
            }
        }