Пример #1
0
    protected void btnedit_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.txtUserName.Value.Trim().Length == 0)
            {
                diverror.InnerHtml = "<div class='diverror'>Xin hãy nhập tài khoản</div>";
                diverror.Visible = true;
                this.txtPassword1.Focus();
                return;
            }
            if (this.txtPassword.Value.Trim().Length == 0)
            {
                diverror.InnerHtml = "<div class='diverror'>Xin hãy nhập mật khẩu</div>";
                diverror.Visible = true;
                this.txtPassword.Focus();
                return;
            }
            if (this.txtPassword1.Value.Trim().Length == 0)
            {
                diverror.InnerHtml = "<div class='diverror'>Xin hãy nhập lại mật khẩu</div>";
                diverror.Visible = true;
                this.txtPassword1.Focus();
                return;
            }
            if (!this.txtPassword1.Value.Trim().Equals(this.txtPassword.Value.Trim()))
            {
                diverror.InnerHtml = "<div class='diverror'>Mật khẩu không khớp</div>";
                diverror.Visible = true;
                this.txtPassword1.Focus();
                return;
            }

            WebUser wu = new WebUser();
            wu.Id = this.id;
            wu.UserName = this.txtUserName.Value.Trim();
            wu.Password = new MD5().Encrypt(this.txtPassword.Value.Trim());
            if (new WebUserFC().CheckExist(wu))
            {
                diverror.InnerHtml = "<div class='diverror'>Tài khoản bạn nhập đã tồn tại</div>";
                diverror.Visible = true;
                this.txtUserName.Focus();
                return;
            }

            if (new WebUserFC().Update(wu))
            {
                diverror.InnerHtml = "<div class='diverror'>Thông tin đã được cập nhật</div>";
                diverror.Visible = true;
                Response.Redirect("AdminWebsite.aspx?menu=UserManage");
            }
        }
        catch (Exception ex)
        {
            diverror.InnerHtml = "<div class='diverror'>" + ex.Message + "</div>";
            diverror.Visible = true;
            this.txtUserName.Focus();
            return;
        }
    }
Пример #2
0
        public ActionResult SWISwapDashboardOrder(string guid1, string guid2)
        {
            WriteDebug("SWISwapDashboardOrder");
            try
            {
                checkSWIAuthentication();

                if (!WebUser.ManageDashboards)
                {
                    throw new Exception("No right to swap  dashboard");
                }

                if (WebUser.Profile.Dashboards.Contains(guid1) && WebUser.Profile.Dashboards.Contains(guid2))
                {
                    var newDashboards = new List <string>();
                    foreach (var guid in WebUser.Profile.Dashboards)
                    {
                        if (guid == guid1)
                        {
                            newDashboards.Add(guid2);
                        }
                        else if (guid == guid2)
                        {
                            newDashboards.Add(guid1);
                        }
                        else
                        {
                            newDashboards.Add(guid);
                        }
                    }
                    WebUser.Profile.Dashboards = newDashboards;
                    WebUser.SaveProfile();
                }
                return(Json(new object { }));
            }
            catch (Exception ex)
            {
                return(HandleSWIException(ex));
            }
        }
Пример #3
0
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (cssFileName.Length == 0)
            {
                Visible = false;
            }

            if (visibleRoles.Length > 0)
            {
                if (!WebUser.IsInRoles(visibleRoles))
                {
                    Visible = false;
                }
            }

            if (visibleUrls.Length > 0)
            {
                bool          match       = false;
                List <string> allowedUrls = visibleUrls.SplitOnChar(',');
                foreach (string u in allowedUrls)
                {
                    //Page.AppRelativeVirtualPath will match for things like blog posts where the friendly url is something like /my-cool-post which
                    //is then mapped to the /Blog/ViewPost.aspx page. So, one could use /Blog/ViewPost.aspx in the AllowedUrls property to render
                    //a css file on blog post pages.
                    if (Page.AppRelativeVirtualPath.ContainsCaseInsensitive(u))
                    {
                        match = true;
                    }

                    //Page.Request.RawUrl is the url used for the request, as in the example above '/my-cool-post'
                    if (Page.Request.RawUrl.ContainsCaseInsensitive(u))
                    {
                        match = true;
                    }
                }
                Visible = match;
            }
        }
