public IActionResult Update(MemberAddViewModel model)
        {
            var member = model.MemberInfo;

            _memberService.Update(member);
            return(RedirectToAction("List"));
        }
        public virtual ActionResult Register()
        {
            if (SettingsService.GetSettings().SuspendRegistration != true)
            {
                var user = MembershipService.CreateEmptyUser();

                // Populate empty viewmodel
                var viewModel = new MemberAddViewModel
                {
                    Email      = user.Email,
                    FirstName  = user.FirstName,
                    Surname    = user.Surname,
                    Password   = user.Password,
                    IsApproved = user.IsApproved,
                    AllRoles   = RoleService.AllRoles()
                };

                // See if a return url is present or not and add it
                var returnUrl = Request["ReturnUrl"];
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    viewModel.ReturnUrl = returnUrl;
                }

                return(View(viewModel));
            }
            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult Register()
        {
            if (SettingsService.GetSettings().RegistrationEnabled == true)
            {
                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    var user      = MembershipService.CreateEmptyUser();
                    var viewModel = new MemberAddViewModel
                    {
                        Email     = user.Email,
                        Password  = user.Password,
                        AllRoles  = RoleService.AllRoles(),
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        City      = user.City,
                        State     = user.State
                    };
                    StatesViewModel statesViewModel = new StatesViewModel()
                    {
                        allStates = SettingsService.ListOfStates().ToList()
                    };
                    viewModel._stateViewModel = statesViewModel;

                    // See if a return url is present or not and add it
                    var returnUrl = Request["ReturnUrl"];
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        viewModel.ReturnUrl = returnUrl;
                    }
                    return(View(viewModel));
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
 public ActionResult Register(MemberAddViewModel viewModel)
 {
     if (SettingsService.GetSettings().RegistrationEnabled == true)
     {
         // Do the register logic
         return(MemberRegisterLogic(viewModel));
     }
     return(RedirectToAction("Index", "Home"));
 }
        public IActionResult Add()
        {
            var model = new MemberAddViewModel()
            {
                MemberInfo = new Member()
            };

            return(View(model));
        }
        public IActionResult Update(string memberId)
        {
            var member = _memberService.GetById(memberId);
            var model  = new MemberAddViewModel()
            {
                MemberInfo = member
            };

            return(View(model));
        }
Example #7
0
        public void Add_User_Success()
        {
            _membershipServiceSub
                .CreateUser(Arg.Any<MembershipUser>())
                .Returns(x => MembershipCreateStatus.Success);

            var viewModel = new MemberAddViewModel
            {
                Comment = "Test"
            };
            var controller = new AccountController(_membershipServiceSub);
            controller.Add(viewModel);

            Assert.IsTrue(controller.ModelState.IsValid);
        }
        public virtual async Task <ActionResult> RegisterAsync(MemberAddViewModel userModel, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (ModelState.IsValid)
            {
                var mailAddress = new MailAddress(userModel.Email);
                if (!await _groupInviteService.InviteExistsForMailAddressAsync(mailAddress, cancellationToken))
                {
                    ModelState.AddModelError(nameof(userModel.Email), "This user has not been invited onto the platform. Please check the email address provided.");
                    return(View(userModel));
                }

                var settings = SettingsService.GetSettings();
                if (settings.SuspendRegistration != true &&
                    settings.DisableStandardRegistration != true)
                {
                    // First see if there is a spam question and if so, the answer matches
                    if (!string.IsNullOrWhiteSpace(settings.SpamQuestion))
                    {
                        // There is a spam question, if answer is wrong return with error
                        if (userModel.SpamAnswer == null ||
                            userModel.SpamAnswer.Trim() != settings.SpamAnswer)
                        {
                            // POTENTIAL SPAMMER!
                            ModelState.AddModelError(string.Empty,
                                                     "There was an error with your answer. Please try again");
                            return(View());
                        }
                    }

                    // Get the user model
                    var user = userModel.ToMembershipUser();

                    var pipeline = await MembershipService.CreateUserAsync(user, LoginType.Standard, cancellationToken);

                    if (!pipeline.Successful)
                    {
                        ModelState.AddModelError(nameof(userModel.Email), pipeline.ProcessLog.FirstOrDefault());
                        return(View());
                    }

                    // Do the register logic
                    return(MemberRegisterLogic(pipeline));
                }
                return(RedirectToAction("Index", "Home"));
            }

            return(View());
        }
        public void Add_User_Fail()
        {
            _membershipServiceSub
            .CreateUser(Arg.Any <MembershipUser>())
            .Returns(x => MembershipCreateStatus.ProviderError);

            var viewModel = new MemberAddViewModel
            {
                Comment = "Test"
            };
            var controller = new AccountController(_membershipServiceSub);

            controller.Add(viewModel);

            Assert.IsFalse(controller.ModelState.IsValid);
        }
Example #10
0
        public ActionResult Register()
        {
            if (SettingsService.GetSetting("SuspendRegistration") != "true")
            {
                // Populate empty viewmodel
                var viewModel = new MemberAddViewModel();

                // See if a return url is present or not and add it
                var returnUrl = Request["ReturnUrl"];
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    viewModel.ReturnUrl = returnUrl;
                }

                return(View(viewModel));
            }
            return(RedirectToAction("Index", "Home"));
        }
