/// <summary>
        /// Save enterprise settings
        /// </summary>
        /// <returns></returns>
        public async Task SaveSettingAsync()
        {
            await RunCommandAsync(() => Saving, async() =>
            {
                if (HasErrors)
                {
                    return;
                }

                var credentials = await ClientDataStore.GetLoginCredentialsAsync();
                var result      = await WebRequests.PostAsync <ApiResponse>(
                    url: RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateEnterpriseSetting),
                    content: new UpdateEnterpriseSettingsApiModel
                {
                    CompanyName = CompanyName
                },
                    bearerToken: credentials.Token
                    );

                // If the response has an error...
                if (await result.HandleErrorIfFailedAsync("Update failed"))
                {
                    // We are done
                    return;
                }
            });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Attempts to register a new user
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/>passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task RegisterAsync(object parameter)
        {
            // Call the server and attempt to register with the provided credentials
            var result = await WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.Register),
                // Create api model
                new RegisterCredentialsApiModel
            {
                Username = Username,
                Email    = Email,
                Password = (parameter as IHavePassword).SecurePassword.Unsecure()
            });

            // If the reposne has an error...
            if (await result.DisplayErrorIfFailedAsync("Register failed"))
            {
                //We are done
                return;
            }

            // OK successfully registered (and logged in)... now get users data
            var loginResult = result.ServerResponse.ResponseT;

            // Let the application view model handle what happens
            // With the successful login
            await ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
        }
        /// <summary>
        /// Loads the enterprise settings from database
        /// </summary>
        /// <returns></returns>
        public async Task LoadEnterPriseSettingsAsync()
        {
            // Lock this command to ignore any other requests while processing
            await RunCommandAsync(() => Loading, async() =>
            {
                ErrorLoading = false;
                ErrorText    = default(string);
                // Get the current known credentials
                var credentials = await ClientDataStore.GetLoginCredentialsAsync();

                var result = await WebRequests.PostAsync <ApiResponse <EnterpriseSettingResultApiModel> >(
                    url: RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetEnterpriseSetting),
                    bearerToken: credentials.Token
                    );


                // If the response has an error...don't mind to continue
                if (await result.HandleErrorIfFailedAsync())
                {
                    ErrorLoading = true;
                    ErrorText    = result.ErrorMessage;
                    return;
                }


                var dataModel = result.ServerResponse.Response;

                CompanyName = dataModel.CompanyName;
            });
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/> passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Login),
                    // Create api model
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Login Failed"))
                {
                    // We are done
                    return;
                }

                // OK successfully logged in... now get users data
                var loginResult = result.ServerResponse.Response;

                // Let the application view model handle what happens
                // with the successful login
                await CoinFlipper.DI.ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Saves the new Password to the server
        /// </summary>
        /// <returns>Returns true if successful, false otherwise</returns>
        public async Task <bool> SavePasswordAsync()
        {
            // Lock this command to ignore any other requests while processing
            return(await RunCommandAsync(() => PasswordIsChanging, async() =>
            {
                // Log it
                Logger.LogDebugSource($"Changing password...");

                // Get the current known credentials
                var credentials = await ClientDataStore.GetLoginCredentialsAsync();

                // Make sure the user has entered the same password
                if (Password.NewPassword.Unsecure() != Password.ConfirmPassword.Unsecure())
                {
                    // Display error
                    await UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        // TODO: Localize
                        Title = "Password Mismatch",
                        Message = "New password and confirm password must match"
                    });

                    // Return fail
                    return false;
                }

                // Update the server with the new password
                var result = await WebRequests.PostAsync <ApiResponse>(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserPassword),
                    // Create API model
                    new UpdateUserPasswordApiModel
                {
                    CurrentPassword = Password.CurrentPassword.Unsecure(),
                    NewPassword = Password.NewPassword.Unsecure()
                },
                    // Pass in user Token
                    bearerToken: credentials.Token);

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync($"Change Password"))
                {
                    // Log it
                    Logger.LogDebugSource($"Failed to change password. {result.ErrorMessage}");

                    // Return false
                    return false;
                }

                // Otherwise, we succeeded...

                // Log it
                Logger.LogDebugSource($"Successfully changed password");

                // Return successful
                return true;
            }));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Sets the settings view model properties based on the data in the client data store
        /// </summary>
        public async Task LoadAsync()
        {
            // Lock this command to ignore any other requests while processing
            await RunCommandAsync(() => SettingsLoading, async() =>
            {
                // Store single transcient instance of client data store
                var scopedClientDataStore = ClientDataStore;

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync(scopedClientDataStore);

                // Get the user token
                var token = (await scopedClientDataStore.GetLoginCredentialsAsync())?.Token;

                // If we don't have a token (so we are not logged in...)
                if (string.IsNullOrEmpty(token))
                {
                    // Then do nothing more
                    return;
                }
                else
                {
                    ViewModelApplication.LoginDetailsVisible = true;
                }


                return;

                // Load user profile details form server
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetUserProfile),
                    // Pass in user Token
                    bearerToken: token);

                // If the response has an error...
                if (await result.HandleErrorIfFailedAsync("Load User Details Failed"))
                {
                    // We are done
                    return;
                }

                // TODO: Should we check if the values are different before saving?

                // Create data model from the response
                var dataModel = result.ServerResponse.Response.ToLoginCredentialsDataModel();

                // Re-add our known token
                dataModel.Token = token;

                // Save the new information in the data store
                await scopedClientDataStore.SaveLoginCredentialsAsync(dataModel);

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync(scopedClientDataStore);
            });
        }
Ejemplo n.º 7
0
        public void When_Url_Slash_Home_Index()
        {
            const string url = "~/";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Home",
                Action     = "Index",
            });
        }
Ejemplo n.º 8
0
        public void slash_user_user_index()
        {
            const string url = "~/User";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "User",
                Action     = "Index",
            });
        }
Ejemplo n.º 9
0
        public void slash_user_register_user_register()
        {
            const string url = "~/User/Register";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "User",
                Action     = "Register",
            });
        }
Ejemplo n.º 10
0
        public void slash_user_login_user_login()
        {
            const string url = "~/User/Login";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "User",
                Action     = "Login",
            });
        }
Ejemplo n.º 11
0
        public void url_when_cb_admin_redirect_to_admin_index()
        {
            string url = "~/cb-admin";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Admin",
                Action     = "Index"
            });
        }
Ejemplo n.º 12
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (ShouldBypassThisFilter(filterContext))
            {
                return;
            }

            filterContext.Result = OdsInstanceFirstTimeSetupCompleted()
                ? RouteHelpers.RedirectToActionRoute <SetupController>(x => x.PostUpdateSetup())
                : RouteHelpers.RedirectToActionRoute <SetupController>(x => x.FirstTimeSetup());
        }
Ejemplo n.º 13
0
        public void url_when_tag_tag_name_redirect_to_post_list_by_tag()
        {
            string url = "~/Tag/tag-name";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Post",
                Action     = "ListPerTag",
                Tag        = "tag-name"
            });
        }
Ejemplo n.º 14
0
        public void slash_b_blogSlug_to_blog_details()
        {
            const string url = "~/b/Soltys_AweSomeBlog";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Blog",
                Action     = "Details",
                BlogSlug   = "Soltys_AweSomeBlog",
            });
        }
Ejemplo n.º 15
0
        public void slash_b_empty_without_ending_slash_to_blog_details()
        {
            const string url = "~/b";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Blog",
                Action     = "Details",
                BlogSlug   = "",
            });
        }
Ejemplo n.º 16
0
        public void slash_b_blogSlug_postSlug_to_post_details()
        {
            const string url = "~/b/Soltys_AweSomeBlog/Soltys_M_E_G_A_post";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Post",
                Action     = "Details",
                BlogSlug   = "Soltys_AweSomeBlog",
                PostSlug   = "Soltys_M_E_G_A_post"
            });
        }
Ejemplo n.º 17
0
        public void url_when_slash_redirect_to_post_list()
        {
            string url = "~/";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Post",
                Action     = "List",
                Year       = string.Empty,
                Month      = string.Empty,
                Day        = string.Empty
            });
        }
Ejemplo n.º 18
0
        public void url_when_year_redirect_to_post_list_by_year()
        {
            string url = "~/2011";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Post",
                Action     = "List",
                Year       = "2011",
                Month      = string.Empty,
                Day        = string.Empty,
            });
        }
Ejemplo n.º 19
0
        public void url_when_full_date_redirect_to_post_list_by_full_name()
        {
            string url = "~/2011/03/22";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Post",
                Action     = "List",
                Year       = "2011",
                Month      = "03",
                Day        = "22",
            });
        }
Ejemplo n.º 20
0
        public void url_when_full_date_and_post_name_redirect_to_post_details_by_date_and_name()
        {
            string url = "~/2011/03/22/post-name";

            RouteHelpers.TestRoute(url, new
            {
                Controller = "Post",
                Action     = "Details",
                Year       = "2011",
                Month      = "03",
                Day        = "22",
                PostName   = "post-name"
            });
        }
Ejemplo n.º 21
0
        public static bool IsCurrent(this HtmlHelper htmlHelper, ActionResult result)
        {
            Condition.Requires(htmlHelper).IsNotNull();

            if (result == null)
            {
                return(false);
            }

            var currentValues  = htmlHelper.ViewContext.RouteData.GetT4RouteValueDictionary();
            var expectedValues = result.GetRouteValueDictionary();

            return(RouteHelpers.Equals(currentValues, expectedValues));
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            if (!ShouldBypassThisFilter(filterContext))
            {
                if (await IsPasswordChangeRequired(filterContext))
                {
                    filterContext.Result =
                        RouteHelpers.RedirectToActionRoute <IdentityController>(x => x.ChangePassword());

                    return;
                }
            }

            await next();
        }
Ejemplo n.º 23
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (ShouldBypassThisFilter(filterContext))
            {
                return;
            }

            _userManager = filterContext.HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();

            if (IsPasswordChangeRequired())
            {
                filterContext.Result =
                    RouteHelpers.RedirectToActionRoute <IdentityController>(x => x.ChangePassword());
            }
        }
Ejemplo n.º 24
0
        protected void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            Condition.Requires(context).IsNotNull();

            var currentValues  = context.RouteData.GetT4RouteValueDictionary();
            var result         = RedirectResult.Value;
            var expectedValues = result.GetRouteValueDictionary();

            if (RouteHelpers.Equals(currentValues, expectedValues))
            {
                return;
            }

            var url = EngineContext.Current.Resolve <UrlHelper>().Action(result);

            context.Result = new RedirectResult(url);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets all users
        /// </summary>
        /// <returns></returns>
        public async Task GetUsersAsync()
        {
            await RunCommandAsync(() => UsersLoading, async() =>
            {
                await Task.Delay(1);

                var credentials = await ClientDataStore.GetLoginCredentialsAsync();

                var result = await WebRequests.PostAsync <ApiResponse <UserResultApiModel> >(
                    url: RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetEnterpriseSetting),
                    bearerToken: credentials.Token
                    );


                // If the response has an error...don't mind to continue
                if (await result.HandleErrorIfFailedAsync())
                {
                    return;
                }
            });
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Sets the settings view model properties based on the data in the client data store
        /// </summary>
        public async Task LoadAsync()
        {
            // Update values from local cache
            await UpdateValuesFromLocalStoreAsync();

            // Get the user token
            var token = (await ClientDataStore.GetLoginCredentialsAsync()).Token;

            // If we don't have a token (so we are not logged in...)
            if (string.IsNullOrEmpty(token))
            {
                // Then do nothing more
                return;
            }

            // Load user profile details form server
            var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserProfile),
                // Pass in user Token
                bearerToken : token);

            // If it was successful...
            if (result.Successful)
            {
                // TODO: Should we check if the values are different before saving?

                // Create data model from the response
                var dataModel = result.ServerResponse.Response.ToLoginCredentialsDataModel();

                // Re-add our known token
                dataModel.Token = token;

                // Save the new information in the data store
                await ClientDataStore.SaveLoginCredentialsAsync(dataModel);

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync();
            }
        }
Ejemplo n.º 27
0
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                var result = await Dna.WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Login),
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = ((IHavePassword)parameter).SecurePassword.Unsecure()
                });

                if (await result.HandleErrorIfFailedAsync("Login Failed"))
                {
                    return;
                }

                var loginResult = result.ServerResponse.Response;

                await DI.Di.ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
Ejemplo n.º 28
0
        internal static Route MapT4Route(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
        {
            Condition.Requires(routes).IsNotNull();
            Condition.Requires(url).IsNotNull();

            url = RouteHelpers.UrlFormatter(url);

            var route = new LowercaseRoute(url, new MvcRouteHandler())
            {
                Defaults    = defaults.Convert(),
                Constraints = constraints.Convert(),
                DataTokens  = new RouteValueDictionary()
            };

            if (namespaces != null && namespaces.Length > 0)
            {
                route.DataTokens["Namespaces"] = namespaces;
            }

            routes.Add(name, route);

            return(route);
        }
Ejemplo n.º 29
0
        public async Task RegisterAsync(object parameter)
        {
            await RunCommandAsync(() => RegisterIsRunning, async() =>
            {
                var result = await Dna.WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >(
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Register),
                    new RegisterCredentialsApiModel
                {
                    Username = Username,
                    Email    = Email,
                    Password = (parameter as IHavePassword)?.SecurePassword.Unsecure()
                });

                if (await result.HandleErrorIfFailedAsync("Register Failed"))
                {
                    return;
                }

                var loginResult = result.ServerResponse.Response;

                await DI.Di.ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Updates a specific value from the client data store for the user profile details
        /// and attempts to update the server to match those details.
        /// For example, updating the first name of the user.
        /// </summary>
        /// <param name="displayName">The display name for logging and display purposes of the property we are updating</param>
        /// <param name="propertyToUpdate">The property from the <see cref="LoginCredentialsDataModel"/> to be updated</param>
        /// <param name="newValue">The new value to update the property to</param>
        /// <param name="setApiModel">Sets the correct property in the <see cref="UpdateUserProfileApiModel"/> model that this property maps to</param>
        /// <returns></returns>
        private async Task <bool> UpdateUserCredentialsValueAsync(string displayName, Expression <Func <LoginCredentialsDataModel, string> > propertyToUpdate, string newValue, Action <UpdateUserProfileApiModel, string> setApiModel)
        {
            // Log it
            Logger.LogDebugSource($"Saving {displayName}...");

            // Get the current known credentials
            var credentials = await ClientDataStore.GetLoginCredentialsAsync();

            // Get the property to update from the credentials
            var toUpdate = propertyToUpdate.GetPropertyValue(credentials);

            // Log it
            Logger.LogDebugSource($"{displayName} currently {toUpdate}, updating to {newValue}");

            // Check if the value is the same. If so...
            if (toUpdate == newValue)
            {
                // Log it
                Logger.LogDebugSource($"{displayName} is the same, ignoring");

                // Return true
                return(true);
            }

            // Set the property
            propertyToUpdate.SetPropertyValue(newValue, credentials);

            // Create update details
            var updateApiModel = new UpdateUserProfileApiModel();

            // Ask caller to set appropriate value
            setApiModel(updateApiModel, newValue);

            // Update the server with the details
            var result = await WebRequests.PostAsync <ApiResponse>(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserProfile),
                // Pass the Api model
                updateApiModel,
                // Pass in user Token
                bearerToken : credentials.Token);

            // If the response has an error...
            if (await result.DisplayErrorIfFailedAsync($"Update {displayName}"))
            {
                // Log it
                Logger.LogDebugSource($"Failed to update {displayName}. {result.ErrorMessage}");

                // Return false
                return(false);
            }

            // Log it
            Logger.LogDebugSource($"Successfully updated {displayName}. Saving to local database cache...");

            // Store the new user credentials the data store
            await ClientDataStore.SaveLoginCredentialsAsync(credentials);

            // Return successful
            return(true);
        }