Пример #4
0
        private void LoadSettings()
        {
            currentUser = SiteUtils.GetCurrentSiteUser();
            config      = new BlogConfiguration(ModuleSettings.GetModuleSettings(moduleId));

            lnkCategories.NavigateUrl = SiteRoot + "/Blog/EditCategory.aspx?pageid="
                                        + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();

            lnkNewPost.NavigateUrl = SiteRoot + "/Blog/EditPost.aspx?pageid="
                                     + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();

            lnkDrafts.NavigateUrl = SiteRoot + "/Blog/Drafts.aspx?pageid="
                                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();

            lnkClosedPosts.NavigateUrl = SiteRoot + "/Blog/ClosedPosts.aspx?pageid="
                                         + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();

            if (currentUser == null)
            {
                return;
            }

            if (BlogConfiguration.SecurePostsByUser)
            {
                if (WebUser.IsInRoles(config.ApproverRoles))
                {
                    countOfDrafts = Blog.GetCountOfDrafts(moduleId, Guid.Empty);
                }
                else
                {
                    countOfDrafts = Blog.GetCountOfDrafts(moduleId, currentUser.UserGuid);
                }
            }
            else
            {
                countOfDrafts = Blog.GetCountOfDrafts(moduleId, Guid.Empty);
            }

            countOfExpiredPosts = Blog.GetCountClosed(moduleId);
        }
Пример #5
0
        protected override void OnPreRender(System.EventArgs e)
        {
            base.OnPreRender(e);

            if (scriptFileName.Length == 0)
            {
                return;
            }

            if (visibleRoles.Length > 0)
            {
                if (!WebUser.IsInRoles(visibleRoles))
                {
                    return;
                }
            }

            if (visibleUrls.Length > 0)
            {
                bool          match       = false;
                List <string> allowedUrls = visibleRoles.SplitOnChar(',');
                foreach (string u in allowedUrls)
                {
                    if (Page.Request.RawUrl.ContainsCaseInsensitive(u))
                    {
                        match = true;
                    }
                }

                if (!match)
                {
                    return;
                }
            }

            if (!renderInPlace)
            {
                SetupScript();
            }
        }
Пример #6
0
        public static bool updateInfo(ModelView.UserView item)
        {
            db = new ShopOnlineEntities();

            try
            {
                WebUser user1 = db.WebUsers.Find(item.id) as WebUser;
                user1.name     = item.name;
                user1.uAddress = item.uAddress;
                user1.pwd      = item.pwd;
                user1.phone    = item.phone;
                user1.zipcode  = item.zipcode;
                db.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);

                throw ex;
            }
        }
Пример #7
0
 public async Task<ActionResult> VaultLog(WebUser user, string id, int page = 1)
 {
     if (id == null)
     {
         return RedirectToAction("VaultLog");
     }
     var events = (await _logManager.ShowLog(id))?.ToList();
     var logModel = new VaultAccessLogModel()
     {
         Events = events?.Skip((page - 1)*_itemsPerPage)
             .Take(_itemsPerPage)
             .ToList(),
         VaultId = id,
         PagingInfo = new PagingInfo()
         {
             CurrentPage = page,
             ItemsPerPage = _itemsPerPage,
             TotalItems = events.Count()
         }
     };
     return View(logModel);
 }
Пример #8
0
        private bool ShouldRender()
        {
            if (basePage == null)
            {
                return(false);
            }
            if (!Page.Request.IsAuthenticated)
            {
                return(false);
            }
            if (!WebConfigSettings.ShowFileManagerLink)
            {
                return(false);
            }
            if (WebConfigSettings.DisableFileManager)
            {
                return(false);
            }
            if (basePage.SiteInfo == null)
            {
                return(false);
            }

            // only roles that can delete can use file manager
            if (!WebUser.IsInRoles(basePage.SiteInfo.RolesThatCanDeleteFilesInEditor))
            {
                return(false);
            }

            if (
                (WebUser.IsInRoles(basePage.SiteInfo.UserFilesBrowseAndUploadRoles)) ||
                (WebUser.IsInRoles(basePage.SiteInfo.GeneralBrowseAndUploadRoles))
                )
            {
                return(true);
            }

            return(false);
        }
