Ejemplo n.º 1
0
        public ActionResult LogOn(LogOnViewModel model)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var username = model.UserName;
                var password = model.Password;

                try
                {
                    if (ModelState.IsValid)
                    {
                        // We have an event here to help with Single Sign Ons
                        // You can do manual lookups to check users based on a webservice and validate a user
                        // Then log them in if they exist or create them and log them in - Have passed in a UnitOfWork
                        // To allow database changes.

                        var e = new LoginEventArgs
                        {
                            UserName = model.UserName,
                            Password = model.Password,
                            RememberMe = model.RememberMe,
                            ReturnUrl = model.ReturnUrl, 
                            UnitOfWork = unitOfWork
                        };
                        EventManager.Instance.FireBeforeLogin(this, e);

                        if (!e.Cancel)
                        {
                            var message = new GenericMessageViewModel();
                            var user = new MembershipUser();
                            if (MembershipService.ValidateUser(username, password, System.Web.Security.Membership.MaxInvalidPasswordAttempts))
                            {
                                // Set last login date
                                user = MembershipService.GetUser(username);
                                if (user.IsApproved && !user.IsLockedOut && !user.IsBanned)
                                {
                                    FormsAuthentication.SetAuthCookie(username, model.RememberMe);
                                    user.LastLoginDate = DateTime.UtcNow;

                                    if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/")
                                        && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
                                    {
                                        return Redirect(model.ReturnUrl);
                                    }

                                    message.Message = LocalizationService.GetResourceString("Members.NowLoggedIn");
                                    message.MessageType = GenericMessages.success;

                                    EventManager.Instance.FireAfterLogin(this, new LoginEventArgs
                                    {
                                        UserName = model.UserName,
                                        Password = model.Password,
                                        RememberMe = model.RememberMe,
                                        ReturnUrl = model.ReturnUrl,
                                        UnitOfWork = unitOfWork
                                    });

                                    return RedirectToAction("Index", "Home", new { area = string.Empty });
                                }
                                //else if (!user.IsApproved && SettingsService.GetSettings().ManuallyAuthoriseNewMembers)
                                //{

                                //    message.Message = LocalizationService.GetResourceString("Members.NowRegisteredNeedApproval");
                                //    message.MessageType = GenericMessages.success;

                                //}
                                //else if (!user.IsApproved && SettingsService.GetSettings().NewMemberEmailConfirmation == true)
                                //{

                                //    message.Message = LocalizationService.GetResourceString("Members.MemberEmailAuthorisationNeeded");
                                //    message.MessageType = GenericMessages.success;
                                //}
                            }

                            // Only show if we have something to actually show to the user
                            if (!string.IsNullOrEmpty(message.Message))
                            {
                                TempData[AppConstants.MessageViewBagName] = message;
                            }
                            else
                            {
                                // get here Login failed, check the login status
                                var loginStatus = MembershipService.LastLoginStatus;

                                switch (loginStatus)
                                {
                                    case LoginAttemptStatus.UserNotFound:
                                    case LoginAttemptStatus.PasswordIncorrect:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.PasswordIncorrect"));
                                        break;

                                    case LoginAttemptStatus.PasswordAttemptsExceeded:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.PasswordAttemptsExceeded"));
                                        break;

                                    case LoginAttemptStatus.UserLockedOut:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.UserLockedOut"));
                                        break;

                                    case LoginAttemptStatus.Banned:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.NowBanned"));
                                        break;

                                    case LoginAttemptStatus.UserNotApproved:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.UserNotApproved"));
                                        user = MembershipService.GetUser(username);
                                        SendEmailConfirmationEmail(user);
                                        break;

                                    default:
                                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.LogonGeneric"));
                                        break;
                                }
                            }
                        }
                    }
                }

                finally
                {
                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                    }

                }

                return View(model);
            }
        }
Ejemplo n.º 2
0
        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 = string.Format("Unable to acquire access token<br/>{0}", 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 = string.Format("http://graph.facebook.com/{0}/picture?type=square", user.Body.Id);
                                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 = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }

            }

            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }
Ejemplo n.º 3
0
 protected void ShowMessage(GenericMessageViewModel messageViewModel)
 {
     //ViewData[AppConstants.MessageViewBagName] = messageViewModel;
     TempData[AppConstants.MessageViewBagName] = messageViewModel;
 }
Ejemplo n.º 4
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.MicrosoftAppId) ||
                string.IsNullOrEmpty(SiteConstants.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.MicrosoftAppId,
                    ClientSecret = SiteConstants.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 = string.Format("Unable to acquire access token<br/>{0}", 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 = user.Emails != null && !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 = string.Format("https://apis.live.net/v5.0/{0}/picture", user.Id)
                                };

                                //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 = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }



            }


            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }
Ejemplo n.º 5
0
        public ActionResult SendTestEmail()
        {
            using (var uow = UnitOfWorkManager.NewUnitOfWork())
            {
                var sb = new StringBuilder();
                sb.AppendFormat("<p>{0}</p>",
                    string.Concat("This is a test email from ", SettingsService.GetSettings().ForumName));
                var email = new Email
                {
                    EmailTo = SettingsService.GetSettings().AdminEmailAddress,
                    NameTo = "Email Test Admin",
                    Subject = string.Concat("Email Test From ", SettingsService.GetSettings().ForumName)
                };
                email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                _emailService.SendMail(email);

                var message = new GenericMessageViewModel
                {
                    Message = "Test Email Sent",
                    MessageType = GenericMessages.success
                };

                try
                {
                    uow.Commit();
                }
                catch (Exception ex)
                {
                    uow.Rollback();
                    LoggingService.Error(ex);
                    message.Message = "Error sending email";
                    message.MessageType = GenericMessages.danger;
                }
                TempData[AppConstants.MessageViewBagName] = message;

                return RedirectToAction("Index");
            }
        }
Ejemplo n.º 6
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;
                }

            }

            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }