示例#1
0
文件: Login.cs 项目: es-dev/cantieri
 private void LoginApplication()
 {
     try
     {
         var username = editUsername.Text;
         var password = editPassword.Text;
         
         var account = new AccountDto(); 
         account.Username = username;
         account.Password = password;
         var viewModel = new AccountViewModel();
         var accountAuthenticated = viewModel.Authenticate(account);
         if (accountAuthenticated!=null)
         {
             SessionManager.Login(Context, accountAuthenticated);
             Context.Redirect("cantieri-homepage.aspx");
         }
         else
         {
             lblLoginFault.Visible = true;
         }
     }
     catch (Exception ex)
     {
         UtilityError.Write(ex);
     }
     
 }
 public ActionResult Index()
 {
     if (Session["loggedin"] != null && isloggedin == false)
     {
         var email = HttpContext.Request.Cookies["Bank"]["Email"];
         Account user = db.Accounts.Find(email);
         var currentuser = new AccountViewModel()
         {
             Email = user.Email,
             Name = user.Name,
             Password = user.Password,
             checkingBal = System.Convert.ToDouble(user.CheckingBalance),
             savingsBal = System.Convert.ToDouble(user.SavingsBalance)
         };
         isloggedin = true;
         return View(currentuser);
     }
     else if (Session["loggedin"] != null && isloggedin == true)
     {
         return View();
     }
     else
     {
         return View();
     }
 }
示例#3
0
 public ActionResult Account()
 {
     var model = new AccountViewModel();
     model.CurrentUser = _userContext.CurrentUser;
     if (model.CurrentUser != null)
         model.NumberOfUnreadMessages = _messageDao.GetNumberOfUnreadMessagesForUser(model.CurrentUser.Id);
     return PartialView(model);
 }
示例#4
0
 public override void Init()
 {
     try
     {
         ViewModel = new AccountViewModel();
     }
     catch (Exception ex)
     {
         UtilityError.Write(ex);
     }
 }
示例#5
0
        /// <summary>
        /// Возвращает модель представления для представления Accounts контроллера Management
        /// </summary>
        public static AccountViewModel GetAccountViewModel(List<AccountTag> accounts)
        {
            var listFilterGroups = Utils.SelectAllValuesFromTable<ACCOUNT_GROUP>(x => new SelectListItem{ Text = x.Code, Value = x.Code });
            listFilterGroups.Insert(0, new SelectListItem { Text = "", Value = "" }); // для фильтра добавляем пустой элемент для поля "сбросить фильтр" в выпадающим списке

            var listFilterCurrency = Utils.SelectAllValuesFromTable<COMMODITY>(x => new SelectListItem{ Text = x.Title, Value = x.Title });
            listFilterCurrency.Insert(0, new SelectListItem { Text = "", Value = "" }); // для фильтра добавляем пустой элемент для поля "сбросить фильтр" в выпадающим списке

            var viewModel = new AccountViewModel
            {
                CurrentPageItems = new PagedList<AccountTag>(accounts, 0, 10),
                SortColName = new List<KeyValuePair<string, int>> { new KeyValuePair<string, int>("SortId", 1 ) },
                StrSortColName = "SortId:1",
                FilterGroups = listFilterGroups,           //для выпадающего списка фильра
                FilterBalanceTickers = listFilterCurrency //для выпадающего списка фильра
            };
            return viewModel;
        }
示例#6
0
        public async Task<ActionResult> Login(AccountViewModel.LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindAsync(model.Login, model.Password);
                if (user != null)
                {
                    await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, false);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");

                }
            }
            return View(model);
        }
示例#7
0
        public async Task<ActionResult> Register(AccountViewModel.RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Login, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    return RedirectToAction("Index", "Home");
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);

        }
 private void OnNavigation(string destination)
 {
     switch (destination)
     {
         case "home":
             CurrentViewModel = new HomeViewModel();
             break;
         case "pvp":
             CurrentViewModel = new PvPViewModel();
             break;
         case "world":
             CurrentViewModel = new WorldViewModel();
             break;
         case "store":
             CurrentViewModel = new StoreViewModel();
             break;
         case "account":
             CurrentViewModel = new AccountViewModel();
             break;
         default:
             throw new ArgumentException($"Failed to navigate to '{destination}', the destination was not recognized");
     }
 }