Пример #9
0
        private void Page_Load(object sender, EventArgs e)
        {
            LoadParams();

            if (
                (BasePage == null) ||
                (!BasePage.UserCanViewPage())
                )
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            if (parametersAreInvalid)
            {
                AllowComments        = false;
                this.pnlBlog.Visible = false;
                return;
            }

            LoadSettings();
            SetupCss();
            PopulateLabels();

            if (!IsPostBack && ModuleId > 0 && ItemId > 0)
            {
                if (Context.User.Identity.IsAuthenticated)
                {
                    if (WebUser.HasEditPermissions(BasePage.SiteInfo.SiteId, ModuleId, BasePage.CurrentPage.PageId))
                    {
                        IsEditable = true;
                    }
                }

                PopulateControls();
            }

            BasePage.LoadSideContent(showLeftContent, showRightContent);
        }
        public async Task TransferMoneyIfAccountHasNotEnoughMoney()
        {
            _mockAccountService.Setup(m => m.GetListAsync()).ReturnsAsync(_accounts);
            _mockAccountService.Setup(m => m.GetItemAsync(It.IsAny <int>())).ReturnsAsync(new Account()
            {
                AccountID = 1, UserId = "1", Cash = 5000
            });
            TransferModel tmodel = new TransferModel()
            {
                FromId = 1, ToId = 1, Summ = 1000.ToString()
            };
            WebUser user = new WebUser()
            {
                Id = "1"
            };
            AccountController target = new AccountController(_mockAccountService.Object);

            ActionResult result = await target.TransferMoney(user, tmodel);

            Assert.IsInstanceOfType(result, typeof(PartialViewResult));
            _mockAccountService.Verify(m => m.UpdateAsync(It.IsAny <Account>()), Times.Never);
        }
        /// <summary>
        /// Set the culture for the logged user.
        /// </summary>
        public ActionResult SWISetUserProfile(string culture, string onStartup, string startupReport, string startupReportName)
        {
            writeDebug("SWISetUserProfile");
            try
            {
                checkSWIAuthentication();
                if (!WebUser.DefaultGroup.EditProfile)
                {
                    throw new Exception("Error: no right to change profile");
                }

                if (string.IsNullOrEmpty(culture))
                {
                    throw new Exception("Error: culture must be supplied");
                }
                if (culture != Repository.CultureInfo.EnglishName)
                {
                    if (!Repository.SetCultureInfo(culture))
                    {
                        throw new Exception("Invalid culture name:" + culture);
                    }
                    WebUser.Profile.Culture = culture;
                }
                var onStartupVal = StartupOptions.Default;
                if (Enum.TryParse(onStartup, out onStartupVal))
                {
                    WebUser.Profile.OnStartup         = onStartupVal;
                    WebUser.Profile.StartUpReport     = startupReport;
                    WebUser.Profile.StartupReportName = startupReportName;
                }
                WebUser.SaveProfile();

                return(Json(new { }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(HandleSWIException(ex));
            }
        }
Пример #12
0
        /// <summary>
        /// 用户登陆,此方法是在开发者校验好用户名与密码后执行
        /// </summary>
        /// <param name="userNo">用户名</param>
        /// <param name="SID">安全ID,请参考流程设计器操作手册</param>
        public static void Port_Login(string userNo, string sid)
        {
            if (BP.Sys.SystemConfig.OSDBSrc == OSDBSrc.Database)
            {
                string    sql = "SELECT SID FROM Port_Emp WHERE No='" + userNo + "'";
                DataTable dt  = BP.DA.DBAccess.RunSQLReturnTable(sql);
                if (dt.Rows.Count == 0)
                {
                    throw new Exception("用户不存在或者SID错误。");
                }

                if (dt.Rows[0]["SID"].ToString() != sid)
                {
                    throw new Exception("用户不存在或者SID错误。");
                }
            }

            BP.Port.Emp emp = new BP.Port.Emp(userNo);
            WebUser.SignInOfGener(emp);
            WebUser.IsWap = false;
            return;
        }
Пример #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //This is a first request, so set the cookie
                Guid sessionGuid = new Guid();
                currentUser.SessionId = sessionGuid;

                //Tell the database about the new user
                usersInDatabase.Add(currentUser);

                //Set the cookie
                Response.Cookies.Add(
                    new HttpCookie(
                        "SessionId", sessionGuid.ToString()));
            }
            else
            {
                //The is a postback so we need to get the cookie
                string cookieSession = Request.Cookies.Get(
                    "SessionId").Value.ToString();
                Guid sessionGuid = new Guid(cookieSession);

                // Obtain the user information from the database.
                var returningUser =
                    from u in usersInDatabase
                    where u.SessionId.ToString() == sessionGuid.ToString()
                    select u;

                foreach (var user in returningUser)
                {
                    //Better only be one
                    currentUser = user;
                }

                // Output the cookie value.
                CookieValue.Text = cookieSession;
            }
        }
Пример #14
0
        public override void HandlePost(HttpListenerContext ctx, WebUser user, string postData)
        {
            ChatApiParams p = null;

            if ((p = TryJsonParse <ChatApiParams>(ctx, postData)) == null)
            {
                return;
            }

            ChatSession s = GetSession(ctx);

            if (p.Action.Equals("chat_send"))
            {
                Logger.Log(LogLevel.Verbose, "Processing webchat input: '{0}'", p.Message);
                ProcessInput(p.Message, s);
            }

            mtx.WaitOne();
            WebAdmin.SendHtml(ctx, ToJson(s.Messages));
            s.Messages.Clear();
            mtx.ReleaseMutex();
        }
Пример #15
0
        public static MvcHtmlString GetContent(List <ContentModel> list, EnumContentKey key)
        {
            var content              = list.Key(key);
            var routeData            = HttpContext.Current.Request.RequestContext.RouteData;
            var routeValueDictionary = new RouteValueDictionary(routeData.Values);

            var div = new TagBuilder("div");

            div.Attributes.Add("id", $"text-{(int)key}");
            var user = new WebUser();

            if (routeValueDictionary.ContainsKey("edit"))
            {
                if (routeData.Values["edit"] as string == "edit")// && user.IsAdmin)
                {
                    div.AddCssClass("ckeditor");
                    div.Attributes.Add("contenteditable", "true");
                }
            }
            div.InnerHtml = content;
            return(new MvcHtmlString(div.ToString()));
        }
Пример #16
0
        public WebUser GetUserInfo(string studentRollNo)
        {
            var query = new StringBuilder();

            query.AppendFormat("SELECT WebUserId, WebUserName, WebPassword, Email, AccountStatus, PasswordQuestion, PasswordAnswer, WebUserRole.RoleName, DateOfBirth, StudentId ")
            .AppendFormat(" FROM WebUser, WebUserRole ")
            .AppendFormat(" WHERE StudentId='{0}' AND WebUser.RoleId = WebUserRole.RoleId AND WebUser.AccountStatus='Active'", studentRollNo);

            WebUser webUser = null;

            using (var reader = this.ExecuteReader(CommandType.Text, query.ToString()))
            {
                webUser = GetUserInfo(reader);
            }

            if (webUser != null)
            {
                webUser.VisibleReports = GetRoleRights(webUser.Role);
            }

            return(webUser);
        }
Пример #17
0
        private bool UserCanModerate()
        {
            if (currentPage == null)
            {
                return(false);
            }
            if (module == null)
            {
                return(false);
            }
            if (forum == null)
            {
                return(false);
            }

            if (WebUser.IsAdminOrContentAdmin)
            {
                return(true);
            }
            if (WebUser.IsInRoles(currentPage.EditRoles))
            {
                return(true);
            }
            if (WebUser.IsInRoles(module.AuthorizedEditRoles))
            {
                return(true);
            }
            if (WebUser.IsInRoles(forum.RolesThatCanModerate))
            {
                return(true);
            }
            if (SiteUtils.UserIsSiteEditor())
            {
                return(true);
            }

            log.Info("user can't moderate");
            return(false);
        }
Пример #18
0
        public override void HandlePost(HttpListenerContext ctx, WebUser user, string postData)
        {
            BanApiParams p = null;

            if ((p = TryJsonParse <BanApiParams>(ctx, postData)) == null)
            {
                return;
            }

            switch (p.Action)
            {
            case "bans_update":
                List <PlayerBan> banList = Core.Database.GetBans(p.PlayerNameExp, p.AdminNameExp, p.ReasonExp, p.Expired, p.Type, p.StartDate, 25);
                WebAdmin.SendHtml(ctx, ToJson(banList));
                break;

            case "bans_delete":
                Core.Database.DeleteBan(p.DatabaseId);
                WebAdmin.SendHtml(ctx, ToJson(new BanAdminResponse(true)));
                break;
            }
        }
Пример #19
0
        public ActionResult DeleteConfirmed(int id)
        {
            //select the record for the id passed to delete from WebsiteReviews table
            WebsiteReview websiteReview = db.WebsiteReviews.Find(id);
            //Get the related primary key of Webuser
            var userid = websiteReview.WebUser.UserID;
            //Get the related primary key of Website
            var websiteid = websiteReview.Website.WebsiteID;
            //find record for the selected Primary Keys
            Website website = db.Websites.Find(websiteid);
            WebUser webuser = db.WebUsers.Find(userid);

            //Removing records from respective tables
            db.WebsiteReviews.Remove(websiteReview);
            db.Websites.Remove(website);
            db.WebUsers.Remove(webuser);
            //save the database
            db.SaveChanges();
            //Captures tempdata from server to display operation completed successfully
            TempData["Message"] = "Review was successfully deleted";
            return(RedirectToAction("Index"));
        }
Пример #20
0
        public IActionResult NewUser(string firstName, string lastName, string eMail, string phone, string pass1, string pass2)
        {
            bool match     = false;
            bool validPass = true;

            ViewBag.Match = match;
            ViewBag.Name  = $"{firstName} {lastName}";
            ViewBag.eMail = eMail;
            match         = pass1.Equals(pass2);

            validPass = ValidatePassword(pass1);

            if (!validPass)
            {
                ViewBag.passStatus = "The password did not contain a number";
                return(View("Register"));
            }

            if (!match)
            {
                ViewBag.matchStatus = "The Passwords did not match";
                return(View("Register"));
                //return RedirectToAction("Register", "Home");
                //return Content($"The passwords do not match");
            }

            WebUser newUser = new WebUser
            {
                Name  = $"{firstName} {lastName}",
                Email = eMail,
                Phone = phone,
                Pass  = pass1,
                ID    = WebUser.Users.Count
            };

            WebUser.Users.Add(newUser);

            return(View(newUser));
        }
Пример #21
0
        /// <summary>
        /// Performs login action onto server
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        protected bool Login(string UserName, string Password)
        {
            CurrentUser = AuthUtil.Instance.Authenticate(UserName, Password);

            if (CurrentUser != null)
            {
                string returnUrl = Request.Params[AppConstants.UrlParams.RETURN_URL];
                if (string.IsNullOrEmpty(returnUrl))
                {
                    returnUrl = UriUtil.GetAbsolutePathForRelativePath(DefaultUrl);
                }
                else
                {
                    returnUrl = UriUtil.RemoveParameter(returnUrl, AppConstants.UrlParams.ACTION);
                }
                string ssoSiteUrl = string.Format(SSOSiteUrlConfig, HttpUtility.UrlEncode(returnUrl));

                Response.Redirect(string.Format("{0}&{1}={2}", ssoSiteUrl, AppConstants.UrlParams.TOKEN, CurrentUser.Token));
            }

            return(false);
        }
Пример #22
0
        private bool RedirectIfNeeded()
        {
            if (
                (!isAdmin) &&
                (!isSiteEditor) &&
                (!WebUser.IsInRoles(CurrentPage.AuthorizedRoles))
                )
            {
                if (!Request.IsAuthenticated)
                {
                    SiteUtils.RedirectToLoginPage(this, SiteUtils.GetCurrentPageUrl());
                    return(true);
                }
                else
                {
                    SiteUtils.RedirectToAccessDeniedPage(this);
                    return(true);
                }
            }

            return(false);
        }
Пример #23
0
        public void SendPrivateMessage(string toUserName, string msg)
        {
            try
            {
                string fromconnectionid = Context.ConnectionId;
                var    toUser           = ConnectedUsers.FirstOrDefault(x => x.UserName == toUserName);
                string fromUserName     = Toolkit.GetCurrentWebUserName();

                WebUser me  = _users.GetFirstOrDefault(x => x.UserName == fromUserName);
                WebUser you = _users.GetFirstOrDefault(x => x.UserName == toUserName);

                // if the person we talk to is online, Send message and save to database
                if (toUser != null)
                {
                    Clients.Client(toUser.ConnectionId).sendPrivateMessage(fromUserName, msg, DateTime.Now.ToShortTimeString(), me.Avatar); // karşı tarafa gönder
                    Clients.Caller.addMessage(fromUserName, msg, DateTime.Now.ToShortTimeString(), me.Avatar);                              // kendine gönder

                    Message newMessage = new Message();
                    newMessage.MessageDate = DateTime.Now;
                    newMessage.MessageText = msg;
                    newMessage.Receiver_Id = you.Id;
                    newMessage.WebUser_Id  = me.Id;
                    _messages.InsertOrUpdate(newMessage);
                }
                // if the person we talk to is offline, save to database
                else
                {
                    Clients.Caller.addMessage(fromUserName, msg, DateTime.Now.ToShortTimeString(), me.Avatar); // kendine gönder

                    Message newMessage = new Message();
                    newMessage.MessageDate = DateTime.Now;
                    newMessage.MessageText = msg;
                    newMessage.Receiver_Id = you.Id;
                    newMessage.WebUser_Id  = me.Id;
                    _messages.InsertOrUpdate(newMessage);
                }
            }
            catch { }
        }
Пример #24
0
    private void Login()
    {
        string user = txtUserName.Text.Trim();
        string pass = txtPassword.Text.Trim();

        try
        {
            //关闭已登录用户
            if (WebUser.No != null)
            {
                WebUser.Exit();
            }

            Emp em = new Emp(user);
            if (em.CheckPass(pass))
            {
                WebUser.SignInOfGenerLang(em, WebUser.SysLang);

                if (this.Request.RawUrl.ToLower().Contains("wap"))
                {
                    WebUser.IsWap = true;
                }
                else
                {
                    WebUser.IsWap = false;
                }

                WebUser.Token = this.Session.SessionID;

                Response.Redirect("Default.aspx", false);
                return;
            }
            this.Alert("用户名密码错误,注意密码区分大小写,请检查是否按下了CapsLock.。");
        }
        catch (System.Exception ex)
        {
            this.Alert("@用户名密码错误!@检查是否按下了CapsLock.@更详细的信息:" + ex.Message);
        }
    }
Пример #25
0
 public bool CollegaUtenteNormale(DataAccess WebConn, WebUser WU, FlowChartUser FCU)
 {
     if (WU.login.ToString() == "")
     {
         MessageBox.Show(this, "Impossibile aggiungere un utente senza login", "Errore");
         return(false);
     }
     //Aggiunge l'utente al dipartimento e
     if (!AggiungiUtente(WU.login.ToString()))
     {
         return(false);                                      //per gli utenti normali login= idcustomuser
     }
     if (FCU.flowchartcode != DBNull.Value)
     {
         if (!AggiungiUtenteAdOrganigramma(FCU))
         {
             return(false);
         }
         return(AddVirtualUser(WebConn, WU));
     }
     return(true); //se non c'è una voce di organigramma lo aggiunge come utente normale punto e basta
 }
Пример #26
0
        public async Task <ActionResult> Add(WebUser user, Category category)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await _categoryService.CreateAsync(category);

                    await _planningHelper.CreatePlanItemsForCategory(user, category.CategoryID);
                }
                catch (ServiceException e)
                {
                    throw new WebUiException($"Ошибка в контроллере {nameof(CategoryController)} в методе {nameof(Add)}", e);
                }

                return(RedirectToAction("GetCategoriesAndPages"));
            }

            ViewBag.TypesOfFlow = await GetTypesOfFlow();

            return(PartialView(category));
        }
Пример #27
0
        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            ISession s = this.Session["User?Session"] as ISession;

            using (ITransaction t = s.BeginTransaction())
            {
                WebUser user = new WebUser();
                user.Username     = txtUsername.Text;
                user.EmailAddress = txtEmailAddress.Text;
                user.UserID       = Guid.NewGuid();
                user.IsActive     = true;
                //user.CreatedBy = this.CurrentUser.UserID;
                //user.CreatedOn = DateTime.UtcNow;

                string hash = Hashing.GetMd5Hash(txtPassword.Text, "sadf");

                user.PasswordHash = hash;

                s.Save(user);
                t.Commit();
            }
        }
Пример #28
0
        public IHttpActionResult Put(WebUser user)
        {
            try
            {
                BizUser bizUser  = user.WebUserToBizUser();
                string  response = userFunctions.BizUpdateUserPassWord(bizUser);

                if (!response.Equals("EXITO"))
                {
                    return(BadRequest(response));
                }
                else
                {
                    return(Ok(response));
                }
            }

            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Пример #29
0
        public IHttpActionResult Post(WebUser user)
        {
            try
            {
                BizUser bizUser      = user.WebUserToBizUser();
                WebUser userResponse = userFunctions.BizFuncLogin(bizUser.Email, bizUser.PassWord).BizUserToWebUser();

                if (userResponse == null)
                {
                    return(Unauthorized());
                }
                else
                {
                    return(Ok(userResponse));
                }
            }

            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
Пример #30
0
        public List <WebUser> GetAll()
        {
            var webUsers = new List <WebUser>();

            using (var con = new SqlConnection(conStr))
            {
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "SELECT * FROM dbo.WebUsers";
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    var webUser = new WebUser();
                    webUser.Id       = (int)reader["id"];
                    webUser.Name     = (string)reader["userName"];
                    webUser.Password = (byte[])reader["hash"];
                    webUser.Role     = (int)reader["role"];
                    webUsers.Add(webUser);
                }
            }
            return(webUsers);
        }
Пример #31
0
        public override void HandlePost(HttpListenerContext ctx, WebUser user, string postData)
        {
            GameSettingsApiParams p = null;

            if ((p = TryJsonParse <GameSettingsApiParams>(ctx, postData)) == null)
            {
                return;
            }

            switch (p.Action)
            {
            case "game_get":
                ServerSettings s = Core.Server.Settings;
                WebServer.LogAudit(user, "modified game settings");

                //TODO hacky way to pass "floats using ints"
                int st = s.AutoAnnouncePeriod;
                s.AutoAnnouncePeriod = (int)Util.I2f(s.AutoAnnouncePeriod);
                WebAdmin.SendHtml(ctx, ToJson(new GameSettingsResponse(s)));
                s.AutoAnnouncePeriod = st;

                break;

            case "game_set":
                //NOTE: hacky way of passing spawnvalue
                p.Settings.AutoAnnouncePeriod = Util.F2i(p.Settings.AutoAnnouncePeriod);
                Core.Server.Settings.UpdateFrom(p.Settings, ConfigSection.GAME);
                try
                {
                    Core.Server.Settings.WriteToFile(Core);
                    WebAdmin.SendHtml(ctx, ToJson(new GameSettingsSaveResponse()));
                }
                catch (Exception e)
                {
                    WebAdmin.SendHtml(ctx, ToJson(new GameSettingsSaveResponse(e)));
                }
                break;
            }
        }
Пример #32
0
 public ActionResult Register(WebUser model)
 {
     UserDetails user = new UserDetails
     {
         UserID = 0,
         RoleID = (int)UserRoles.User,
         RegisterVia = (int)RegisterVia.Website,
         RegistrationIP = Request.UserHostAddress,
         Email = model.Email,
         Password = Utility.GetEncryptedValue(model.Password),
         ResetPassword = false,
         PasswordResetCode = null,
         FullName = model.FullName,
         DisplayName = model.DisplayName,
         ProfilePicture = string.IsNullOrEmpty(model.ProfilePicture) ? Constants.DefaultUserPic : model.ProfilePicture,
         CountryID = model.CountryID,
         StateID = model.StateID,
         OtherState = model.OtherState,
         City = model.City,
         OtherCity = model.OtherCity,
         ZipCode = model.ZipCode,
         FailedLoginAttempts = 0,
         CreatedOn = DateTime.Now,
     };
     ActionOutput<UserDetails> Result = _homeManager.SaveOrUpdateUser(user);
     //if (model.ProfilePicture != null && model.ProfilePicture != Constants.DefaultUserPic)
     //{
     //    // Move file from temp to actual folder
     //    if (!System.IO.Directory.Exists(HostingEnvironment.MapPath(Config.UserImages + LOGGEDIN_USER.UserID)))
     //        System.IO.Directory.CreateDirectory(HostingEnvironment.MapPath(Config.UserImages + LOGGEDIN_USER.UserID));
     //    System.IO.File.Move(HostingEnvironment.MapPath("~/Temp/" + model.ProfilePicture), HostingEnvironment.MapPath(Config.UserImages + LOGGEDIN_USER.UserID + "/" + model.ProfilePicture));
     //}
     //if (model.Subscribe && Result.Status == ActionStatus.Successfull)
     //    _userManager.Subscribe(model.Email, (int)SubscriptionStatus.Subscribe, Result.Object.UserID);
     return Json(Result, JsonRequestBehavior.AllowGet);
 }
Пример #33
0
 public static Customer GetCustomerById(int customerId)
 {
     WebUser customer = new WebUser(customerId);
     return customer.Instance;
 }
Пример #34
0
        // POST: odata/WebUsers
        public IHttpActionResult Post( WebUser webUser )
        {
            if ( !ModelState.IsValid ) {
                return BadRequest( ModelState );
            }

            db.WebUserSet.Add( webUser );
            db.SaveChanges();

            return Created( webUser );
        }
        public AuthenticationResult Authenticate(HttpRequestBase request)
        {
            var encryptedAuthCookie = request.Cookies[authCookieName];

            if (encryptedAuthCookie == null)
                return new AuthenticationResult(WebUser.UnauthenticatedUser, AuthFailure.Unauthenticated);

            try
            {
                var encryptedCookieValue = Convert.FromBase64String(encryptedAuthCookie.Values["enc"]);
                var encryptedCookieSignature = Convert.FromBase64String(encryptedAuthCookie.Values["sig"]);

                var expectedSignature = Sign(encryptedCookieValue);
                if (!encryptedCookieSignature.ContentEquals(expectedSignature))
                    return new AuthenticationResult(WebUser.UnauthenticatedUser, AuthFailure.BadAuthData);

                var authCookieValue = Encoding.ASCII.GetString(Decrypt(encryptedCookieValue));
                var authCookie = new HttpCookie(authCookieName, authCookieValue);
                var user = new WebUser(Int64.Parse(authCookie["id"]), authCookie["name"]);
                return new AuthenticationResult(user);
            }
            catch (ArgumentNullException) { }
            catch (ArgumentException) { }
            catch (FormatException) { }
            catch (CryptographicException) {}

            return new AuthenticationResult(WebUser.UnauthenticatedUser, AuthFailure.BadAuthData);
        }