Ejemplo n.º 1
0
        protected override void OnData()
        {
            base.OnData();

            SystemUser user = SystemUser.GetCurrentSystemUser();

            if (user != null)
            {
                this.Username = user.Username;
            }
        }
Ejemplo n.º 2
0
        protected override void OnData()
        {
            base.OnData();

            SystemUser   user  = SystemUser.GetCurrentSystemUser();
            EmailAddress email = Utils.GetUserEmailAddress(user);

            this.Username = user.Username;

            if (email != null)
            {
                this.Email = email.Name;
            }
        }
Ejemplo n.º 3
0
        public void RefreshCurrentPage()
        {
            if (string.IsNullOrEmpty(this.PartialUrl))
            {
                this.CurrentPage = null;
                return;
            }

            SystemUser user = SystemUser.GetCurrentSystemUser();

            if (SystemUser.IsMemberOfGroup(user, allowedSystemUserGroup))
            {
                this.CurrentPage = Self.GET(this.PartialUrl);
            }
            else
            {
                this.CurrentPage = Self.GET("/website/partials/deny");
            }
        }
Ejemplo n.º 4
0
        void Handle(Input.Save action)
        {
            if (!CheckPasswordMatch(this.Password, this.ConfirmPassword))
            {
                return;
            }

            if (this.ResetPassword == null)
            {
                this.Message = "Reset token already used";
                return;
            }

            if (this.ResetPassword.Expire < DateTime.UtcNow)
            {
                this.Message = "Reset token expired";
                return;
            }

            if (this.ResetPassword.User == null)
            {
                this.Message = "Failed to get the user"; // TODO: Better message
                return;
            }

            Db.Transact(() =>
            {
                var user = this.ResetPassword.User;

                UserHelper.SetPassword(user, this.Password);
                ResetPassword.Delete();

                if (SystemUser.GetCurrentSystemUser() != user)
                {
                    SystemUser.SignOutSystemUser(user);
                }
            });

            this.RedirectUrl = "/signin/signinuser";
        }
Ejemplo n.º 5
0
        void Handle(Input.UpdateClick action)
        {
            action.Cancel();
            this.Message    = null;
            this.MessageCss = "alert alert-danger";

            if (string.IsNullOrEmpty(this.Email))
            {
                this.Message = "E-mail address is required!";
                return;
            }

            if (!Utils.IsValidEmail(this.Email))
            {
                this.Message = "This is not a valid e-mail address!";
                return;
            }

            Db.Transact(() =>
            {
                SystemUser user    = SystemUser.GetCurrentSystemUser();
                EmailAddress email = Utils.GetUserEmailAddress(user);

                if (email == null)
                {
                    email = new EmailAddress();

                    EmailAddressRelation relation = new EmailAddressRelation()
                    {
                        EmailAddress = email,
                        Somebody     = user.WhoIs as Person
                    };
                }

                email.Name = this.Email;
            });

            this.Message    = "Profile changes has been updated";
            this.MessageCss = "alert alert-success";
        }
Ejemplo n.º 6
0
        void Handle(Input.ChangePasswordClick action)
        {
            action.Cancel();
            this.Message    = null;
            this.MessageCss = "alert alert-danger";

            SystemUser user             = SystemUser.GetCurrentSystemUser();
            bool       validOldPassword = SystemUser.ValidatePasswordHash(
                user.Username, this.OldPassword, user.PasswordSalt, user.Password);

            if (!validOldPassword)
            {
                this.Message = "Invalid old password!";
                return;
            }

            if (string.IsNullOrEmpty(this.NewPassword))
            {
                this.Message = "New password is required!";
                return;
            }

            if (this.NewPassword != this.RepeatPassword)
            {
                this.Message = "Passwords do not match!";
                return;
            }

            string password = SystemUser.GeneratePasswordHash(
                user.Username, this.NewPassword, user.PasswordSalt);

            Db.Transact(() => { user.Password = password; });

            this.Message        = "Your password has been successfully changed";
            this.MessageCss     = "alert alert-success";
            this.OldPassword    = null;
            this.NewPassword    = null;
            this.RepeatPassword = null;
        }
