Esempio n. 1
0
        /// <summary>
        /// 获取当前用户可以看到的项目列表
        /// 作者:姚栋
        /// 日期:20180717
        /// </summary>
        /// <returns></returns>
        public IEnumerable <Base_ProjectInfoEntity> GetListByAuthorize(string queryJson)
        {
            StringBuilder sqlBuilder = new StringBuilder("select * from Base_ProjectInfo");
            var           lookAll    = new AuthorizeService <Base_ProjectInfoEntity>().LookAll();

            if (!lookAll)
            {
                sqlBuilder.Clear();
                sqlBuilder.AppendFormat(@"select distinct * from (
                    select  pinfo.ProjectID,pinfo.ProjecName,pinfo.DataStatus, pinfo.CompanyCode,pinfo.CompanyId,pinfo.CompanyName 
                     from view_post_project userProject
                    inner join Base_ProjectInfo pinfo
                    on userProject.ItemId=pinfo.ProjectID
                    where userProject.UserId='{0}'", SystemInfo.CurrentUserId);
                if (queryJson != "" && queryJson != null)
                {
                    sqlBuilder.AppendFormat(@" and pinfo.CompanyCode='{0}'", queryJson);
                }
                sqlBuilder.Append(@") Project");
            }
            else
            {
                if (queryJson != "" && queryJson != null)
                {
                    sqlBuilder.AppendFormat(@" where CompanyCode='{0}'", queryJson);
                }
            }
            return(this.BaseRepository().FindList <Base_ProjectInfoEntity>(sqlBuilder.ToString()));
        }
Esempio n. 2
0
        public async Task <IActionResult> Post([FromBody] Ruling ruling)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                if (!AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditCardRuling))
                {
                    return(Forbid("You are not allowed to create rulings."));
                }

                if (ruling.Card == null)
                {
                    return(BadRequest("The card is required."));
                }

                if (string.IsNullOrWhiteSpace(ruling.RuleText))
                {
                    return(BadRequest("The rule text is required."));
                }

                var cardModel = await repository.Context.Cards.FindByGuidAsync(ruling.Card.Guid);

                if (cardModel == null)
                {
                    return(BadRequest("The card is not found."));
                }

                var ruleModel = repository.CreateRuling(cardModel, ruling.RuleText, Guid.NewGuid());
                await repository.Context.SaveChangesAsync();

                return(Ok(ruleModel.FromDal()));
            }
        }
Esempio n. 3
0
        public static User FromDal(this UserModel userModel, bool includeRole = false, bool includeDecks = false, bool includeCards = false)
        {
            if (userModel == null)
            {
                return(null);
            }
            var result = new User
            {
                Id            = userModel.UserId,
                Guid          = userModel.Guid,
                Name          = userModel.Name,
                Email         = userModel.Email,
                LastLoginTime = userModel.LastLoginTime,
                CreateTime    = userModel.CreateTime,
                Token         = userModel.Token,
                IsDisabled    = userModel.IsDisabled,
                IsVerified    = userModel.IsVerified,
            };

            if (includeRole)
            {
                result.Role   = userModel.Role.FromDal();
                result.Rights = AuthorizeService.GetRights(userModel.Role);
            }

            if (includeDecks)
            {
                userModel.Decks.ForEach(x => result.Decks.Add(x.FromDal()));
            }
            if (includeCards)
            {
                userModel.Cards.ForEach(x => result.Cards.Add(x.FromDal()));
            }
            return(result);
        }
Esempio n. 4
0
 public IActionResult ModifyUser(ModifyUserModel model)
 {
     if (!AuthorizeService.AuthorizeUser(User, model.Id))
     {
         return(RedirectToAction("AccessDenied", "Auth"));
     }
     else
     {
         if (ModelState.IsValid)
         {
             Response response = UserService.UpdateUser(model.Id, model.Username);
             if (response.IsSuccessful)
             {
                 return(RedirectToAction("Success"));
             }
             else
             {
                 ModelState.AddModelError(string.Empty, response.Message);
                 return(View(model));
             }
         }
         else
         {
             return(View(model));
         }
     }
 }
Esempio n. 5
0
        public async Task <IActionResult> Get(Guid id)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                await repository.Context.Factions.LoadAsync();

                await repository.Context.CardTypes.LoadAsync();

                var result = await repository.Context.Decks
                             .Include(x => x.Creator)
                             .Include(x => x.Status)
                             .Include(x => x.DeckCards)
                             .ThenInclude(x => x.Card)
                             .Where(x => x.Guid == id).FirstOrDefaultAsync();

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

                var deck = result.FromDal(true);

                await repository.Context.Entry(result).Reference(x => x.Creator).LoadAsync();

                var isMyDeck = deck.Creator.Guid == repository.ServiceUser?.Guid;

                deck.IsEditable =
                    (isMyDeck && AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditDeck)) ||
                    (!isMyDeck && AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.AllowOthersDeckEdit));

                return(Ok(deck));
            }
        }
Esempio n. 6
0
        protected void btnChangePassword_Click(object sender, EventArgs e)
        {
            if (txtNewPassword.Text == txtNewPasswordConfirm.Text)
            {
                var customer = CustomerService.GetCustomerByEmail(Request["email"]);
                if (customer == null)
                {
                    return;
                }

                if (ValidationHelper.DeleteSigns(SecurityHelper.GetPasswordHash(customer.Password)).ToLower() ==
                    Request["recoverycode"].ToLower())
                {
                    CustomerService.ChangePassword(customer.Id, txtNewPassword.Text, false);
                    AuthorizeService.SignIn(Request["email"], txtNewPassword.Text, false, true);
                    MultiView1.SetActiveView(ViewPasswordChanged);
                }
                else
                {
                    MultiView1.SetActiveView(ViewRecoveryError);
                }
            }
            else
            {
                ShowMessage(Notify.NotifyType.Notice, Resources.Resource.Client_FogotPassword_PasswordDiffrent);
            }
        }
Esempio n. 7
0
    public string AddCategoryByFields(string name, int parent, string picture, bool enabled, int sortOrder)
    {
        if (!AuthorizeService.CheckAdminCookies())
        {
            return(MsgAuthFailed);
        }
        if (string.IsNullOrEmpty(picture))
        {
            picture = null;
        }
        var category = new Category
        {
            Name             = name,
            ParentCategoryId = parent,
            Picture          = new Photo(0, 0, PhotoType.CategoryBig)
            {
                OriginName = picture
            },
            SortOrder = sortOrder,
            Enabled   = enabled
        };
        int catId = CategoryService.AddCategory(category, true);

        return(catId != 0 ? string.Format(MsgAdded, catId) : MsgAddFailed);
    }
 public IActionResult Modify(ModifyCurrentUserModel model)
 {
     if (!AuthorizeService.AuthorizeUser(User, model.Id))
     {
         return(RedirectToAction("AccessDenied", "Auth"));
     }
     else
     {
         if (ModelState.IsValid)
         {
             User     user     = ModelConverter.ConvertFromUserModifyCurrnetUserModel(model);
             Response response = UserService.UpdateUser(user);
             if (response.IsSuccessful)
             {
                 return(RedirectToAction("Success"));
             }
             else
             {
                 ModelState.AddModelError(string.Empty, response.Message);
                 return(View(model));
             }
         }
         else
         {
             return(View(model));
         }
     }
 }
Esempio n. 9
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            // 这是base.IsAuthorized里的逻辑
            //IPrincipal principal = actionContext.ControllerContext.RequestContext.Principal;
            //return principal != null && principal.Identity != null
            //    && principal.Identity.IsAuthenticated &&
            //    (
            //        (this._usersSplit.Length <= 0 || ((IEnumerable<string>)this._usersSplit).Contains<string>(principal.Identity.Name, (IEqualityComparer<string>)StringComparer.OrdinalIgnoreCase))
            //        &&
            //        (this._rolesSplit.Length <= 0 || ((IEnumerable<string>)this._rolesSplit).Any<string>(new Func<string, bool>(principal.IsInRole)))
            //     );

            // 下在可替换成自己的授权逻辑代码
            AuthorizeService authorizeService = new AuthorizeService(new DB());
            var resourceName = actionContext.ActionDescriptor.GetCustomAttributes <RBAuthorizeAttribute>().Any()
                ? actionContext.ActionDescriptor.ActionName
                : actionContext.ControllerContext.ControllerDescriptor.ControllerName;
            var        roleNames = authorizeService.GetResourceRoleNames(resourceName);
            IPrincipal principal = actionContext.ControllerContext.RequestContext.Principal;

            return(principal != null && principal.Identity != null &&
                   principal.Identity.IsAuthenticated &&
                   (
                       (((IEnumerable <string>)roleNames).Any <string>(new Func <string, bool>(principal.IsInRole)))
                   ));
        }
Esempio n. 10
0
        /// <summary>
        /// 获取当前用户可以看到的区域公司列表
        /// 作者:姚栋
        /// 日期:20180717
        /// </summary>
        /// <returns></returns>
        public IEnumerable <DepartmentEntity> GetListByAuthorize()
        {
            StringBuilder sqlBuilder = new StringBuilder(@"
  select * from Base_Department dp where   dp.Layer = '区域公司' and dp.SourceSys = 'YGHR03'
  and dp.InnerPhone = '地产' and DeleteMark=0");
            var           lookAll    = new AuthorizeService <DepartmentEntity>().LookAll();

            if (!lookAll)
            {
                sqlBuilder.Clear();
                sqlBuilder.AppendFormat(@"select distinct 
                CompanyData.DepartmentId,
                CompanyData.FullName,
                CompanyData.DataStatus
                from (
                select  dp.DepartmentId,dp.FullName, userProject.ItemId,pinfo.DataStatus,
                pinfo.ProjecName,
                userProject.UserId
                 from view_post_project userProject
                inner join Base_ProjectInfo pinfo
                on userProject.ItemId=pinfo.ProjectID
                inner join  Base_Department dp
                on pinfo.CompanyCode=dp.DepartmentId 
                where userProject.UserId='{0}'
                ) CompanyData
                ", SystemInfo.CurrentUserId);
            }
            return(this.BaseRepository().FindList(sqlBuilder.ToString()));
        }
Esempio n. 11
0
        public async Task <IActionResult> Patch(Guid id, [FromBody] License license)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                if (!AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditLicense))
                {
                    return(Forbid("You are not allowed to edit licenses."));
                }
                if (string.IsNullOrWhiteSpace(license.Name))
                {
                    return(BadRequest("The name is required."));
                }
                if (string.IsNullOrWhiteSpace(license.Description))
                {
                    return(BadRequest("The description is required."));
                }
                if (string.IsNullOrWhiteSpace(license.Url))
                {
                    return(BadRequest("The url is required."));
                }
                var licenseModel = await repository.Context.Licenses.FindByGuidAsync(id);

                licenseModel.Patch(license, repository.ServiceUser);
                await repository.Context.SaveChangesAsync();

                return(Ok(licenseModel.FromDal()));
            }
        }
Esempio n. 12
0
 public void Setup()
 {
     _mockRepo             = new Mock <IPaymentGatewayRepo>();
     _mockLuhnCheckService = new Mock <ILuhnCheckService>();
     _repo        = _mockRepo.Object;
     _authService = new AuthorizeService(_mockRepo.Object, _mockLuhnCheckService.Object);
 }
Esempio n. 13
0
        public async Task <IActionResult> Get(Guid id)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                var cardModel = await repository.Context.Cards.FindByGuidAsync(id);

                await repository.Context.Entry(cardModel).Reference(x => x.Status).LoadAsync();

                await repository.Context.Entry(cardModel).Reference(x => x.Creator).LoadAsync();

                var cardOptions = new CardOptions();
                if (repository.ServiceUser != null)
                {
                    var isFinal = cardModel.Status.Guid == PredefinedGuids.Final;

                    cardOptions.IsEditable             = !isFinal && AuthorizeService.HashRight(repository.ServiceUser.Role, Rights.EditCard);
                    cardOptions.IsRulingEditable       = AuthorizeService.HashRight(repository.ServiceUser.Role, Rights.EditCardRuling);
                    cardOptions.IsStatusChangedAllowed = AuthorizeService.HashRight(repository.ServiceUser.Role, Rights.AllowCardStatusChange);
                }

                cardOptions.Factions        = repository.Context.Factions.AsNoTracking().ToList().Select(x => x.FromDal()).ToList();
                cardOptions.Series          = repository.Context.Series.AsNoTracking().ToList().Select(x => x.FromDal(false)).ToList();
                cardOptions.RuleSets        = repository.Context.RuleSets.AsNoTracking().ToList().Select(x => x.FromDal()).ToList();
                cardOptions.Statuses        = repository.Context.Statuses.AsNoTracking().ToList().Select(x => x.FromDal()).ToList();
                cardOptions.ArtworkLicenses = repository.Context.Licenses.AsNoTracking().ToList().Select(x => x.FromDal()).ToList();
                cardOptions.CardTypes       = repository.Context.CardTypes.Include(x => x.TemplateInfo).AsNoTracking().ToList().Select(x => x.FromDal(true)).ToList();

                cardOptions.Languages = Languages.All;

                return(Ok(cardOptions));
            }
        }
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            AuthorizeService.ClearCache(HttpContext.User.Identity.Name);
            FormsAuthentication.SignOut();

            return(RedirectToAction("Login", "Account", ""));
        }
Esempio n. 15
0
    public XmlDocument ExportOrderToXmlByStatus(int statusId)
    {
        if (!AuthorizeService.CheckAdminCookies())
        {
            return(ErrMsg(MsgAuthFailed));
        }
        var stats = OrderService.GetOrderStatuses(false);

        if (!stats.ContainsKey(statusId.ToString()))
        {
            return(ErrMsg(string.Format(MsgStatusError, statusId)));
        }
        var orders = OrderService.GetOrdersByStatusId(statusId);

        if (orders == null)
        {
            return(ErrMsg(MsgListError));
        }
        using (var writer = new StringWriter())
        {
            OrderService.SerializeToXml(orders, writer);
            var xml = new XmlDocument();
            xml.Load(writer.ToString());
            return(xml);
        }
    }
Esempio n. 16
0
    public XmlDocument GetOrderStatuses()
    {
        if (!AuthorizeService.CheckAdminCookies())
        {
            return(ErrMsg(MsgAuthFailed));
        }
        var        result = new XmlDocument();
        XmlElement root   = result.CreateElement("Statuses");
        Dictionary <string, string> stats = OrderService.GetOrderStatuses(false);

        if (stats == null)
        {
            return(ErrMsg(MsgStatusesError));
        }
        foreach (var stat in stats)
        {
            XmlElement   status = result.CreateElement("Status");
            XmlAttribute index  = result.CreateAttribute("ID");
            index.Value = stat.Key;
            status.Attributes.Append(index);
            status.InnerText = stat.Value;
            root.AppendChild(status);
        }
        result.AppendChild(root);
        return(result);
    }
Esempio n. 17
0
    public XmlDocument ExportOrderToXmlByStatusName(string statusName)
    {
        if (!AuthorizeService.CheckAdminCookies())
        {
            return(ErrMsg(MsgAuthFailed));
        }
        Dictionary <string, string> stats = OrderService.GetOrderStatuses(true);

        if (!stats.ContainsKey(statusName))
        {
            return(ErrMsg(string.Format(MsgStatusError, statusName)));
        }
        List <Order> orders = OrderService.GetOrdersByStatusId(Int32.Parse(stats[statusName]));

        if (orders == null)
        {
            return(ErrMsg(MsgListError));
        }
        using (var writer = new StringWriter())
        {
            OrderService.SerializeToXml(orders, writer);
            var xml = new XmlDocument();
            xml.Load(writer.ToString());
            return(xml);
        }
    }
Esempio n. 18
0
        public async Task <IActionResult> Get(Guid id)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                var deckModel = await repository.Context.Decks.FindByGuidAsync(id);

                await repository.Context.Entry(deckModel).Reference(x => x.Status).LoadAsync();

                await repository.Context.Entry(deckModel).Reference(x => x.Creator).LoadAsync();

                var deckOptions = new DeckOptions();
                var isMyDeck    = deckModel.Creator.Guid == repository.ServiceUser?.Guid;

                deckOptions.IsEditable =
                    (isMyDeck && AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditDeck)) ||
                    (!isMyDeck && AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.AllowOthersDeckEdit));

                deckOptions.IsStatusChangedAllowed =
                    (isMyDeck && AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditDeck)) ||
                    (!isMyDeck && AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.AllowDeckStatusChange));

                deckOptions.Statuses = repository.Context.Statuses.AsNoTracking().ToList().Select(x => x.FromDal()).ToList();

                return(Ok(deckOptions));
            }
        }
Esempio n. 19
0
        public static void AuthOrRegCustomer(Customer customer, string identifier)
        {
            if (!CustomerService.IsExistOpenIdLinkCustomer(identifier))
            {
                if (!CustomerService.CheckCustomerExist(customer.EMail))
                {
                    customer.Id = CustomerService.InsertNewCustomer(customer);

                    var registrationMail = new RegistrationMailTemplate(SettingsMain.SiteUrl, customer.FirstName,
                                                                        customer.LastName,
                                                                        Localization.Culture.ConvertDate(DateTime.Now),
                                                                        customer.Password,
                                                                        customer.SubscribedForNews
                                                                                ? Resources.Resource.Client_Registration_Yes
                                                                                : Resources.Resource.Client_Registration_No,
                                                                        customer.EMail);
                    registrationMail.BuildMail();

                    SendMail.SendMailNow(SettingsMail.EmailForRegReport, registrationMail.Subject, registrationMail.Body, true);
                }
                else
                {
                    customer = CustomerService.GetCustomerByEmail(customer.EMail);
                }
                CustomerService.AddOpenIdLinkCustomer(customer.Id, identifier);
                customer = CustomerService.GetCustomerByEmail(customer.EMail);
            }
            else
            {
                customer = CustomerService.GetCustomerByOpenAuthIdentifier(identifier);
            }

            AuthorizeService.SignIn(customer.EMail, customer.Password, true, true);
        }
Esempio n. 20
0
        public async Task <List <Users> > ValidLogin([FromBody] Users obj)
        {
            try
            {
                List <Users> lstLogin = new List <Users>();
                lstLogin = await this._usersBAL.ValidLogin(obj);

                if (lstLogin.Count > 0)
                {
                    AuthorizeService auth   = new AuthorizeService();
                    string           _token = auth.Authenticate(Convert.ToString(lstLogin[0].UserID), _appSettings);
                    lstLogin[0].Token = _token;
                    // return lstLogin;
                }

                return(lstLogin);
            }
            catch (Exception ex)
            {
                ErrorLogger.Log($"Something went wrong inside UsersController ValidLogin action: {ex.Message}");
                ErrorLogger.Log(ex.StackTrace);

                Logger.LogError($"Something went wrong inside UsersController ValidLogin action: {ex.Message}");
                return(null);
            }
        }
 public ActionResult List()
 {
     ViewBag.Title       = UtilityService.GetPagetTitlePrefix(ConstantVariableService.FormStateList);
     ViewBag.DisplayOnly = AuthorizeService.CheckDisplayOnly(new[] { AppCompositeRoleViewModel.RoleForManageData });
     ViewBag.user        = User.Identity.Name;
     return(View("~/Views/Authorization/AppCompositeRole/AppCompositeRoleList.cshtml"));
 }
Esempio n. 22
0
        public async Task <IActionResult> Get(string id)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                if (repository.ServiceUser == null)
                {
                    return(Forbid());
                }

                if (id == "me")
                {
                    var result = repository.ServiceUser.FromDal(true);
                    return(Ok(result));
                }


                if (Guid.TryParse(id, out var guid))
                {
                    var isMe = repository.ServiceUser.Guid == guid;
                    if (!isMe && !AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditPlayer))
                    {
                        return(Forbid());
                    }

                    var userModel = await repository.Context.Users.Include(x => x.Role).FirstOrDefaultAsync(x => x.Guid == guid);

                    var result = userModel.FromDal(true);
                    return(Ok(result));
                }

                return(NotFound("User not found"));
            }
        }
Esempio n. 23
0
 public List <CustomerContact> GetCustomerContacts(string customerId)
 {
     if (!AuthorizeService.CheckAdminCookies())
     {
         return(null);
     }
     return(CustomerService.GetCustomerContacts(customerId.TryParseGuid()));
 }
Esempio n. 24
0
 public CustomerContact GetCustomerContact(string contactId)
 {
     if (!AuthorizeService.CheckAdminCookies())
     {
         return(null);
     }
     return(CustomerService.GetCustomerContact(contactId));
 }
Esempio n. 25
0
 public Customer GetCustomer(string customerId)
 {
     if (!AuthorizeService.CheckAdminCookies())
     {
         return(null);
     }
     return(CustomerService.GetCustomer(customerId.TryParseGuid()));
 }
Esempio n. 26
0
 public List <Customer> GetCustomers()
 {
     if (!AuthorizeService.CheckAdminCookies())
     {
         return(null);
     }
     return(new List <Customer>(CustomerService.GetCustomers()));
 }
Esempio n. 27
0
        public ActionResult ViewChangePassword(int idUser)
        {
            AuthorizeService usr = new AuthorizeService();

            ViewBag.UserId   = idUser;
            ViewBag.UserName = usr.getUserName(idUser);
            return(PartialView("_ChangePassword"));
        }
Esempio n. 28
0
 protected void btnChangeAdminPassword_Click(object sender, EventArgs e)
 {
     if (rfvPassword.IsValid && cvPasswords.IsValid)
     {
         CustomerService.ChangePassword("835d82df-aaa6-4d54-a870-8d353e541af9", txtPassword.Text, false);
         AuthorizeService.AuthorizeTheUser("admin", txtPassword.Text, false);
     }
 }
Esempio n. 29
0
        public ActionResult ViewCreateLogin(int idUser)
        {
            AuthorizeService usr = new AuthorizeService();

            ViewBag.UserId   = idUser;
            ViewBag.UserName = usr.getUserName(idUser);
            return(PartialView("_CreateLogin"));
        }
Esempio n. 30
0
 public string AddProduct(Product product)
 {
     if (!AuthorizeService.CheckAdminCookies())
     {
         return(MsgAuthFailed);
     }
     return(ProductService.AddProduct(product, true) != 0 ? string.Format(MsgAddSuccess, product.ProductId) : MsgAddError);
 }