示例#9
0
        public ActionResult Login(AccountViewModel.Login model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            if (ModelState.IsValid)
            {

                var user =  UserManager.Find(model.UserName, model.Password);
                if (user != null)
                {
                    HttpRequestExt.SetLogin(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("Password", "用户名或密码错误");
                }
            }
            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
示例#10
0
        public ActionResult Login(string returnUrl, string message, string modelMessage)
        {
            Logger.Current.Informational("In Login returnUrl " + returnUrl + ", message:" + message);
            if (Request.IsAuthenticated)
            {
                GetAccountAuthorizationRequest request = new GetAccountAuthorizationRequest();
                request.name = DomainName;
                GetAccountAuthorizationResponse response = accountService.GetAccountByDomainUrl(request);
                if (response.Exception != null)
                {
                    ExceptionHandler.Current.HandleException(response.Exception, DefaultExceptionPolicies.LOG_ONLY_POLICY);
                    ModelState.AddModelError("", "[|Invalid Account.|]");
                    return(View());
                }
                cachingService.AddAccountPermissions(response.AccountId);
                cachingService.AddUserPermissions(response.AccountId);
                return(RedirectToLocal("", Thread.CurrentPrincipal.Identity.ToRoleID(), Thread.CurrentPrincipal.Identity.ToAccountID(), "", ""));
            }
            if (!String.IsNullOrEmpty(modelMessage))
            {
                ModelState.AddModelError("", modelMessage);
            }
            var defaultHelpURL = ConfigurationManager.AppSettings["helpURL"].ToString();

            ViewBag.SecurityMessage = message;
            if (!string.IsNullOrEmpty(returnUrl) && returnUrl.ToLower().Contains("logoff"))
            {
                returnUrl = null;
            }
            Logger.Current.Verbose("Request for login using domainurl:" + DomainName);
            ViewBag.Page = "Login";
            string loginPage = "Login";
            string masterUrl = DomainName;

            if (!string.IsNullOrWhiteSpace(DomainName))
            {
                GetAccountAuthorizationRequest request = new GetAccountAuthorizationRequest();
                request.name = DomainName;
                var accountID = default(int);
                GetAccountAuthorizationResponse response  = accountService.GetAccountByDomainUrl(request);
                GetSubscriptionSettingsRequest  ssRequest = new GetSubscriptionSettingsRequest();
                if (response != null)
                {
                    ssRequest.SubscriptionId = response.SubscriptionId;
                }
                GetSubscriptionSettingsResponse ssResponse = accountService.GetSubscriptionSettings(ssRequest);
                masterUrl = ssResponse.SubscriptionSettings.Where(p => p.SubscriptionSettingType == SubscriptionSettingTypes.Master).Select(p => p.Value).FirstOrDefault();
                if (masterUrl != null && masterUrl != DomainName)
                {
                    return(Redirect("https://" + masterUrl + "/Login/?modelMessage=" + modelMessage));
                }
                loginPage         = ssResponse.SubscriptionSettings.Where(p => p.SubscriptionSettingType == SubscriptionSettingTypes.Login).Select(p => p.Value).FirstOrDefault();
                ViewBag.LoginUrl  = masterUrl == null ? DomainName : masterUrl;
                ViewBag.LoginPage = loginPage;
                if (response.Exception != null)
                {
                    ExceptionHandler.Current.HandleException(response.Exception, DefaultExceptionPolicies.LOG_ONLY_POLICY);
                    ModelState.AddModelError("", "[|Invalid Account.|]");
                    return(View());
                }
                if (response != null)
                {
                    cachingService.AddAccountPermissions(response.AccountId);
                    Logger.Current.Informational("AccountId :" + response.AccountId);
                    Logger.Current.Informational("Account Name :" + response.AccountName);
                    accountID = response.AccountId;
                    this.Response.Cookies.Add(new HttpCookie("helpURL", !string.IsNullOrEmpty(response.HelpURL) ? response.HelpURL : defaultHelpURL));
                }
                LoginViewModel loginViewModel = new LoginViewModel();
                loginViewModel.AccountId = accountID;
                if (response.SubscriptionId == (int)AccountSubscription.Standard || response.SubscriptionId == (int)AccountSubscription.STAdmin)
                {
                    loginViewModel.AccountName = response.AccountName;
                }
                if (returnUrl != null)
                {
                    ViewBag.ReturnUrl = returnUrl;
                }
                ViewBag.AccountID   = accountID;
                ViewBag.AccountName = response.AccountName;
                if (response.Status == 3)
                {
                    AccountViewModel account = cachingService.GetAccount(accountID);
                    ViewBag.AccountName   = account.AccountName;
                    ViewBag.ImageSrc      = account.Image == null ? "" : account.Image.ImageContent;
                    ViewBag.StatusMessage = account.StatusMessage;
                    return(View("~/Views/Error/Suspended.cshtml"));
                }
                else if (response.Status == 5)
                {
                    AccountViewModel account = cachingService.GetAccount(accountID);
                    ViewBag.AccountName   = account.AccountName;
                    ViewBag.ImageSrc      = account.Image == null ? "" : account.Image.ImageContent;
                    ViewBag.StatusMessage = account.StatusMessage;
                    return(View("~/Views/Error/Maintenance.cshtml"));
                }
                return(View(loginPage, loginViewModel));
            }
            else
            {
                return(View(loginPage));
            }
        }
示例#11
0
        public async Task UpdateSecondaryLiveTiles()
        {
            var tiles = await SecondaryTile.FindAllForPackageAsync();

            List <string> displaycontent = new List <string>();

            displaycontent = await GetPaymentsAsync(TileSizeOptions.Large, PaymentInformation.Previous)
                             .ConfigureAwait(false);

            if (tiles == null)
            {
                return;
            }

            foreach (SecondaryTile item in tiles)
            {
                AccountViewModel acct = await crudService.ReadSingleAsync <AccountViewModel>(item.TileId)
                                        .ConfigureAwait(false);

                TileContent content = new TileContent {
                    Visual = new TileVisual {
                        TileSmall = new TileBinding {
                            Content = new TileBindingContentAdaptive {
                                Children =
                                {
                                    new AdaptiveGroup                {
                                        Children =
                                        {
                                            new AdaptiveSubgroup     {
                                                Children =
                                                {
                                                    new AdaptiveText {
                                                        Text      = acct.Name,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text      = LiveTileHelper.TruncateNumber(acct.CurrentBalance),
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        TileMedium = new TileBinding {
                            Content = new TileBindingContentAdaptive {
                                Children =
                                {
                                    new AdaptiveGroup                {
                                        Children =
                                        {
                                            new AdaptiveSubgroup     {
                                                Children =
                                                {
                                                    new AdaptiveText {
                                                        Text      = acct.Name,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileAccountBalance,
                                                                             acct.CurrentBalance.ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = Strings.ExpenseLabel,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileLastMonthsExpenses,
                                                                             DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(
                                                                                 DateTime.Now.AddMonths(-1).Month),
                                                                             LiveTileHelper.TruncateNumber(
                                                                                 GetMonthExpenses(
                                                                                     DateTime.Now.AddMonths(-1).Month, DateTime.Now.Year,
                                                                                     acct))),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileCurrentMonthsExpenses,
                                                                             DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(
                                                                                 DateTime.Now.Month),
                                                                             LiveTileHelper.TruncateNumber(
                                                                                 GetMonthExpenses(
                                                                                     DateTime.Now.Month, DateTime.Now.Year, acct))),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        TileWide = new TileBinding {
                            Content = new TileBindingContentAdaptive {
                                Children =
                                {
                                    new AdaptiveGroup                {
                                        Children =
                                        {
                                            new AdaptiveSubgroup     {
                                                Children =
                                                {
                                                    new AdaptiveText {
                                                        Text      = acct.Name,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileAccountBalance,
                                                                             acct.CurrentBalance.ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = Strings.ExpenseLabel,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileLastMonthsExpenses,
                                                                             DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(
                                                                                 DateTime.Now.AddMonths(-1).Month),
                                                                             GetMonthExpenses(
                                                                                 DateTime.Now.AddMonths(-1).Month, DateTime.Now.Year,
                                                                                 acct).ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileCurrentMonthsExpenses,
                                                                             DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(
                                                                                 DateTime.Now.Month),
                                                                             GetMonthExpenses(
                                                                                 DateTime.Now.Month, DateTime.Now.Year, acct)
                                                                             .ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        TileLarge = new TileBinding {
                            Content = new TileBindingContentAdaptive {
                                Children =
                                {
                                    new AdaptiveGroup                {
                                        Children =
                                        {
                                            new AdaptiveSubgroup     {
                                                Children =
                                                {
                                                    new AdaptiveText {
                                                        Text      = acct.Name,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileAccountBalance,
                                                                             acct.CurrentBalance.ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = Strings.ExpenseLabel,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileLastMonthsExpenses,
                                                                             DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(
                                                                                 DateTime.Now.AddMonths(-1).Month),
                                                                             GetMonthExpenses(
                                                                                 DateTime.Now.AddMonths(-1).Month, DateTime.Now.Year,
                                                                                 acct).ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text = string.Format(CultureInfo.InvariantCulture,
                                                                             Strings.LiveTileCurrentMonthsExpenses,
                                                                             DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(
                                                                                 DateTime.Now.Month),
                                                                             GetMonthExpenses(
                                                                                 DateTime.Now.Month, DateTime.Now.Year, acct)
                                                                             .ToString("C2", CultureInfo.InvariantCulture)),
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = Strings.LiveTilePastPayments,
                                                        HintStyle = AdaptiveTextStyle.Caption
                                                    },
                                                    new AdaptiveText {
                                                        Text      = displaycontent[0],
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = displaycontent[1],
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = displaycontent[2],
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = displaycontent[3],
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = displaycontent[4],
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    },
                                                    new AdaptiveText {
                                                        Text      = displaycontent[5],
                                                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                };

                TileNotification tn = new TileNotification(content.GetXml());
                TileUpdateManager.CreateTileUpdaterForSecondaryTile(item.TileId).Update(tn);
            }
        }
示例#12
0
        public List <AccountViewModel> GetAccountViewModels(
            string name, int?level,
            out int totalSize, int currentPage = 1, int pageSize = 10)
        {
            //----- Process filter conditions -----
            List <string> conditions = new List <string>();

            if (!string.IsNullOrEmpty(name))
            {
                conditions.Add(" AccountInfos.Name LIKE '%' + @name + '%'");
            }

            if (level.HasValue)
            {
                conditions.Add(" UserLevel = @level");
            }

            string filterConditions =
                (conditions.Count > 0)
                    ? (" WHERE " + string.Join(" AND ", conditions))
                    : string.Empty;
            //----- Process filter conditions -----


            string query =
                $@" 
                    SELECT TOP {pageSize} * FROM
                    (
                        SELECT 
                            ROW_NUMBER() OVER(ORDER BY Accounts.ID) AS RowNumber,
                            Accounts.ID,
                            Accounts.Name AS Account,
                            Accounts.UserLevel,
                            AccountInfos.Name,
                            AccountInfos.Title
                        FROM Accounts
                        JOIN AccountInfos
                        ON Accounts.ID = AccountInfos.ID
                        {filterConditions}
                    ) AS TempT
                    WHERE RowNumber > {pageSize * (currentPage - 1)}
                    ORDER BY ID
                ";

            string countQuery =
                $@" SELECT 
                        COUNT(Accounts.ID)
                    FROM Accounts
                    JOIN AccountInfos
                    ON Accounts.ID = AccountInfos.ID
                    {filterConditions}
                ";

            List <SqlParameter> dbParameters = new List <SqlParameter>();

            if (!string.IsNullOrEmpty(name))
            {
                dbParameters.Add(new SqlParameter("@name", name));
            }

            if (level.HasValue)
            {
                dbParameters.Add(new SqlParameter("@level", level.Value));
            }


            var dt = this.GetDataTable(query, dbParameters);

            List <AccountViewModel> list = new List <AccountViewModel>();

            foreach (DataRow dr in dt.Rows)
            {
                AccountViewModel model = new AccountViewModel();
                model.ID        = (Guid)dr["ID"];
                model.Name      = (string)dr["Name"];
                model.Title     = (string)dr["Title"];
                model.Account   = (string)dr["Account"];
                model.UserLevel = (int)dr["UserLevel"];

                list.Add(model);
            }


            // 算總數並回傳
            int?totalSize2 = this.GetScale(countQuery, dbParameters) as int?;

            totalSize = (totalSize2.HasValue) ? totalSize2.Value : 0;

            return(list);
        }
        public async Task account_add_update_delete_async()
        {
            var client = fixture.Client;

            if (String.IsNullOrEmpty(TokenTest.TokenValue))
            {
                await TokenTest.token_get(client);
            }

            //insert
            AccountViewModel vmentity = new AccountViewModel
            {
                Name        = "Account 1",
                Email       = "*****@*****.**",
                Description = "desc",
                IsTrial     = false,
                IsActive    = true,
                SetActive   = DateTime.Now
            };

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenTest.TokenValue);
            var response = await client.PostAsync("/api/accountasync", new StringContent(
                                                      JsonConvert.SerializeObject(vmentity), Encoding.UTF8, "application/json"));

            response.EnsureSuccessStatusCode();
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            var lastAddedId = await response.Content.ReadAsStringAsync();

            Assert.True(int.Parse(lastAddedId) > 1);
            int id = 0; int.TryParse(lastAddedId, out id);

            //get inserted
            var util = new Utility();

            vmentity = await util.GetAccount(client, id);

            //update test
            vmentity.Description = "desc updated";
            response             = await client.PutAsync("/api/accountasync/" + id.ToString(), new StringContent(JsonConvert.SerializeObject(vmentity), Encoding.UTF8, "application/json"));

            response.EnsureSuccessStatusCode();
            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

            //confirm update
            response = await client.GetAsync("/api/accountasync/" + id.ToString());

            response.EnsureSuccessStatusCode();
            var jsonString = await response.Content.ReadAsStringAsync();

            var oj   = JObject.Parse(jsonString);
            var desc = oj["description"].ToString();

            Assert.Equal(desc, vmentity.Description);

            //another update with same account - concurrency
            vmentity.Description = "desc updated 2";
            response             = await client.PutAsync("/api/accountasync/" + id.ToString(), new StringContent(JsonConvert.SerializeObject(vmentity), Encoding.UTF8, "application/json"));

            Assert.Equal(HttpStatusCode.PreconditionFailed, response.StatusCode);

            //delete test
            response = await client.DeleteAsync("/api/accountasync/" + id.ToString());

            response.EnsureSuccessStatusCode();
            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
        }
 //Make yourself some handy extension methods for syntactic sugar
 public static Account ConvertFromViewModel(this AccountViewModel x)
 {
     return(Mapper.Map <AccountViewModel, Account>(x));
 }
示例#15
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //获取当前域名
            string      host     = filterContext.HttpContext.Request.Url.Host;
            long        tenantId = 0;
            TenantModel tenant   = tenantBLL.GetAllModelList().Find(o => o.TenantDomain.ToLower() == host.ToLower());

            if (tenant != null)
            {
                tenantId = tenant.ID;
                //CacheHelper.SetCookie("tenantId", "tenantId");
            }

            //获取当前控制器信息
            string controllername = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            string actionname     = filterContext.ActionDescriptor.ActionName.ToLower();
            string allowActions   = string.Empty;


            if (!filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
            {
                //未登录的时候,此处加了一个判断,判断同步请求还是一部请求
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    //异步请求,返回JSON数据
                    filterContext.Result = new JsonResult
                    {
                        Data = new
                        {
                            Status  = -1,
                            Message = "登录已过期,请刷新页面后操作!"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    //非异步请求,则跳转登录页
                    FormsAuthentication.RedirectToLoginPage();//重定向会登录页
                }
            }
            else
            {
                //1.登录状态获取用户信息(自定义保存的用户)
                var cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

                //2.使用 FormsAuthentication 解密用户凭据
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                AccountViewModel loginUser = new AccountViewModel();

                //3. 直接解析到用户模型里去,有没有很神奇
                loginUser = new JavaScriptSerializer().Deserialize <AccountViewModel>(ticket.UserData);

                //4. 将要使用的数据放到ViewData 里,方便页面使用
                filterContext.Controller.ViewData["UserName"] = loginUser.AccountName;
                //filterContext.Controller.ViewData["Portrait"] = loginUser.Portrait;
                filterContext.Controller.ViewData["UserID"] = loginUser.ID;

                //var actionParameters = filterContext.ActionDescriptor.GetParameters();
                //foreach (var p in actionParameters)
                //{
                //    if (p.ParameterType == typeof(string))
                //    {
                //        if (filterContext.ActionParameters[p.ParameterName] != null)
                //        {
                //            filterContext.ActionParameters[p.ParameterName] = StringHelper.GetValidScriptMsg(filterContext.ActionParameters[p.ParameterName].ToString());
                //        }
                //    }
                //}


                //////对参数的过滤,例如处理一些比较敏感的信息
                ////string parameterName = "AdminName";
                //////s1: 获取参数信息 ,得到参数的个数以及每个参数的类别
                ////filterContext.ActionDescriptor.GetParameters();
                //////s2: 获取参数值,返回一个字典
                //////parameterValue 参数值 , parameterName 参数名
                ////var parameterValue = filterContext.ActionParameters[parameterName];
                //////s3: 敏感信息过滤
                ////// 过滤算法

                ////// 过滤后赋值
                //////filterContext.ActionParameters[parameterName] = newParameterValue;

                ////追加参数
                //var parameters = filterContext.ActionParameters;
                //parameters.Add("TenantId", loginUser.TenantId);
                //parameters.Add("CreateId", loginUser.ID);
                //parameters.Add("AdminName", loginUser.AccountName);
                //parameters.Add("CreateIP", Util.GetLocalIP);
                //parameters.Add("CreateTime", DateTime.Now);
                //parameters.Add("UpdateId", loginUser.ID);
                //parameters.Add("UpdateUser", loginUser.AccountName);
                //parameters.Add("UpdateIP", Util.GetLocalIP);
                //parameters.Add("UpdateTime", DateTime.Now);
            }
            // 别忘了这一句。
            base.OnActionExecuting(filterContext);



            //if (parameters.Keys.Contains("qxun_userkey"))
            //{
            //    parameters["qxun_userkey"] as string;
            //}
        }
示例#16
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var manager = new AccountManager();


            AccountViewModel model = null;

            if (this.IsUpdateMode())
            {
                string qsID = Request.QueryString["ID"];

                Guid temp;
                if (!Guid.TryParse(qsID, out temp))
                {
                    return;
                }


                model = manager.GetAccountViewModel(temp);
            }
            else
            {
                model = new AccountViewModel();
            }


            if (this.IsUpdateMode())
            {
                if (!string.IsNullOrEmpty(this.txtPWD.Text) &&
                    !string.IsNullOrEmpty(this.txtNewPWD.Text))
                {
                    if (model.PWD == this.txtPWD.Text.Trim())
                    {
                        if (this.txtPWD.Text.Trim() == this.txtNewPWD.Text.Trim())
                        {
                            this.lblMsg.Text = "新密碼和原密碼重複";
                            return;
                        }
                        else
                        {
                            model.PWD = this.txtNewPWD.Text.Trim();
                        }
                    }
                    else
                    {
                        this.lblMsg.Text = "密碼和原密碼不一致";
                        return;
                    }
                }
            }
            else
            {
                if (string.IsNullOrEmpty(this.txtNewPWD.Text))
                {
                    this.lblMsg.Text = "密碼不可以為空";
                    return;
                }

                if (manager.GetAccount(this.txtAccount.Text.Trim()) != null)
                {
                    this.lblMsg.Text = "帳號已重覆,請選擇其它帳號";
                    return;
                }

                model.Account = this.txtAccount.Text.Trim();
                model.PWD     = this.txtNewPWD.Text.Trim();
            }

            model.Title = this.txtTitle.Text.Trim();
            model.Name  = this.txtName.Text.Trim();
            model.Email = this.txtEmail.Text.Trim();
            model.Phone = this.txtPhone.Text.Trim();

            int userLever = 0;

            if (int.TryParse(this.rdblUserLevel.SelectedValue, out userLever))
            {
                try
                {
                    var item = (UserLevel)userLever;
                }
                catch
                {
                    throw;
                }

                model.UserLevel = userLever;
            }


            if (this.IsUpdateMode())
            {
                manager.UpdateAccountViewModel(model);
            }
            else
            {
                try
                {
                    manager.CreateAccountViewModel(model);
                }
                catch (Exception ex)
                {
                    this.lblMsg.Text = ex.ToString();
                    return;
                }
            }

            this.lblMsg.Text = "存檔成功";
        }
        /// <summary>
        /// 新增帳號
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult Create()
        {
            var viewModel = new AccountViewModel();
            viewModel.RoleCheckList = accountService.GetRoleByAdminId(null);

            return View(viewModel);
        }
        //
        // GET: /Manage/Index
        public async Task <ActionResult> Index(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : message == ManageMessageId.SavedAccountDetailsSuccess ? "Your new account information saved successfully."
                : "";

            var             userId      = User.Identity.GetUserId();
            var             memberUser  = new MemberUser();
            var             creditCards = new List <CreditCard>();
            CVGSAppEntities db          = new CVGSAppEntities();

            memberUser  = db.MemberUsers.FirstOrDefault(m => m.Id == userId);
            creditCards = db.CreditCards.Where(c => c.HolderId == userId).ToList();

            var categoryPrefs = (GameCategoryOptions)memberUser.CategoryOptions;
            var platformPrefs = (FavoritePlatforms)memberUser.PlatformOptions;

            var mailingAddress = string.Empty;

            if (!string.IsNullOrEmpty(memberUser.MailingAddressStreetNumber))
            {
                mailingAddress = string.IsNullOrEmpty(memberUser.MailingAddressApartment) ? string.Empty : memberUser.MailingAddressApartment + "-";
                //mailingAddress += string.IsNullOrEmpty(mailingAddress) ? string.Empty : " ";
                mailingAddress += memberUser.MailingAddressStreetNumber;
                mailingAddress += " " + memberUser.MailingAddressStreetName;
                mailingAddress += ", " + memberUser.MailingAddressCity;
                mailingAddress += ", " + db.Provinces.FirstOrDefault(p => p.Code == memberUser.MailingAddressProvince).Name;
                mailingAddress += ", " + memberUser.MailingAddressPostalCode;
            }

            var shippingAddress = string.Empty;

            if (!string.IsNullOrEmpty(memberUser.ShippingAddressStreetNumber))
            {
                shippingAddress = string.IsNullOrEmpty(memberUser.ShippingAddressApartment) ? string.Empty : memberUser.ShippingAddressApartment + "-";
                //shippingAddress += string.IsNullOrEmpty(shippingAddress) ? string.Empty : " ";
                shippingAddress += memberUser.ShippingAddressStreetNumber;
                shippingAddress += " " + memberUser.ShippingAddressStreetName;
                shippingAddress += ", " + memberUser.ShippingAddressCity;
                shippingAddress += ", " + db.Provinces.FirstOrDefault(p => p.Code == memberUser.ShippingAddressProvince).Name;
                shippingAddress += ", " + memberUser.ShippingAddressPostalCode;
            }



            var model = new AccountViewModel
            {
                DisplayName                     = User.Identity.Name,
                Email                           = await UserManager.GetEmailAsync(userId),
                FirstName                       = memberUser.FirstName,
                LastName                        = memberUser.LastName,
                BirthDate                       = memberUser.BirthDate,
                Sex                             = memberUser.Sex == null ? 2 : (int)memberUser.Sex,
                GameCategoryPreference          = categoryPrefs.ToString(),
                GamePlatformPreference          = platformPrefs.ToString(),
                SendPromotionalEmailsPreference = memberUser.SendPromotionalEmails == null || !(bool)memberUser.SendPromotionalEmails ? "No" : "Yes",
                //ActionChecked = categoryPrefs.HasFlag(GameCategoryOptions.Action),
                //AdventureChecked = categoryPrefs.HasFlag(GameCategoryOptions.Adventure),
                //RolePlayingChecked = categoryPrefs.HasFlag(GameCategoryOptions.RolePlaying),
                //SimulationChecked = categoryPrefs.HasFlag(GameCategoryOptions.Simulation),
                //StrategyChecked = categoryPrefs.HasFlag(GameCategoryOptions.Strategy),
                //PuzzleChecked = categoryPrefs.HasFlag(GameCategoryOptions.Puzzle),
                //PCChecked = platformPrefs.HasFlag(FavoritePlatforms.PC),
                //PlayStationChecked = platformPrefs.HasFlag(FavoritePlatforms.PlayStation),
                //XboxChecked = platformPrefs.HasFlag(FavoritePlatforms.Xbox),
                //NintendoChecked = platformPrefs.HasFlag(FavoritePlatforms.Nintendo),
                //MobileChecked = platformPrefs.HasFlag(FavoritePlatforms.Mobile),
                //SendPromotionalEmails = memberUser.SendPromotionalEmails == null ? false : (bool)memberUser.SendPromotionalEmails,
                MailingAddress  = mailingAddress,
                ShippingAddress = shippingAddress,
                CreditCards     = creditCards ?? new List <CreditCard>()
            };

            return(View(model));
        }
 private void InitDesignTime()
 {
     PivotIndex = 0;
     AccountVM  = new AccountViewModel(navigationService);
 }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            /*Check if this action has AllowAnonymousAttribute*/
            string actionname = filterContext.ActionDescriptor.ActionName;
            int    AccountID  = Thread.CurrentPrincipal.Identity.ToAccountID();

            if (AccountID > 0 && (actionname != "Suspended" && actionname != "Maintanance"))
            {
                AccountViewModel account = cacheService.GetAccount(AccountID);
                if (account != null)
                {
                    if (account.Status == 3)/*paused*/
                    {
                        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                        {
                            controller = "Error",
                            action     = "Suspended"
                        }));
                        return;
                    }
                    else if (account.Status == 5)
                    {
                        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                        {
                            controller = "Error",
                            action     = "Maintanance"
                        }));
                        return;
                    }
                }
            }
            var attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);

            #region route data
            var routeData = Request.RequestContext.RouteData;
            this.CurrentArea       = routeData.DataTokens["area"] as string;
            this.CurrentController = routeData.GetRequiredString("controller");
            this.CurrentAction     = routeData.GetRequiredString("action");
            #endregion
            if (attributes.Any(a => a is MenuTypeAttribute))
            {
                TempData[Keys.MENU_TYPE] = ((MenuTypeAttribute)attributes.Where(a => a is MenuTypeAttribute).Single()).Category;
            }
            else
            {
                TempData[Keys.MENU_TYPE] = default(MenuCategory);
            }
            if (attributes.Any(a => a is MenuTypeAttribute))
            {
                TempData[Keys.LEFT_MENU_TYPE] = ((MenuTypeAttribute)attributes.Where(a => a is MenuTypeAttribute).Single()).LeftMenuType;
            }
            else
            {
                TempData[Keys.LEFT_MENU_TYPE] = default(MenuCategory);
            }
            if (attributes.Any(a => a is AllowAnonymousAttribute))
            {
                return;
            }
            /*must login*/
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                Logger.Current.Informational("Request not authenticated 1 " + filterContext.HttpContext.User.Identity.ToUserEmail());
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
            /*check authorization*/
            if (attributes.Any(a => a is AppFeatureAttribute) && ((AppFeatureAttribute)attributes.Where(a => a is AppFeatureAttribute).Single()).Feature != AppFeatures.NOT_APPLICABLE && !Thread.CurrentPrincipal.Identity.IsInFeature(((AppFeatureAttribute)attributes.Where(a => a is AppFeatureAttribute).Single()).Feature))
            {
                Logger.Current.Informational("Request not authenticated 2 " + filterContext.HttpContext.User.Identity.ToUserEmail());
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
 public ActionResult Create(AccountViewModel account)
 {
     service.OpenAccount(account.HolderFirstName, account.HolderLastName, account.HolderEmail, account.AccountType);
     return(RedirectToAction("Index"));
 }
示例#22
0
        public async Task <IActionResult> ChangeBalance(AccountViewModel model, string returnUrl)
        {
            var balance = await this.userService.ChangeBalance(model.Id, model.BalanceValue);

            return(Redirect(returnUrl));
        }
示例#23
0
 public void ShowAccountDetails(AccountViewModel accountViewModel)
 {
     _navigationService.UriFor <AccountDetailsPageViewModel>()
     .WithParam(x => x.AccountId, accountViewModel.Id)
     .Navigate();
 }
 public RemoveAccountCommand(AccountViewModel viewModel)
 {
     _viewModel = viewModel;
 }
示例#25
0
 public MainViewModel()
 {
     this.Items = new ObservableCollection<ItemViewModel>();
     this.OnlineTags = new ObservableCollection<OnlineTagListViewModel>();
     Account = new AccountViewModel();
 }
 public AddAccountCommand(AccountViewModel viewModel)
 {
     _viewModel = viewModel;
 }
        /// <summary>
        /// 編輯帳號
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>ActionResult.</returns>
        public ActionResult Edit(Guid id)
        {
            var data = accountService.GetById(id);
            if (data == null)
                return HttpNotFound();

            var viewModel = new AccountViewModel();
            var account = new AccountView
            {
                Id = data.Id,
                Account = data.Account
            };

            viewModel.AccountView = account;
            viewModel.RoleCheckList = accountService.GetRoleByAdminId(id);

            return View(viewModel);
        }
示例#28
0
 /// <summary>
 /// Indicates the existence of the passed account name.
 /// </summary>
 /// <param name="account">Account: account object of which the name existence is desired.</param>
 /// <param name="userID">String: UserID of the account.</param>
 /// <returns></returns>
 public bool NameExists(AccountViewModel vm, string userID)
 {
     return(Context.Accounts
            .Where(a => a.UserID == userID && a.Name.ToLower() == vm.AccountOfInterest.Name.ToLower() && a.AccountID != vm.AccountOfInterest.AccountID)
            .Any());
 }
示例#29
0
 public void ShowAccountDetails(AccountViewModel accountViewModel)
 {
     _navigationService.UriFor<AccountDetailsPageViewModel>()
         .WithParam(x => x.AccountId, accountViewModel.Id)
         .Navigate();
 }
示例#30
0
        public ActionResult SignIn()
        {
            var model = new AccountViewModel();

            return(View(model));
        }
示例#31
0
 public CustomPrincipal(AccountViewModel _account)
 {
     this.accountViewModel = _account;
     this.Identity         = new GenericIdentity(this.accountViewModel.Nombre);
 }
示例#32
0
 public void Setup()
 {
     _sut = new AccountViewModel();
 }
示例#33
0
 public AccountPage()
 {
     InitializeComponent();
     BindingContext = viewModel = new AccountViewModel();
 }
示例#34
0
 public void TearDown()
 {
     _sut = null;
 }
示例#35
0
 public Login()
 {
     InitializeComponent();
     _vm = new AccountViewModel();
 }
        public async Task GetTotalEndOfMonthBalance_ClearedPaymentsIgnored_CorrectSum()
        {
            // Arrange
            var account1 = new AccountViewModel {
                Id = 1, CurrentBalance = 100
            };

            var accounts = new List <AccountViewModel>
            {
                account1
            };

            var paymentList = new List <PaymentViewModel>
            {
                new PaymentViewModel
                {
                    Id             = 10,
                    ChargedAccount = account1,
                    Amount         = 100,
                    IsCleared      = false,
                    Date           = DateTime.Now,
                    Type           = PaymentType.Expense
                },
                new PaymentViewModel
                {
                    Id             = 15,
                    ChargedAccount = account1,
                    Amount         = 200,
                    IsCleared      = false,
                    Date           = DateTime.Now,
                    Type           = PaymentType.Income
                },
                new PaymentViewModel
                {
                    Id             = 20,
                    ChargedAccount = account1,
                    Amount         = 450,
                    IsCleared      = true,
                    Date           = DateTime.Now,
                    Type           = PaymentType.Expense
                },
                new PaymentViewModel
                {
                    Id             = 25,
                    ChargedAccount = account1,
                    Amount         = 150,
                    IsCleared      = true,
                    Date           = DateTime.Now,
                    Type           = PaymentType.Income
                }
            };

            var mock = paymentList.AsQueryable().BuildMock();

            var crudServiceSetup = new Mock <ICrudServicesAsync>();

            crudServiceSetup.Setup(x => x.ReadManyNoTracked <PaymentViewModel>())
            .Returns(mock.Object);
            crudServiceSetup.Setup(x => x.ReadManyNoTracked <AccountViewModel>())
            .Returns(accounts.AsQueryable().BuildMock().Object);

            // Act
            var result = await new BalanceCalculationService(crudServiceSetup.Object)
                         .GetTotalEndOfMonthBalance();

            // Assert
            Assert.Equal(200, result);
        }
示例#37
0
 private bool IsValid(AccountViewModel avm)
 {
     return(avm.Account.Username.Equals("test") && avm.Account.Password.Equals("test"));
 }
 public void Register(AccountViewModel accountViewModel)
 {
     throw new NotImplementedException();
 }
示例#39
0
 public SignInCommand(AccountViewModel accountViewModel)
 {
     this.accountViewModel = accountViewModel;
 }
 public void Update(AccountViewModel accountViewModel)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Calculates the sum of all accounts at the current moment.
        /// </summary>
        /// <returns>Sum of the balance of all accounts.</returns>
        protected override async Task <decimal> CalculateTotalBalanceAsync()
        {
            AccountViewModel account = mapper.Map <AccountViewModel>(await mediator.Send(new GetAccountByIdQuery(accountId)));

            return(account.CurrentBalance);
        }
        public ActionResult Accounts(AccountViewModel model, string pageAccountAction, string pageAccountArg)
        {
            var pageItems = FillAccountViewModel(model, pageAccountAction, pageAccountArg);

            ModelState.Remove("StrSortColName");
            ModelState.Remove("PageNomber");

            var newModel = new AccountViewModel
            {
                CurrentPageItems = pageItems,
                PageNomber = pageItems.PageIndex,
                SortColName = model.SortColName,
                StrSortColName = model.StrSortColName
            };

            if (Request.IsAjaxRequest())
                return PartialView("AccountsPartialTable", newModel);
            return  View("Accounts", newModel);
        }
示例#43
0
        public void Upload(AccountViewModel account, ItemViewModel toUpload, Dispatcher dispatcher)
        {
            this.account = account;
            this.toUpload = toUpload;
            this.dispatcher = dispatcher;
            childWindow = new Views.StyledChildWindow();

            var backgroundThread = new System.Threading.Thread(UploadProc);
            backgroundThread.Start();

            childWindow.Closed += (sender, args) =>
            {
                cancelRequested = true;
                try
                {
                    if (myRequest != null)
                        myRequest.Abort();
                }
                catch
                {
                    // ignore problems :/
                }
            };

            childWindow.Show("uploading script '" + toUpload.Title + "'");
            childWindow.ShowCancelButton();
        }
        /// <summary>
        /// в объекте типа AccountViewModel заполняет актуальными данными свойства, относящие к постраничному разбиению и сортировке
        /// </summary>
        /// <param name="model">ссылка на объект модели. В этом объекте будем ооновлять значения свойств</param>
        /// <param name="pageAccountAction">идентификатор действия, которое было произведено пользователем</param>
        /// <param name="pageAccountArg">дополнительные данный (номер страници или порядок сортировки)</param>
        /// <returns></returns>
        private PagedList<AccountTag> FillAccountViewModel(AccountViewModel model, string pageAccountAction, string pageAccountArg)
        {
            model.SortColName = new List<KeyValuePair<string, int>>();
            FillSortColName(model);

            switch (pageAccountAction)
            {
                case "Paging":
                    model.PageNomber = String.IsNullOrEmpty(pageAccountArg) ? 0 : Convert.ToInt32(pageAccountArg);
                    break;
                case "Sort":
                    var direction = 1;
                    if (model.SortColName.Select(x => x.Key).Contains(pageAccountArg))
                        direction = -1 * model.SortColName.First(x => x.Key == pageAccountArg).Value;

                    model.SortColName.RemoveAll(x => x.Key == pageAccountArg);
                    model.SortColName.Add(new KeyValuePair<string, int>(pageAccountArg, direction));
                    break;
            }
            model.StrSortColName = String.Join(";", model.SortColName.Select(x => String.Format("{0}:{1}", x.Key, x.Value)));

            var pageItems = accountRepository.GetAllAccounts(model);
            return new PagedList<AccountTag>(pageItems, model.PageNomber, model.CurrentPageSize); //TODO непонятно, как это работает
        }
        public ActionResult Create(AccountViewModel model)
        {
            // 新增帳號
            CiResult<Guid> result = accountService.DbCreate(model.AccountView.Account, model.AccountView.Password);
            TempData["alert"] = result.Message;

            if (result.ReturnResult == ReturnResult.Success)
            {
                Guid adminId = result.Data;
                // 新增角色list
                CiResult resultRole = accountService.DbUpdateAdminRoles(adminId, model.RoleCheckList);
                TempData["alert"] += resultRole.Message;
                if (resultRole.ReturnResult == ReturnResult.Success)
                {
                    return RedirectToAction("Index", "Account");
                }
            }

            return View(model);
        }
        public async Task <IActionResult> Post([FromBody] LoginViewModel User)
        {
            try
            {
                var account = await _accountService.Authenticate(User.Username, User.Password);

                if (account == null)
                {
                    Dictionary <string, object> Result =
                        new ResultFormatter(ApiVersion, General.NOT_FOUND_STATUS_CODE, General.NOT_FOUND_MESSAGE)
                        .Fail();
                    return(NotFound(Result));
                }
                else
                {
                    AccountViewModel viewModel = Mapper.Map <AccountViewModel>(account);

                    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Secret));
                    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                    var header = new JwtHeader(credentials);

                    var payload = new JwtPayload
                    {
                        { "username", viewModel.username }
                    };

                    payload["profile"] = new
                    {
                        viewModel.profile.firstname,
                        viewModel.profile.lastname,
                        viewModel.profile.gender,
                        viewModel.profile.dob,
                        viewModel.profile.email
                    };

                    string jsonRes = "{";

                    if (viewModel.roles.Count > 0)
                    {
                        foreach (var item in viewModel.roles.SelectMany(x => x.permissions).GroupBy(x => x.unit.Code).Select(g => g.First()))
                        {
                            jsonRes = jsonRes + "'" + item.unit.Code + "'" + " : " + item.permission + ",";
                        }

                        jsonRes = jsonRes.Remove(jsonRes.Length - 1);
                    }

                    jsonRes += "}";



                    var jsonObject = JObject.Parse(jsonRes);

                    payload["permission"] = jsonObject;

                    payload["iat"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

                    var secToken = new JwtSecurityToken(header, payload);
                    var handler  = new JwtSecurityTokenHandler();

                    var tokenString = handler.WriteToken(secToken);

                    Dictionary <string, object> Result =
                        new ResultFormatter(ApiVersion, General.OK_STATUS_CODE, General.OK_MESSAGE)
                        .Ok();

                    Result.Add("data", tokenString);

                    return(Ok(Result));
                }
            }
            catch (Exception ex)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.BAD_REQUEST_STATUS_CODE, ex.Message)
                    .Fail();

                return(BadRequest(Result));
            }
        }
        public ActionResult Edit(AccountViewModel model)
        {
            var data = accountService.GetById(model.AccountView.Id);
            if (data == null)
                return HttpNotFound();

            // 更改帳號
            CiResult resultAcount = accountService.DbUpdateAccount(model.AccountView.Id, model.AccountView.Account);
            TempData["alert"] = resultAcount.Message;
            if (resultAcount.ReturnResult != ReturnResult.Success)
            {
                return View(model);
            }

            // 更改密碼
            if (!string.IsNullOrEmpty(model.AccountView.Password))
            {
                CiResult resultPassword = accountService.DbUpdatePassword(model.AccountView.Id, model.AccountView.Password);
                TempData["alert"] += resultPassword.Message;
                if (resultPassword.ReturnResult != ReturnResult.Success)
                {
                    return View(model);
                }
            }

            // 更改角色list
            CiResult resultRole = accountService.DbUpdateAdminRoles(model.AccountView.Id, model.RoleCheckList);
            TempData["alert"] += resultRole.Message;
            if (resultRole.ReturnResult != ReturnResult.Success)
            {
                return View(model);
            }

            return RedirectToAction("Index");
        }
示例#48
0
        /// <summary>
        /// Запрос проще сформировать в виде стоки и отпра
        /// </summary>
        public List<AccountTag> GetFilterAccountFromServer(AccountViewModel model)
        {
            #region Формируем список фильтров
            var filters = new List<string>();
            if (model != null)
            {
                if (model.FilterId.HasValue) filters.Add("ID = " + model.FilterId.Value);
                if (model.FilterBalanceLower.HasValue) filters.Add("Balance >= " + model.FilterBalanceLower.Value);
                if (model.FilterBalanceUpper.HasValue) filters.Add("Balance <= " + model.FilterBalanceUpper.Value);
                if (!String.IsNullOrEmpty(model.FilterBalanceTicker)) filters.Add("Currency = '" + model.FilterBalanceTicker + "'");
                if (!String.IsNullOrEmpty(model.FilterGroup)) filters.Add("AccountGroup = '" + model.FilterGroup + "'");
            }
            #endregion

            var result = new List<AccountTag>();
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var sqlQueryString = new StringBuilder();
                    sqlQueryString.Append(@"select ac.ID, AccountGroup, Currency, Balance,
                                            STUFF((select ',' +  dbo.MakeUserNameWithInitials(usr.Login, usr.Name, usr.Surname, usr.Patronym)
                                                    from PLATFORM_USER usr join PLATFORM_USER_ACCOUNT ua on usr.ID = ua.PlatformUser
                                            where ac.ID = ua.Account for xml path('')), 1, 1, '') UserNames,
                                            STUFF((select ',' + convert(VARCHAR, usr.ID)
                                                from PLATFORM_USER usr join PLATFORM_USER_ACCOUNT ua on usr.ID = ua.PlatformUser
                                            where ac.ID = ua.Account for xml path('')), 1, 1, '') UserId from ACCOUNT ac");
                    // фильтр по хозяевам счёта
                    if (model != null && !String.IsNullOrEmpty(model.FilterOwners))
                        sqlQueryString.Append(@" join PLATFORM_USER_ACCOUNT pac on ac.ID = pac.Account
                                                join PLATFORM_USER us on us.ID = pac.PlatformUser and dbo.MakeUserNameWithInitials(us.Login, us.Name, us.Surname, us.Patronym)
                                                like '%" + model.FilterOwners + "%'");

                    if (filters.Count > 0)
                    {
                        sqlQueryString.Append(" where ");
                        sqlQueryString.Append(String.Join(" and ", filters));
                    }

                    var accountsDb = ctx.Database.SqlQuery<GetAllAccountsUserDetail_Result>(sqlQueryString.ToString()).ToList();
                    // ReSharper disable LoopCanBeConvertedToQuery
                    foreach (var ac in accountsDb)
                    // ReSharper restore LoopCanBeConvertedToQuery
                    {
                        result.Add(new AccountTag(ac));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Не удалось получить список всех счетов", ex);
                return new List<AccountTag>();
            }
            return result;
        }
        public ActionResult Login(string Email, string Password, bool? rmcheck)
        {
            //int index;
            Account mu = db.Accounts.FirstOrDefault(i => i.Email.Equals(Email));
            //string dp = null;
            if (!String.IsNullOrEmpty(Email))
            {
                if (mu != null)
                {
                    //index = mu.UserID;
                    string pass = db.Accounts.Where(x => x.Email.Equals(Email)).Select(x => x.Password).Single();
                    //pass = Crypt.Decrypt(pass);
                    if (!string.IsNullOrEmpty(Password) && Password.Equals(pass))
                    {
                        Account id = db.Accounts.Find(Email);
                        var viewID = new AccountViewModel()
                        {
                            Email = id.Email,
                            Name = id.Name,
                            Password = id.Password
                        };
                        TempData["user"] = viewID;
                        Session["loggedin"] = viewID.Email;
                        //GetUniqueKey(25);

                        string token = Guid.NewGuid().ToString().Substring(0, 20);
                        if (rmcheck.HasValue)
                        {
                            HttpCookie cookie = new HttpCookie("Bank");
                            cookie.Values["Created"] = DateTime.Now.ToLongTimeString();

                            cookie.Values["Email"] = mu.Email.ToString();
                            cookie.Values["Name"] = mu.Name.ToString();
                            cookie.Values["rmcheck"] = rmcheck.ToString();
                            cookie.Expires = DateTime.Now.AddHours(8.0);
                            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                        }
                        else
                        {
                            HttpCookie cookie = new HttpCookie("Bank");
                            cookie.Values["Created"] = DateTime.Now.ToLongTimeString();

                            cookie.Values["Email"] = mu.Email.ToString();
                            cookie.Values["Name"] = mu.Name.ToString();
                            cookie.Values["rmcheck"] = rmcheck.ToString();
                            cookie.Expires = DateTime.Now.AddHours(0.5);
                            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                        }
                        //var userList = db.Logins.ToList();
                        return RedirectToAction("Index", "Account");
                    }
                    else
                    {
                        ViewBag.message = "Invalid Username or Password";
                    }
                }
                else
                {
                    ViewBag.message = "Account not found";
                    return View();
                }
            }
            else
            {
                //ViewBag.message = "Please enter a username and password";
                return View();
            }
            return View();
            //cookie();
        }
示例#50
0
        public ActionResult LoginByWeixin(string code, string userInfo)
        {
            try
            {
                var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code);
                if (jsonResult.errcode == ReturnCode.请求成功)
                {
                    //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐)
                    //使用SessionContainer管理登录信息(推荐)
                    //var unionId = "";
                    //var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId);
                    var accountViewModel = new AccountViewModel();
                    var accountDto       = SerializeHelper.DeserializeString <AccountDto>(userInfo);

                    var user = _context.Account.FirstOrDefault(_ => _.OpenId == jsonResult.openid);
                    if (user == null)
                    {
                        user = new Account
                        {
                            OpenId    = jsonResult.openid,
                            NickName  = accountDto.NickName,
                            AvatarUrl = accountDto.AvatarUrl,
                            Status    = AccountStatus.Enabled
                        };
                        var account = _context.Account.Add(user).Entity;
                        _context.SaveChanges();
                        //角色控制
                        Role role = _context.Role.FirstOrDefault(_ => _.RoleName == "普通用户");
                        _context.UserRole.Add(new UserRole
                        {
                            RoleId = role.Id,
                            UserId = account.Id
                        });
                        _context.SaveChanges();
                    }
                    //角色控制
                    var  userRole = _context.UserRole.FirstOrDefault(_ => _.UserId == user.Id);
                    Role bindRole = userRole == null ? null : userRole.Role;
                    accountViewModel = _mapper.Map <AccountViewModel>(user);
                    //角色控制
                    accountViewModel.Role     = _mapper.Map <RoleViewModel>(bindRole);
                    accountViewModel.RoleName = bindRole == null ? null : bindRole.RoleName;
                    // 将用户id和角色名,作为单独的自定义变量封装进 token 字符串中。
                    TokenModelJwt tokenModel = new TokenModelJwt {
                        Uid = user.Id.ToString(), Role = accountViewModel.Role == null ? "" : accountViewModel.Role.RoleName
                    };
                    string jwtStr = JwtHelper.IssueJwt(tokenModel, TokenType.AccessToken);//登录,获取到一定规则的 Token 令牌

                    _distributeCache.Set("AppAccount" + tokenModel.Uid, SerializeHelper.ObjectToByteArray(accountViewModel));

                    //注意:生产环境下SessionKey属于敏感信息,不能进行传输!
                    return(Ok(new
                    {
                        success = true,
                        msg = "OK",
                        data = new
                        {
                            token = jwtStr,
                            userInfo = accountViewModel
                        }
                    }));
                }
                else
                {
                    return(Ok(new { success = false, msg = jsonResult.errmsg }));
                }
            }
            catch (Exception ex)
            {
                return(Ok(new { success = false, msg = ex.Message }));
            }
        }
示例#51
0
 public object Convert(object value, Type targetType,
                       object parameter, string language)
 {
     return(AccountViewModel.getName((long)value));
 }
示例#52
0
 public ButtonCommand(AccountViewModel _Account)
 {
     Account = _Account;
 }
 /// <summary>
 /// заполняем свойство 'SortColName' из строки 'StrSortColName' 
 /// </summary>
 /// <param name="model">ссылка на модель представления, для того, что бы в ней можно было заполнить свойство 'SortColName'</param>
 /// <returns></returns>
 private static void FillSortColName(AccountViewModel model)
 {
     if (!string.IsNullOrEmpty(model.StrSortColName))
         foreach (var sortColName in model.StrSortColName.Split(';'))
         {
             var strKeyValue = sortColName.Split(':');
             // ReSharper disable RedundantAssignment
             var direct = 1;
             // ReSharper restore RedundantAssignment
             Int32.TryParse(strKeyValue[1], out direct);
             model.SortColName.Add(new KeyValuePair<string, int>(strKeyValue[0], direct));
         }
 }
示例#54
0
 public List<AccountTag> GetAllAccounts(AccountViewModel model)
 {
     var accounts = GetFilterAccountFromServer(model);
     if (model != null)
     {
         if (model.SortColName != null && model.SortColName.Count > 0)
         {
             model.SortColName.Reverse();
             accounts.Sort((a, b) =>
             {
                 foreach (var field in model.SortColName)
                 {
                     try
                     {
                         var valA = (IComparable)AccountViewModel.sortFieldSelector[field.Key](a);
                         var valB = (IComparable)AccountViewModel.sortFieldSelector[field.Key](b);
                         var order = field.Value * valA.CompareTo(valB);
                         if (order != 0)
                             return order;
                         //Если элементы равны по первому полю, тогда сравниваем по второму. Если не равны по первому - сравнивать по второму нет смысла
                     }
                     catch (Exception ex)
                     {
                         Logger.Error(
                             String.Format(
                                 "GetAllAccountsSort() не удалось сравнить элементы типа AccountTag. Возможно тип поля {0} не реализует IComparable",
                                 field.Key), ex);
                     }
                 }
                 return 0;
             });
         }
     }
     return accounts;
 }
		public ConfigPanelViewModel(TimelineBlock block)
		{
			this.block = block;
			this.CompositeDisposable.Add(new PropertyChangedEventListener(block)
			{
				(sender, e) => this.RaisePropertyChanged(e.PropertyName),
			});

			this._CurrentAccount = AccountViewModel.Get(block.Account);
			this.CompositeDisposable.Add(new CollectionChangedEventListener(TwitterClient.Current.Accounts)
			{
				// アカウントのコレクションが更新されたとき、現在のアカウントが設定されていなければ、再取得する
				(sender, e) => { if (!this.CurrentAccount.IsValid) this.CurrentAccount = AccountViewModel.Get(block.Account); },
			});

			this.ReceivingSettings = block.IsReceivingAll
				? "受信したすべてのツイート"
				: block.Timeline.SubscribedLists.ToString(" ");
		}
        public ActionResult Register(string Email, string Password, string Name, string ConfirmPass)
        {
            //Account mu = db.Accounts.FirstOrDefault(i => i.Email.Equals(Email));
            DateTime Date = DateTime.Now.Date;
            //int UserId;
            //if (db.Accounts.Count() == 0)
            //{
            //    UserId = 1;
            //}
            //else
            //{
            //    UserId = db.Accounts.Max(i => i.UserID) + 1;
            //};
            var newUser = db.Accounts.FirstOrDefault(u => u.Email == Email);
            if (newUser != null)
            {
                ViewBag.email = "Email Address Exists";

                return View();

            }
            else
            {
                if (Password != ConfirmPass)
                {
                    ViewBag.pass = "******";

                    return View();
                }
                else
                {
                    //Password = Crypt.Encrypt(Password);
                    string query = "INSERT INTO Account ( Email, Name,  Password, ConfirmPass, Date) VALUES ('" + Email + "','" + Name + "','" + Password + "','" + ConfirmPass + "','"+DateTime.Now+"');";
                    SqlCommand comm = new SqlCommand(query, conn);

                    using (conn)
                    {
                        try
                        {
                            conn.Open();
                            comm.ExecuteNonQuery();
                        }
                        catch (SqlException e)
                        {
                            e.StackTrace.ToString();
                        }
                        finally
                        {
                            conn.Close();
                        }

                        HttpCookie cookie = new HttpCookie("Bank");
                        cookie.Values["Created"] = DateTime.Now.ToLongTimeString();
                        cookie.Values["Email"] = Email.ToString();
                        cookie.Values["Name"] = Name.ToString();
                        cookie.Expires = DateTime.Now.AddHours(2.0);
                        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                    }
                }
                Account id = db.Accounts.Find(Email);
                var viewID = new AccountViewModel()
                {
                    Email = id.Email,
                    Name = id.Name,
                    Password = id.Password,
                    checkingBal = System.Convert.ToDouble(id.CheckingBalance),
                    savingsBal = System.Convert.ToDouble(id.SavingsBalance)
                    //UserID = id.UserID.ToString()
                };
                TempData["user"] = viewID;
                Session["loggedin"] = viewID.Email;
                return RedirectToAction("Index", "Account");
                //return View();
            }
        }