Ejemplo n.º 7
0
        public static bool TryNavigateTo(string url, Request request, out Json returnPage)
        {
            returnPage = null;

            SystemUser systemUser = SystemUser.GetCurrentSystemUser();

            if (systemUser == null)
            {
                // Ask user to sign in.
                returnPage = Self.GET("/signin/partial/accessdenied-form");
                return(false);
            }

            // Check user permission
            if (!CanGetUri(systemUser, url, request))
            {
                // User has no permission, redirect to the Access Denied page
                returnPage = Self.GET("/signin/partial/accessdenied-form");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 8
0
        public void Register()
        {
            Handle.GET("/signin/app-name", () => new AppName());

            Handle.GET("/signin", () => Self.GET("/signin/signinuser"));

            Handle.GET("/signin/user", () =>
            {
                MasterPage master = this.GetMaster();

                if (master.SignInPage != null)
                {
                    return(master.SignInPage);
                }

                Cookie cookie   = CookieHelpers.GetSignInCookie();
                SignInPage page = new SignInPage()
                {
                    Data = null
                };

                Session.Current.Store[nameof(SignInPage)] = page;

                if (cookie != null)
                {
                    SystemUser.SignInSystemUser(cookie.Value);
                    master.RefreshSignInState();
                }

                return(page);
            });

            Handle.GET("/signin/signinuser", HandleSignInForm);
            Handle.GET <string>("/signin/signinuser?{?}", HandleSignInForm);

            Handle.GET("/signin/profile", () =>
            {
                MasterPage master = this.GetMaster();

                master.RequireSignIn = true;
                master.Open("/signin/partial/profile-form");

                return(master);
            });

            Handle.GET("/signin/generateadminuser", (Request request) =>
                       new Response()
            {
                Body = "Create the admin user by going to '/signin/signinuser' and " +
                       "pressing the 'Create Admin' button.",
            }, new HandlerOptions()
            {
                SkipRequestFilters = true
            });

            Handle.GET("/signin/createadminuser", () =>
            {
                MasterPage master = this.GetMaster();

                master.RequireSignIn = false;
                master.Open("/signin/partial/createadminuser");

                return(master);
            });

            Handle.GET("/signin/settings", (Request request) =>
            {
                if (!AuthorizationHelper.TryNavigateTo("/signin/settings", request, out Json page))
                {
                    return(page);
                }

                return(Db.Scope(() =>
                {
                    var settingsPage = new SettingsPage
                    {
                        Html = "/SignIn/views/SettingsPage.html",
                        Uri = request.Uri,
                        Data = MailSettingsHelper.GetSettings()
                    };
                    return settingsPage;
                }));
            });

            // Reset password
            Handle.GET("/signin/user/resetpassword?{?}", (string query, Request request) =>
            {
                NameValueCollection queryCollection = HttpUtility.ParseQueryString(query);
                string token = queryCollection.Get("token");

                MasterPage master = this.GetMaster();

                if (token == null)
                {
                    // TODO:
                    master.Partial = null; // (ushort)System.Net.HttpStatusCode.NotFound;
                    return(master);
                }

                // Retrive the resetPassword instance
                var resetPassword = Db.SQL <ResetPassword>(
                    "SELECT o FROM Simplified.Ring6.ResetPassword o WHERE o.Token=? AND o.Expire>?",
                    token, DateTime.UtcNow).FirstOrDefault();

                if (resetPassword == null)
                {
                    // TODO: Show message "Reset token already used or expired"
                    master.Partial = null; // (ushort)System.Net.HttpStatusCode.NotFound;
                    return(master);
                }

                if (resetPassword.User == null)
                {
                    // TODO: Show message "User deleted"
                    master.Partial = null; // (ushort)System.Net.HttpStatusCode.NotFound;
                    return(master);
                }

                SystemUser systemUser = resetPassword.User;

                var page = new ResetPasswordPage()
                {
                    Html          = "/SignIn/views/ResetPasswordPage.html",
                    Uri           = "/signin/user/resetpassword",
                    ResetPassword = resetPassword,
                    FullName      = systemUser.WhoIs?.FullName ?? systemUser.Username
                                    //Uri = request.Uri // TODO:
                };

                master.Partial = page;

                return(master);
            });

            Handle.GET("/signin/user/authentication/settings/{?}", (string userid, Request request) =>
            {
                if (!AuthorizationHelper.TryNavigateTo("/signin/user/authentication/settings/{?}", request, out Json page))
                {
                    return(new Json());
                }

                // Get system user
                var user = Db.SQL <SystemUser>(
                    "SELECT o FROM Simplified.Ring3.SystemUser o WHERE o.ObjectID = ?", userid)
                           .FirstOrDefault();

                if (user == null)
                {
                    // TODO: Return a "User not found" page
                    return(new Json());
                    //return (ushort)System.Net.HttpStatusCode.NotFound;
                }

                SystemUser systemUser = SystemUser.GetCurrentSystemUser();

                var adminGroup = Db.SQL <SystemUserGroup>(
                    "SELECT o FROM Simplified.Ring3.SystemUserGroup o WHERE o.Name = ?",
                    AuthorizationHelper.AdminGroupName).FirstOrDefault();

                // Check if current user has permission to get this user instance
                if (AuthorizationHelper.IsMemberOfGroup(systemUser, adminGroup))
                {
                    if (user.WhoIs is Person)
                    {
                        page = Db.Scope(() => new SystemUserAuthenticationSettings
                        {
                            Html         = "/SignIn/views/SystemUserAuthenticationSettings.html",
                            Uri          = request.Uri,
                            Data         = user,
                            UserPassword = Self.GET("/signin/user/authentication/password/" + user.GetObjectID())
                        });

                        return(page);
                    }
                }

                return(new Json());
            }, new HandlerOptions {
                SelfOnly = true
            });

            Handle.GET("/signin/user/authentication/password/{?}", (string userid, Request request) =>
            {
                // Get system user
                var user = Db.SQL <SystemUser>(
                    "SELECT o FROM Simplified.Ring3.SystemUser o WHERE o.ObjectID = ?", userid)
                           .FirstOrDefault();

                if (user == null)
                {
                    return(new Json());
                }

                Json page = Db.Scope(() => new SetPasswordPage
                {
                    Html = "/SignIn/views/SetPasswordPage.html",
                    Data = user
                });

                return(page);
            }, new HandlerOptions {
                SelfOnly = true
            });
        }
Ejemplo n.º 9
0
        public void Register()
        {
            Application.Current.Use(new HtmlFromJsonProvider());
            Application.Current.Use(new PartialToStandaloneHtmlProvider());

            //Testing JWT

            /*Handle.GET("/signin/jwt/{?}/{?}", (string Username, string Password) => {
             *  string message;
             *  SystemUserSession session = SignInOut.SignInSystemUser(Username, Password, null, out message);
             *
             *  if (session != null) {
             *      string jwt = JWT.JsonWebToken.Encode(new { Username = Username, Issuer = "Polyjuice.SignIn" }, session.Token.User.Password, JWT.JwtHashAlgorithm.HS256);
             *      Handle.AddOutgoingHeader("x-jwt", jwt);
             *  }
             *
             *  return 200;
             * });*/

            Application.Current.Use((Request req) =>
            {
                Cookie cookie = GetSignInCookie();

                if (cookie != null)
                {
                    if (Session.Current == null)
                    {
                        Session.Current = new Session(SessionOptions.PatchVersioning);
                    }

                    SystemUserSession session = SystemUser.SignInSystemUser(cookie.Value);

                    if (session != null)
                    {
                        RefreshAuthCookie(session);
                    }
                }

                return(null);
            });

            Handle.GET("/signin/user", () =>
            {
                MasterPage master = this.GetMaster();

                if (master.SignInPage != null)
                {
                    return(master.SignInPage);
                }

                Cookie cookie   = GetSignInCookie();
                SignInPage page = new SignInPage()
                {
                    Data = null
                };

                master.SignInPage = page;

                if (cookie != null)
                {
                    SystemUser.SignInSystemUser(cookie.Value);
                    master.RefreshSignInState();
                }

                //Testing JWT

                /*if (Handle.IncomingRequest.HeadersDictionary.ContainsKey("x-jwt")) {
                 *  System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                 *  string jwt = Handle.IncomingRequest.HeadersDictionary["x-jwt"];
                 *  Dictionary<string, string> payload = JWT.JsonWebToken.DecodeToObject<Dictionary<string, string>>(jwt, string.Empty, false);
                 *  string username = payload["Username"];
                 *  SystemUser user = Db.SQL<SystemUser>("SELECT su FROM Simplified.Ring3.SystemUser su WHERE su.Username = ?", username).First;
                 *
                 *  try {
                 *      JWT.JsonWebToken.DecodeToObject<Dictionary<string, string>>(jwt, user.Password, true);
                 *      page.SetAuthorizedState(SignInOut.SignInSystemUser(user));
                 *  } catch (JWT.SignatureVerificationException) {
                 *  }
                 * }*/

                return(page);
            });

            Handle.GET("/signin/partial/signout", HandleSignOut, new HandlerOptions()
            {
                SkipRequestFilters = true
            });

            Handle.GET("/signin/signinuser", HandleSignInForm);
            Handle.GET <string>("/signin/signinuser?{?}", HandleSignInForm);

            Handle.GET("/signin/profile", () =>
            {
                MasterPage master = this.GetMaster();

                master.RequireSignIn = true;
                master.Open("/signin/partial/profile-form");

                return(master);
            });

            Handle.GET("/signin/partial/signin-form", () => new SignInFormPage()
            {
                Data = null
            }, new HandlerOptions()
            {
                SelfOnly = true
            });
            Handle.GET("/signin/partial/alreadyin-form", () => new AlreadyInPage()
            {
                Data = null
            },
                       new HandlerOptions()
            {
                SelfOnly = true
            });
            Handle.GET("/signin/partial/restore-form", () => new RestorePasswordFormPage(),
                       new HandlerOptions()
            {
                SelfOnly = true
            });
            Handle.GET("/signin/partial/profile-form", () => new ProfileFormPage()
            {
                Data = null
            },
                       new HandlerOptions()
            {
                SelfOnly = true
            });
            Handle.GET("/signin/partial/accessdenied-form", () => new AccessDeniedPage(),
                       new HandlerOptions()
            {
                SelfOnly = true
            });

            Handle.GET("/signin/partial/main-form", () => new MainFormPage()
            {
                Data = null
            },
                       new HandlerOptions()
            {
                SelfOnly = true
            });

            Handle.GET("/signin/partial/user/image", () => new UserImagePage());
            Handle.GET("/signin/partial/user/image/{?}", (string objectId) => new Json(),
                       new HandlerOptions {
                SelfOnly = true
            });

            Handle.GET("/signin/generateadminuser", (Request request) =>
            {
                if (Db.SQL("SELECT o FROM Simplified.Ring3.SystemUser o").First != null)
                {
                    Handle.SetOutgoingStatusCode(403);
                    return("Unable to generate admin user: database is not empty!");
                }

                string ip = request.ClientIpAddress.ToString();

                if (ip == "127.0.0.1" || ip == "localhost")
                {
                    SignInOut.AssureAdminSystemUser();

                    return("Default admin user has been successfully generated.");
                }

                Handle.SetOutgoingStatusCode(403);
                return("Access denied.");
            }, new HandlerOptions()
            {
                SkipRequestFilters = true
            });

            Handle.POST("/signin/partial/signin", (Request request) =>
            {
                NameValueCollection values = HttpUtility.ParseQueryString(request.Body);
                string username            = values["username"];
                string password            = values["password"];
                string rememberMe          = values["rememberMe"];

                HandleSignIn(username, password, rememberMe);
                Session.Current.CalculatePatchAndPushOnWebSocket();

                return(200);
            }, new HandlerOptions()
            {
                SkipRequestFilters = true
            });

            Handle.GET("/signin/admin/settings", (Request request) =>
            {
                Json page;
                if (!AuthorizationHelper.TryNavigateTo("/signin/admin/settings", request, out page))
                {
                    return(page);
                }

                return(Db.Scope(() =>
                {
                    var settingsPage = new SettingsPage
                    {
                        Html = "/SignIn/viewmodels/SettingsPage.html",
                        Uri = request.Uri,
                        Data = MailSettingsHelper.GetSettings()
                    };
                    return settingsPage;
                }));
            });

            // Reset password
            Handle.GET("/signin/user/resetpassword?{?}", (string query, Request request) =>
            {
                NameValueCollection queryCollection = HttpUtility.ParseQueryString(query);
                string token = queryCollection.Get("token");

                MasterPage master = this.GetMaster();

                if (token == null)
                {
                    // TODO:
                    master.Partial = null; // (ushort)System.Net.HttpStatusCode.NotFound;
                    return(master);
                }

                // Retrive the resetPassword instance
                ResetPassword resetPassword = Db.SQL <ResetPassword>("SELECT o FROM Simplified.Ring6.ResetPassword o WHERE o.Token=? AND o.Expire>?", token, DateTime.UtcNow).First;

                if (resetPassword == null)
                {
                    // TODO: Show message "Reset token already used or expired"
                    master.Partial = null; // (ushort)System.Net.HttpStatusCode.NotFound;
                    return(master);
                }

                if (resetPassword.User == null)
                {
                    // TODO: Show message "User deleted"
                    master.Partial = null; // (ushort)System.Net.HttpStatusCode.NotFound;
                    return(master);
                }

                SystemUser systemUser = resetPassword.User;

                ResetPasswordPage page = new ResetPasswordPage()
                {
                    Html = "/SignIn/viewmodels/ResetPasswordPage.html",
                    Uri  = "/signin/user/resetpassword"
                           //Uri = request.Uri // TODO:
                };

                page.ResetPassword = resetPassword;

                if (systemUser.WhoIs != null)
                {
                    page.FullName = systemUser.WhoIs.FullName;
                }
                else
                {
                    page.FullName = systemUser.Username;
                }

                master.Partial = page;

                return(master);
            });

            Handle.GET("/signin/user/authentication/settings/{?}", (string userid, Request request) =>
            {
                Json page;
                if (!AuthorizationHelper.TryNavigateTo("/signin/user/authentication/settings/{?}", request, out page))
                {
                    return(new Json());
                }

                // Get system user
                SystemUser user = Db.SQL <SystemUser>("SELECT o FROM Simplified.Ring3.SystemUser o WHERE o.ObjectID = ?", userid).FirstOrDefault();

                if (user == null)
                {
                    // TODO: Return a "User not found" page
                    return(new Json());
                    //return (ushort)System.Net.HttpStatusCode.NotFound;
                }

                SystemUser systemUser      = SystemUser.GetCurrentSystemUser();
                SystemUserGroup adminGroup = Db.SQL <SystemUserGroup>("SELECT o FROM Simplified.Ring3.SystemUserGroup o WHERE o.Name = ?",
                                                                      AuthorizationHelper.AdminGroupName).FirstOrDefault();

                // Check if current user has permission to get this user instance
                if (AuthorizationHelper.IsMemberOfGroup(systemUser, adminGroup))
                {
                    if (user.WhoIs is Person)
                    {
                        page = Db.Scope(() => new SystemUserAuthenticationSettings
                        {
                            Html         = "/SignIn/viewmodels/SystemUserAuthenticationSettings.html",
                            Uri          = request.Uri,
                            Data         = user,
                            UserPassword = Self.GET("/signin/user/authentication/password/" + user.GetObjectID())
                        });

                        return(page);
                    }
                }

                return(new Json());
            }, new HandlerOptions {
                SelfOnly = true
            });

            Handle.GET("/signin/user/authentication/password/{?}", (string userid, Request request) =>
            {
                // Get system user
                SystemUser user = Db.SQL <SystemUser>("SELECT o FROM Simplified.Ring3.SystemUser o WHERE o.ObjectID = ?", userid).FirstOrDefault();

                if (user == null)
                {
                    return(new Json());
                }

                Json page = Db.Scope(() => new SetPasswordPage
                {
                    Html = "/SignIn/viewmodels/SetPasswordPage.html",
                    Data = user
                });

                return(page);
            }, new HandlerOptions {
                SelfOnly = true
            });

            Blender.MapUri("/signin/user", "user");                      //expandable icon; used in Launcher
            Blender.MapUri("/signin/signinuser", "userform");            //inline form; used in RSE Launcher
            Blender.MapUri("/signin/signinuser?{?}", "userform-return"); //inline form; used in UserAdmin
            Blender.MapUri("/signin/admin/settings", "settings");
            Blender.MapUri("/signin/user/authentication/password/{?}", "authentication-password");
            Blender.MapUri("/signin/user/authentication/settings/{?}", "authentication-settings");
            Blender.MapUri("/signin/partial/user/image", "userimage-default");  // default user image
        }