Example #11
0
        /// <summary>
        /// Converts a add view model to a membershipuser
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public static MembershipUser ToMembershipUser(this MemberAddViewModel viewModel)
        {
            var surnameInitial = string.IsNullOrEmpty(viewModel.Surname) ? string.Empty : viewModel.Surname[0].ToString();

            var userToSave = new MembershipUser
            {
                UserName   = viewModel.Email,
                FirstName  = viewModel.FirstName,
                Surname    = viewModel.Surname,
                Initials   = string.Format("{0}{1}", viewModel.FirstName[0], surnameInitial).ToUpper(),
                Email      = viewModel.Email,
                Password   = viewModel.Password,
                IsApproved = viewModel.IsApproved
            };


            return(userToSave);
        }
        public HttpResponseMessage Post(MemberAddViewModel userModel)
        {
            if (SettingsService.GetSettings().SuspendRegistration != true)
            {
                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    //Custom Code: Check for presence of universal id
                    if (string.IsNullOrWhiteSpace(userModel.UniversalId))
                    {
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.UniversalIdRegistration"));
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                    }
                    // First see if there is a spam question and if so, the answer matches
                    if (!string.IsNullOrEmpty(SettingsService.GetSettings().SpamQuestion))
                    {
                        // There is a spam question, if answer is wrong return with error
                        if (userModel.SpamAnswer == null || userModel.SpamAnswer.Trim() != SettingsService.GetSettings().SpamAnswer)
                        {
                            // POTENTIAL SPAMMER!
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.WrongAnswerRegistration"));
                            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                        }
                    }

                    // Secondly see if the email is banned
                    if (_bannedEmailService.EmailIsBanned(userModel.Email))
                    {
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.EmailIsBanned"));
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                    }
                }

                // Standard Login
                userModel.LoginType = LoginType.Standard;

                // Do the register logic
                return(MemberRegisterLogic(userModel));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        /// <summary>
        /// Converts a add view model to a membershipuser
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public static MembershipUser ToMembershipUser(this MemberAddViewModel viewModel)
        {
            var userToSave = new MembershipUser
            {
                UserName   = viewModel.UserName,
                Email      = viewModel.Email,
                Password   = viewModel.Password,
                IsApproved = viewModel.IsApproved,
                Comment    = viewModel.Comment
            };

            if (viewModel.LoginType == LoginType.Facebook)
            {
                userToSave.FacebookAccessToken = viewModel.UserAccessToken;
            }
            if (viewModel.LoginType == LoginType.Google)
            {
                userToSave.GoogleAccessToken = viewModel.UserAccessToken;
            }
            if (viewModel.LoginType == LoginType.Microsoft)
            {
                userToSave.MicrosoftAccessToken = viewModel.UserAccessToken;
            }

            // Save the social url
            if (!string.IsNullOrWhiteSpace(viewModel.SocialProfileImageUrl))
            {
                // Save the SocialProfileImageUrl in ExtendedData as we'll need it
                userToSave.SetExtendedDataValue(Constants.ExtendedDataKeys.SocialProfileImageUrl, viewModel.SocialProfileImageUrl);
            }

            // Save the return url on the user to
            if (!string.IsNullOrWhiteSpace(viewModel.ReturnUrl))
            {
                userToSave.SetExtendedDataValue(Constants.ExtendedDataKeys.ReturnUrl, viewModel.ReturnUrl);
            }

            return(userToSave);
        }
Example #14
0
        public ActionResult Add()
        {
            ICollection <SelectListItemCount> organizationItems = _organizationRepository.GetOrganizations(
                UserContext.User.Id,
                UserContext.User.OrganizationId,
                new List <int> {
                Dom.OrganizationType.Club
            }
                );
            var viewModel = new MemberAddViewModel
            {
                GenderItems       = InitGenderSelectListItems(),
                OrganizationItems = Mapper.Map <ICollection <SelectListItem> >(organizationItems)
            };

            if (organizationItems.FirstOrDefault(m => m.Value == UserContext.User.OrganizationId) != null)
            {
                viewModel.OrganizationId = UserContext.User.OrganizationId;
            }

            return(View(Mvc.View.Member.Add, viewModel));
        }
Example #15
0
        public virtual ActionResult FacebookLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback         = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias    = Request.QueryString["propertyAlias"];

            if (AuthState != null)
            {
                var stateValue = Session[$"MvcForum_{AuthState}"] as string[];
                if (stateValue != null && stateValue.Length == 3)
                {
                    Callback         = stateValue[0];
                    ContentTypeAlias = stateValue[1];
                    PropertyAlias    = stateValue[2];
                }
            }

            // Get the prevalue options
            if (string.IsNullOrWhiteSpace(ForumConfiguration.Instance.FacebookAppId) ||
                string.IsNullOrWhiteSpace(ForumConfiguration.Instance.FacebookAppSecret))
            {
                resultMessage.Message     = "You need to add the Facebook app credentials";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {
                // Settings valid move on
                // Configure the OAuth client based on the options of the prevalue options
                var client = new FacebookOAuthClient
                {
                    AppId       = ForumConfiguration.Instance.FacebookAppId,
                    AppSecret   = ForumConfiguration.Instance.FacebookAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session[$"MvcForum_{AuthState}"] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Facebook
                if (AuthError != null)
                {
                    Session.Remove($"MvcForum_{AuthState}");
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Redirect the user to the Facebook login dialog
                if (AuthCode == null)
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session[$"MvcForum_{state}"] = new[] { Callback, ContentTypeAlias, PropertyAlias };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends"

                    // Redirect the user
                    return(Redirect(url));
                }

                // Exchange the authorization code for a user access token
                var userAccessToken = string.Empty;
                try
                {
                    userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                try
                {
                    if (string.IsNullOrWhiteSpace(resultMessage.Message))
                    {
                        // Initialize the Facebook service (no calls are made here)
                        var service = FacebookService.CreateFromAccessToken(userAccessToken);

                        // Declare the options for the call to the API
                        var options = new FacebookGetUserOptions
                        {
                            Identifier = "me",
                            Fields     = new[] { "id", "name", "email", "first_name", "last_name", "gender" }
                        };

                        var user = service.Users.GetUser(options);

                        // Try to get the email - Some FB accounts have protected passwords
                        var email = user.Body.Email;
                        if (string.IsNullOrWhiteSpace(email))
                        {
                            resultMessage.Message =
                                LocalizationService.GetResourceString("Members.UnableToGetEmailAddress");
                            resultMessage.MessageType = GenericMessages.danger;
                            ShowMessage(resultMessage);
                            return(RedirectToAction("LogOn", "Members"));
                        }

                        // First see if this user has registered already - Use email address
                        var userExists = MembershipService.GetUserByEmail(email);

                        if (userExists != null)
                        {
                            try
                            {
                                // Users already exists, so log them in
                                FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                                resultMessage.Message =
                                    LocalizationService.GetResourceString("Members.NowLoggedIn");
                                resultMessage.MessageType = GenericMessages.success;
                                ShowMessage(resultMessage);
                                return(RedirectToAction("Index", "Home"));
                            }
                            catch (Exception ex)
                            {
                                LoggingService.Error(ex);
                            }
                        }
                        else
                        {
                            // Not registered already so register them
                            var viewModel = new MemberAddViewModel
                            {
                                Email           = email,
                                LoginType       = LoginType.Facebook,
                                Password        = StringUtils.RandomString(8),
                                UserAccessToken = userAccessToken
                            };

                            // Get the image and save it
                            var getImageUrl = $"http://graph.facebook.com/{user.Body.Id}/picture?type=square";
                            viewModel.SocialProfileImageUrl = getImageUrl;

                            // Large size photo https://graph.facebook.com/{facebookId}/picture?type=large
                            // Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal
                            // Small size photo https://graph.facebook.com/{facebookId}/picture?type=small
                            // Square photo https://graph.facebook.com/{facebookId}/picture?type=square

                            // Store the viewModel in TempData - Which we'll use in the register logic
                            TempData[Constants.MemberRegisterViewModel] = viewModel;

                            return(RedirectToAction("SocialLoginValidator", "Members"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }
            }

            ShowMessage(resultMessage);
            return(RedirectToAction("LogOn", "Members"));
        }
Example #16
0
        public ActionResult GoogleLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback         = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias    = Request.QueryString["propertyAlias"];
            Feature          = Request.QueryString["feature"];

            if (AuthState != null)
            {
                var stateValue = Session["MVCForum_" + AuthState] as NameValueCollection;
                if (stateValue != null)
                {
                    Callback         = stateValue["Callback"];
                    ContentTypeAlias = stateValue["ContentTypeAlias"];
                    PropertyAlias    = stateValue["PropertyAlias"];
                    Feature          = stateValue["Feature"];
                }
            }

            if (string.IsNullOrEmpty(SiteConstants.GooglePlusAppId) ||
                string.IsNullOrEmpty(SiteConstants.GooglePlusAppSecret))
            {
                resultMessage.Message     = "You need to add the Google app credentials";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {
                // Configure the OAuth client based on the options of the prevalue options
                var client = new GoogleOAuthClient
                {
                    ClientId     = SiteConstants.GooglePlusAppId,
                    ClientSecret = SiteConstants.GooglePlusAppSecret,
                    RedirectUri  = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session["MVCForum_" + AuthState] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Google
                if (AuthError != null)
                {
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                    if (AuthState != null)
                    {
                        Session.Remove("MVCForum_" + AuthState);
                    }
                }

                // Redirect the user to the Google login dialog
                if (AuthCode == null)
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["MVCForum_" + state] = new NameValueCollection {
                        { "Callback", Callback },
                        { "ContentTypeAlias", ContentTypeAlias },
                        { "PropertyAlias", PropertyAlias },
                        { "Feature", Feature }
                    };

                    // Declare the scope
                    var scope = new[] {
                        GoogleScopes.OpenId,
                        GoogleScopes.Email,
                        GoogleScopes.Profile
                    };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force);

                    // Redirect the user
                    return(Redirect(url));
                }

                var info = new GoogleAccessTokenResponse();
                try
                {
                    info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = string.Format("Unable to acquire access token<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.danger;
                }

                try
                {
                    // Initialize the Google service
                    var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken);

                    // Get information about the authenticated user
                    var user = service.GetUserInfo();
                    using (UnitOfWorkManager.NewUnitOfWork())
                    {
                        var userExists = MembershipService.GetUserByEmail(user.Email);

                        if (userExists != null)
                        {
                            // Users already exists, so log them in
                            FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                            resultMessage.Message     = LocalizationService.GetResourceString("Members.NowLoggedIn");
                            resultMessage.MessageType = GenericMessages.success;
                            ShowMessage(resultMessage);
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            // Not registered already so register them
                            var viewModel = new MemberAddViewModel
                            {
                                Email                 = user.Email,
                                LoginType             = LoginType.Google,
                                Password              = StringUtils.RandomString(8),
                                UserName              = user.Name,
                                SocialProfileImageUrl = user.Picture,
                                UserAccessToken       = info.RefreshToken
                            };

                            // Store the viewModel in TempData - Which we'll use in the register logic
                            TempData[AppConstants.MemberRegisterViewModel] = viewModel;

                            return(RedirectToAction("SocialLoginValidator", "Members"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }
            }

            ShowMessage(resultMessage);
            return(RedirectToAction("LogOn", "Members"));
        }
Example #17
0
        /// <summary>
        /// Add a new user
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            if (SettingsService.GetSettings().SuspendRegistration != true)
            {
                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    var user = MembershipService.CreateEmptyUser();

                    // Populate empty viewmodel
                    var viewModel = new MemberAddViewModel
                    {
                        UserName = user.UserName,
                        Email = user.Email,
                        Password = user.Password,
                        IsApproved = user.IsApproved,
                        Comment = user.Comment,
                        AllRoles = RoleService.AllRoles()
                    };

                    // See if a return url is present or not and add it
                    var returnUrl = Request["ReturnUrl"];
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        viewModel.ReturnUrl = returnUrl;
                    }

                    return View(viewModel);
                }
            }
            return RedirectToAction("Index", "Home");
        }
 public IActionResult Add(MemberAddViewModel model)
 {
     _memberService.Add(model.MemberInfo);
     return(RedirectToAction("List"));
 }
Example #19
0
        public ActionResult Add(MemberAddViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                Member member = Member.Empty();
                member.FirstName   = viewModel.FirstName;
                member.LastName    = viewModel.LastName;
                member.MiddleName  = viewModel.MiddleName;
                member.DateOfBirth = viewModel.DateOfBirth;
                member.GenderId    = viewModel.GenderId;
                member.Email       = viewModel.Email;
                member.Phone       = viewModel.Phone;
                member.Mobile      = viewModel.Mobile;

                if (!string.IsNullOrWhiteSpace(viewModel.Address?.FormattedAddress))
                {
                    member.Address = new Address
                    {
                        CountryId        = Dom.Country.Ukraine,
                        City             = viewModel.Address.City,
                        PostalCode       = viewModel.Address.PostalCode,
                        Street           = viewModel.Address.Street,
                        Number           = viewModel.Address.Number,
                        Latitude         = double.Parse(viewModel.Address.Latitude.Replace(".", ",")),
                        Longitude        = double.Parse(viewModel.Address.Longitude.Replace(".", ",")),
                        FormattedAddress = viewModel.Address.FormattedAddress
                    };
                }

                if (!string.IsNullOrWhiteSpace(viewModel.Website?.Url))
                {
                    member.Website = new Website
                    {
                        Url = viewModel.Website.Url,
                    };
                }

                EntityContext.AddEntityProgress(
                    member.EntityInfo,
                    new EntityProgress
                {
                    OrganizationId     = viewModel.OrganizationId,
                    EntityStateAfterId = Dom.EntityType.Member.State.Created
                }
                    );
                EntityContext.AddEntityOrganization(
                    member.EntityInfo,
                    viewModel.OrganizationId,
                    Dom.EntityType.Member.State.Created
                    );
                _memberRepository.AddOrUpdate(member);
                _memberRepository.UnitOfWork.SaveChanges();

                return(RedirectToAction(Mvc.Controller.Member.List, Mvc.Controller.Member.Name));
            }

            ICollection <SelectListItemCount> organizationItems = _organizationRepository.GetOrganizations(
                UserContext.User.Id,
                UserContext.User.OrganizationId,
                new List <int> {
                Dom.OrganizationType.Club
            }
                );

            viewModel.GenderItems       = InitGenderSelectListItems();
            viewModel.OrganizationItems = Mapper.Map <ICollection <SelectListItem> >(organizationItems);
            return(View(Mvc.View.Member.Add, viewModel));
        }
        public ActionResult MemberRegisterLogic(MemberAddViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var settings     = SettingsService.GetSettings();
                var homeRedirect = false;

                var userToSave = new MembershipUser
                {
                    Email     = viewModel.Email,
                    Password  = viewModel.Password,
                    FirstName = viewModel.FirstName,
                    LastName  = viewModel.LastName,
                    City      = viewModel.City,
                    State     = viewModel.State
                };
                var createStatus = MembershipService.CreateUser(userToSave);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus));
                }
                else
                {
                    var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, userToSave.Id));
                    if (uploadFolderPath != null && !Directory.Exists(uploadFolderPath))
                    {
                        Directory.CreateDirectory(uploadFolderPath);
                    }

                    //admin/email approval goes here
                    SetRegisterViewBagMessage(false, false, userToSave);
                    //if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded)
                    //{
                    homeRedirect = true;
                    //}
                    try
                    {
                        // Only send the email if the admin is not manually authorising emails or it's pointless
                        //SendEmailConfirmationEmail(userToSave);
                        unitOfWork.Commit();

                        if (homeRedirect)
                        {
                            if (Url.IsLocalUrl(viewModel.ReturnUrl) && viewModel.ReturnUrl.Length > 1 && viewModel.ReturnUrl.StartsWith("/") &&
                                !viewModel.ReturnUrl.StartsWith("//") && !viewModel.ReturnUrl.StartsWith("/\\"))
                            {
                                return(Redirect(viewModel.ReturnUrl));
                            }
                            return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, "Error registering");
                    }
                }
            }
            return(View("Register"));
        }
Example #21
0
 public ActionResult Add(MemberAddViewModel model)
 {
     _memberService.Add(model.Member);
     return(View(new MemberAddViewModel()));
 }
Example #22
0
        public ActionResult MemberRegisterLogic(MemberAddViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var settings = SettingsService.GetSettings();
                var manuallyAuthoriseMembers = settings.ManuallyAuthoriseNewMembers;
                var memberEmailAuthorisationNeeded = settings.NewMemberEmailConfirmation == true;
                var homeRedirect = false;

                var userToSave = new MembershipUser
                {
                    UserName = _bannedWordService.SanitiseBannedWords(userModel.UserName),
                    Email = userModel.Email,
                    Password = userModel.Password,
                    IsApproved = userModel.IsApproved,
                    Comment = userModel.Comment,
                };

                var createStatus = MembershipService.CreateUser(userToSave);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus));
                }
                else
                {
                    // See if this is a social login and we have their profile pic
                    if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl))
                    {
                        // We have an image url - Need to save it to their profile
                        var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl);

                        // Set upload directory - Create if it doesn't exist
                        var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, userToSave.Id));
                        if (uploadFolderPath != null && !Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Get the file name
                        var fileName = Path.GetFileName(userModel.SocialProfileImageUrl);

                        // Create a HttpPostedFileBase image from the C# Image
                        using (var stream = new MemoryStream())
                        {
                            // Microsoft doesn't give you a file extension - See if it has a file extension
                            // Get the file extension
                            var fileExtension = Path.GetExtension(fileName);

                            // Fix invalid Illegal charactors
                            var regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
                            var reg = new Regex($"[{Regex.Escape(regexSearch)}]");
                            fileName = reg.Replace(fileName, "");

                            if (string.IsNullOrEmpty(fileExtension))
                            {
                                // no file extension so give it one
                                fileName = string.Concat(fileName, ".jpg");
                            }

                            image.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;
                            HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName);

                            // Upload the file
                            var uploadResult = AppHelpers.UploadFile(formattedImage, uploadFolderPath, LocalizationService, true);

                            // Don't throw error if problem saving avatar, just don't save it.
                            if (uploadResult.UploadSuccessful)
                            {
                                userToSave.Avatar = uploadResult.UploadedFileName;
                            }
                        }

                    }

                    // Store access token for social media account in case we want to do anything with it
                    var isSocialLogin = false;
                    if (userModel.LoginType == LoginType.Facebook)
                    {
                        userToSave.FacebookAccessToken = userModel.UserAccessToken;
                        isSocialLogin = true;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        userToSave.GoogleAccessToken = userModel.UserAccessToken;
                        isSocialLogin = true;
                    }
                    if (userModel.LoginType == LoginType.Microsoft)
                    {
                        userToSave.MicrosoftAccessToken = userModel.UserAccessToken;
                        isSocialLogin = true;
                    }

                    // If this is a social login, and memberEmailAuthorisationNeeded is true then we need to ignore it
                    // and set memberEmailAuthorisationNeeded to false because the email addresses are validated by the social media providers
                    if (isSocialLogin && !manuallyAuthoriseMembers)
                    {
                        memberEmailAuthorisationNeeded = false;
                        userToSave.IsApproved = true;
                    }

                    // Set the view bag message here
                    SetRegisterViewBagMessage(manuallyAuthoriseMembers, memberEmailAuthorisationNeeded, userToSave);

                    if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded)
                    {
                        homeRedirect = true;
                    }

                    try
                    {
                        // Only send the email if the admin is not manually authorising emails or it's pointless
                        SendEmailConfirmationEmail(userToSave);

                        unitOfWork.Commit();

                        if (homeRedirect)
                        {
                            if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length > 1 && userModel.ReturnUrl.StartsWith("/")
                            && !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\"))
                            {
                                return Redirect(userModel.ReturnUrl);
                            }
                            return RedirectToAction("Index", "Home", new { area = string.Empty });
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }

            return View("Register");
        }
        public ActionResult FacebookLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias = Request.QueryString["propertyAlias"];

            if (AuthState != null)
            {
                var stateValue = Session["MVCForum_" + AuthState] as string[];
                if (stateValue != null && stateValue.Length == 3)
                {
                    Callback = stateValue[0];
                    ContentTypeAlias = stateValue[1];
                    PropertyAlias = stateValue[2];
                }
            }

            // Get the prevalue options
            if (string.IsNullOrEmpty(SiteConstants.Instance.FacebookAppId) ||
                string.IsNullOrEmpty(SiteConstants.Instance.FacebookAppSecret))
            {
                resultMessage.Message = "You need to add the Facebook app credentials";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {

                // Settings valid move on
                // Configure the OAuth client based on the options of the prevalue options
                var client = new FacebookOAuthClient
                {
                    AppId = SiteConstants.Instance.FacebookAppId,
                    AppSecret = SiteConstants.Instance.FacebookAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session["MVCForum_" + AuthState] == null)
                {
                    resultMessage.Message = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Facebook
                if (AuthError != null)
                {
                    Session.Remove("MVCForum_" + AuthState);
                    resultMessage.Message = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Redirect the user to the Facebook login dialog
                if (AuthCode == null)
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["MVCForum_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends"

                    // Redirect the user
                    return Redirect(url);
                }

                // Exchange the authorization code for a user access token
                var userAccessToken = string.Empty;
                try
                {
                    userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message))
                    {
                        // Initialize the Facebook service (no calls are made here)
                        var service = FacebookService.CreateFromAccessToken(userAccessToken);

                        // Declare the options for the call to the API
                        var options = new FacebookGetUserOptions
                        {
                            Identifier = "me",
                            Fields = new[] { "id", "name", "email", "first_name", "last_name", "gender" }
                        };

                        var user = service.Users.GetUser(options);

                        // Try to get the email - Some FB accounts have protected passwords
                        var email = user.Body.Email;
                        if (string.IsNullOrEmpty(email))
                        {
                            resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress");
                            resultMessage.MessageType = GenericMessages.danger;
                            ShowMessage(resultMessage);
                            return RedirectToAction("LogOn", "Members");
                        }

                        // First see if this user has registered already - Use email address
                        using (UnitOfWorkManager.NewUnitOfWork())
                        {
                            var userExists = MembershipService.GetUserByEmail(email);

                            if (userExists != null)
                            {
                                try
                                {
                                    // Users already exists, so log them in
                                    FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                                    resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn");
                                    resultMessage.MessageType = GenericMessages.success;
                                    ShowMessage(resultMessage);
                                    return RedirectToAction("Index", "Home");
                                }
                                catch (Exception ex)
                                {
                                    LoggingService.Error(ex);
                                }
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new MemberAddViewModel
                                {
                                    Email = email,
                                    LoginType = LoginType.Facebook,
                                    Password = StringUtils.RandomString(8),
                                    UserName = user.Body.Name,
                                    UserAccessToken = userAccessToken
                                };

                                // Get the image and save it
                                var getImageUrl = $"http://graph.facebook.com/{user.Body.Id}/picture?type=square";
                                viewModel.SocialProfileImageUrl = getImageUrl;

                                //Large size photo https://graph.facebook.com/{facebookId}/picture?type=large
                                //Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal
                                //Small size photo https://graph.facebook.com/{facebookId}/picture?type=small
                                //Square photo https://graph.facebook.com/{facebookId}/picture?type=square

                                // Store the viewModel in TempData - Which we'll use in the register logic
                                TempData[AppConstants.MemberRegisterViewModel] = viewModel;

                                return RedirectToAction("SocialLoginValidator", "Members");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }

            }

            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }
Example #24
0
        public ActionResult GoogleLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias = Request.QueryString["propertyAlias"];
            Feature = Request.QueryString["feature"];

            if (AuthState != null)
            {
                var stateValue = Session["MVCForum_" + AuthState] as NameValueCollection;
                if (stateValue != null)
                {
                    Callback = stateValue["Callback"];
                    ContentTypeAlias = stateValue["ContentTypeAlias"];
                    PropertyAlias = stateValue["PropertyAlias"];
                    Feature = stateValue["Feature"];
                }
            }

            if (string.IsNullOrEmpty(SiteConstants.Instance.GooglePlusAppId) ||
                string.IsNullOrEmpty(SiteConstants.Instance.GooglePlusAppSecret))
            {
                resultMessage.Message = "You need to add the Google app credentials";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {
                // Configure the OAuth client based on the options of the prevalue options
                var client = new GoogleOAuthClient
                {
                    ClientId = SiteConstants.Instance.GooglePlusAppId,
                    ClientSecret = SiteConstants.Instance.GooglePlusAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session["MVCForum_" + AuthState] == null)
                {
                    resultMessage.Message = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Google
                if (AuthError != null)
                {
                    resultMessage.Message = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                    if (AuthState != null) Session.Remove("MVCForum_" + AuthState);
                }

                // Redirect the user to the Google login dialog
                if (AuthCode == null)
                {

                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["MVCForum_" + state] = new NameValueCollection {
                    { "Callback", Callback},
                    { "ContentTypeAlias", ContentTypeAlias},
                    { "PropertyAlias", PropertyAlias},
                    { "Feature", Feature}
                };

                    // Declare the scope
                    var scope = new[] {
                    GoogleScopes.OpenId,
                    GoogleScopes.Email,
                    GoogleScopes.Profile
                };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force);

                    // Redirect the user
                    return Redirect(url);
                }

                var info = new GoogleAccessTokenResponse();
                try
                {
                    info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                try
                {

                    // Initialize the Google service
                    var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken);

                    // Get information about the authenticated user
                    var user = service.GetUserInfo();
                    using (UnitOfWorkManager.NewUnitOfWork())
                    {
                        var userExists = MembershipService.GetUserByEmail(user.Email);

                        if (userExists != null)
                        {
                            // Users already exists, so log them in
                            FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                            resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn");
                            resultMessage.MessageType = GenericMessages.success;
                            ShowMessage(resultMessage);
                            return RedirectToAction("Index", "Home");
                        }
                        else
                        {
                            // Not registered already so register them
                            var viewModel = new MemberAddViewModel
                            {
                                Email = user.Email,
                                LoginType = LoginType.Google,
                                Password = StringUtils.RandomString(8),
                                UserName = user.Name,
                                SocialProfileImageUrl = user.Picture,
                                UserAccessToken = info.RefreshToken
                            };

                            // Store the viewModel in TempData - Which we'll use in the register logic
                            TempData[AppConstants.MemberRegisterViewModel] = viewModel;

                            return RedirectToAction("SocialLoginValidator", "Members");
                        }
                    }

                }
                catch (Exception ex)
                {
                    resultMessage.Message = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }

            }

            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }
        private HttpResponseMessage MemberRegisterLogic(MemberAddViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var userToSave = new MVCForum.Domain.DomainModel.MembershipUser
                {
                    UserName    = _bannedWordService.SanitiseBannedWords(userModel.UserName),
                    Email       = userModel.Email,
                    Password    = userModel.Password,
                    IsApproved  = userModel.IsApproved,
                    Comment     = userModel.Comment,
                    UniversalId = userModel.UniversalId
                };

                var createStatus = _membershipService.CreateUser(userToSave);
                if (createStatus != MVCForum.Domain.DomainModel.MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, _membershipService.ErrorCodeToString(createStatus));
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
                else
                {
                    // See if this is a social login and we have their profile pic
                    if (!string.IsNullOrWhiteSpace(userModel.SocialProfileImageUrl))
                    {
                        // We have an image url - Need to save it to their profile
                        var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl);

                        // Set upload directory - Create if it doesn't exist
                        var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.UploadFolderPath, userToSave.Id));
                        if (!Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Get the file name
                        var fileName = Path.GetFileName(userModel.SocialProfileImageUrl);

                        // Create a HttpPostedFileBase image from the C# Image
                        using (var stream = new MemoryStream())
                        {
                            image.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;
                            HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName);

                            // Upload the file
                            var uploadResult = AppHelpers.UploadFile(formattedImage, uploadFolderPath, LocalizationService);

                            // Don't throw error if problem saving avatar, just don't save it.
                            if (uploadResult.UploadSuccessful)
                            {
                                userToSave.Avatar = uploadResult.UploadedFileName;
                            }
                        }
                    }

                    // Store access token for social media account in case we want to do anything with it
                    if (userModel.LoginType == LoginType.Facebook)
                    {
                        userToSave.FacebookAccessToken = userModel.UserAccessToken;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        userToSave.GoogleAccessToken = userModel.UserAccessToken;
                    }

                    if (userModel.Roles != null && userModel.Roles.Any())
                    {
                        UpdateUserRoles(userToSave, userModel.Roles);
                    }

                    try
                    {
                        userToSave.IsApproved = userModel.IsApproved;
                        unitOfWork.Commit();
                        return(Request.CreateResponse(HttpStatusCode.OK, userToSave.Id));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                    }
                }
            }
        }
Example #26
0
        public ActionResult MicrosoftLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            var input = new
            {
                Code  = AuthCode,
                State = AuthState,
                Error = new
                {
                    HasError         = !String.IsNullOrWhiteSpace(AuthError),
                    Text             = AuthError,
                    ErrorDescription = AuthErrorDescription
                }
            };


            // Get the prevalue options
            if (string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppId) ||
                string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppSecret))
            {
                resultMessage.Message     = "You need to add the Microsoft app credentials to the web.config";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {
                var client = new MicrosoftOAuthClient
                {
                    ClientId     = SiteConstants.Instance.MicrosoftAppId,
                    ClientSecret = SiteConstants.Instance.MicrosoftAppSecret,
                    RedirectUri  = ReturnUrl
                };

                // Session expired?
                if (input.State != null && Session["MVCForum_" + input.State] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Microsoft
                if (input.Error.HasError)
                {
                    Session.Remove("MVCForum_" + input.State);
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Redirect the user to the Microsoft login dialog
                if (string.IsNullOrWhiteSpace(input.Code))
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["MVCForum_" + state] = "/";

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday);

                    // Redirect the user
                    return(Redirect(url));
                }

                // Exchange the authorization code for an access token
                MicrosoftTokenResponse accessTokenResponse;
                try
                {
                    Session.Remove("MVCForum_" + input.State);
                    accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code);
                }
                catch (Exception ex)
                {
                    accessTokenResponse       = null;
                    resultMessage.Message     = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }


                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null)
                    {
                        //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items;

                        //accessTokenResponse.Body.AccessToken
                        //foreach (MicrosoftScope scope in accessTokenResponse.Body.Scope.Items) {
                        //    scope
                        //}
                        //accessTokenResponse.Response.Body

                        // Initialize a new MicrosoftService so we can make calls to the API
                        var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                        // Make the call to the Windows Live API / endpoint
                        var response = service.WindowsLive.GetSelf();

                        // Get a reference to the response body
                        var user = response.Body;

                        var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred);
                        if (!getEmail)
                        {
                            resultMessage.Message     = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress");
                            resultMessage.MessageType = GenericMessages.danger;
                            ShowMessage(resultMessage);
                            return(RedirectToAction("LogOn", "Members"));
                        }

                        using (UnitOfWorkManager.NewUnitOfWork())
                        {
                            var userExists = MembershipService.GetUserByEmail(user.Emails.Preferred);

                            if (userExists != null)
                            {
                                try
                                {
                                    // Users already exists, so log them in
                                    FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                                    resultMessage.Message     = LocalizationService.GetResourceString("Members.NowLoggedIn");
                                    resultMessage.MessageType = GenericMessages.success;
                                    ShowMessage(resultMessage);
                                    return(RedirectToAction("Index", "Home"));
                                }
                                catch (Exception ex)
                                {
                                    LoggingService.Error(ex);
                                }
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new MemberAddViewModel
                                {
                                    Email                 = user.Emails.Preferred,
                                    LoginType             = LoginType.Microsoft,
                                    Password              = StringUtils.RandomString(8),
                                    UserName              = user.Name,
                                    UserAccessToken       = accessTokenResponse.Body.AccessToken,
                                    SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture"
                                };

                                //var uri = string.Concat("https://apis.live.net/v5.0/me?access_token=",viewModel.UserAccessToken);
                                //using (var dl = new WebClient())
                                //{
                                //    var profile = JObject.Parse(dl.DownloadString(uri));
                                //    var pictureUrl = ;
                                //    if (!string.IsNullOrEmpty(pictureUrl))
                                //    {
                                //        //viewModel.SocialProfileImageUrl = getImageUrl;
                                //    }
                                //}


                                // Store the viewModel in TempData - Which we'll use in the register logic
                                TempData[AppConstants.MemberRegisterViewModel] = viewModel;

                                return(RedirectToAction("SocialLoginValidator", "Members"));
                            }
                        }
                    }
                    else
                    {
                        resultMessage.MessageType = GenericMessages.danger;
                        ShowMessage(resultMessage);
                        return(RedirectToAction("LogOn", "Members"));
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }
            }


            ShowMessage(resultMessage);
            return(RedirectToAction("LogOn", "Members"));
        }
        public ActionResult MicrosoftLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            var input = new
            {
                Code = AuthCode,
                State = AuthState,
                Error = new
                {
                    HasError = !String.IsNullOrWhiteSpace(AuthError),
                    Text = AuthError,
                    ErrorDescription = AuthErrorDescription
                }
            };

            // Get the prevalue options
            if (string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppId) ||
                string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppSecret))
            {
                resultMessage.Message = "You need to add the Microsoft app credentials to the web.config";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {

                var client = new MicrosoftOAuthClient
                {
                    ClientId = SiteConstants.Instance.MicrosoftAppId,
                    ClientSecret = SiteConstants.Instance.MicrosoftAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (input.State != null && Session["MVCForum_" + input.State] == null)
                {
                    resultMessage.Message = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Microsoft
                if (input.Error.HasError)
                {
                    Session.Remove("MVCForum_" + input.State);
                    resultMessage.Message = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Redirect the user to the Microsoft login dialog
                if (string.IsNullOrWhiteSpace(input.Code))
                {

                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["MVCForum_" + state] = "/";

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday);

                    // Redirect the user
                    return Redirect(url);
                }

                // Exchange the authorization code for an access token
                MicrosoftTokenResponse accessTokenResponse;
                try
                {
                    Session.Remove("MVCForum_" + input.State);
                    accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code);
                }
                catch (Exception ex)
                {
                    accessTokenResponse = null;
                    resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null)
                    {
                        //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items;

                        //accessTokenResponse.Body.AccessToken
                        //foreach (MicrosoftScope scope in accessTokenResponse.Body.Scope.Items) {
                        //    scope
                        //}
                        //accessTokenResponse.Response.Body

                        // Initialize a new MicrosoftService so we can make calls to the API
                        var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                        // Make the call to the Windows Live API / endpoint
                        var response = service.WindowsLive.GetSelf();

                        // Get a reference to the response body
                        var user = response.Body;

                        var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred);
                        if (!getEmail)
                        {
                            resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress");
                            resultMessage.MessageType = GenericMessages.danger;
                            ShowMessage(resultMessage);
                            return RedirectToAction("LogOn", "Members");
                        }

                        using (UnitOfWorkManager.NewUnitOfWork())
                        {
                            var userExists = MembershipService.GetUserByEmail(user.Emails.Preferred);

                            if (userExists != null)
                            {
                                try
                                {
                                    // Users already exists, so log them in
                                    FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                                    resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn");
                                    resultMessage.MessageType = GenericMessages.success;
                                    ShowMessage(resultMessage);
                                    return RedirectToAction("Index", "Home");
                                }
                                catch (Exception ex)
                                {
                                    LoggingService.Error(ex);
                                }
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new MemberAddViewModel
                                {
                                    Email = user.Emails.Preferred,
                                    LoginType = LoginType.Microsoft,
                                    Password = StringUtils.RandomString(8),
                                    UserName = user.Name,
                                    UserAccessToken = accessTokenResponse.Body.AccessToken,
                                    SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture"
                                };

                                //var uri = string.Concat("https://apis.live.net/v5.0/me?access_token=",viewModel.UserAccessToken);
                                //using (var dl = new WebClient())
                                //{
                                //    var profile = JObject.Parse(dl.DownloadString(uri));
                                //    var pictureUrl = ;
                                //    if (!string.IsNullOrEmpty(pictureUrl))
                                //    {
                                //        //viewModel.SocialProfileImageUrl = getImageUrl;
                                //    }
                                //}

                                // Store the viewModel in TempData - Which we'll use in the register logic
                                TempData[AppConstants.MemberRegisterViewModel] = viewModel;

                                return RedirectToAction("SocialLoginValidator", "Members");
                            }
                        }

                    }
                    else
                    {
                        resultMessage.MessageType = GenericMessages.danger;
                        ShowMessage(resultMessage);
                        return RedirectToAction("LogOn", "Members");
                    }

                }
                catch (Exception ex)
                {
                    resultMessage.Message = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }

            }

            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }
Example #28
0
        public ActionResult Register(MemberAddViewModel userModel)
        {
            if (SettingsService.GetSetting("SuspendRegistration") != "true" && SettingsService.GetSetting("DisableStandardRegistration") != "true")
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    if (userModel.Password != userModel.ConfirmPassword)
                    {
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.PasswordNotConfirm"));
                        return(View(userModel));
                    }

                    // First see if there is a spam question and if so, the answer matches
                    if (!string.IsNullOrEmpty(SettingsService.GetSetting("SpamQuestion")))
                    {
                        // There is a spam question, if answer is wrong return with error
                        if (userModel.SpamAnswer == null || userModel.SpamAnswer.Trim() != SettingsService.GetSetting("SpamAnswer"))
                        {
                            // POTENTIAL SPAMMER!
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.WrongAnswerRegistration"));
                            return(View(userModel));
                        }
                    }

                    // Secondly see if the email is banned
                    //if (_bannedEmailService.EmailIsBanned(userModel.Email))
                    //{
                    //    ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.EmailIsBanned"));
                    //    return View();
                    //}

                    MembershipUser newuser = new MembershipUser();
                    newuser.UserName = userModel.UserName;
                    newuser.Password = userModel.Password;
                    newuser.Email    = userModel.Email;


                    var createStatus = MembershipService.NewUser(newuser);
                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus));
                        return(View(userModel));
                    }
                    else
                    {
                    }

                    try
                    {
                        unitOfWork.Commit();

                        if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length > 1 && userModel.ReturnUrl.StartsWith("/") &&
                            !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\"))
                        {
                            return(Redirect(userModel.ReturnUrl));
                        }
                        return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        //System.Web.Security.FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }
            return(View(userModel));
        }
Example #29
0
        public ActionResult Register(MemberAddViewModel userModel)
        {
            if (SettingsService.GetSettings().SuspendRegistration != true && SettingsService.GetSettings().DisableStandardRegistration != true)
            {
                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    // First see if there is a spam question and if so, the answer matches
                    if (!string.IsNullOrEmpty(SettingsService.GetSettings().SpamQuestion))
                    {
                        // There is a spam question, if answer is wrong return with error
                        if (userModel.SpamAnswer == null || userModel.SpamAnswer.Trim() != SettingsService.GetSettings().SpamAnswer)
                        {
                            // POTENTIAL SPAMMER!
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.WrongAnswerRegistration"));
                            return View();
                        }
                    }

                    // Secondly see if the email is banned
                    if (_bannedEmailService.EmailIsBanned(userModel.Email))
                    {
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.EmailIsBanned"));
                        return View();
                    }
                }

                // Standard Login
                userModel.LoginType = LoginType.Standard;

                // Do the register logic
                return MemberRegisterLogic(userModel);

            }
            return RedirectToAction("Index", "Home");
        }