Beispiel #1
0
        public ActionResult Edit(FormCollection formCollection, string filesToUpload, string PIN, string P)
        {
            NullChecker.NullCheck(new object[] { PIN, P });

            var  pin             = EncryptionHelper.Unprotect(PIN);
            var  p               = EncryptionHelper.Unprotect(P);
            Post postEntryToEdit = unitOfWOrk.PostRepository.GetByID(pin);

            if (AuthorizationHelper.isRelevant((int)postEntryToEdit.posterUserID) &&
                pin == p)
            {
                if (TryUpdateModel(postEntryToEdit, "", new string[] { "post" }))
                {
                    if (!String.IsNullOrWhiteSpace(postEntryToEdit.post))
                    {
                        unitOfWOrk.PostRepository.Update(postEntryToEdit);
                    }
                    if (!String.IsNullOrWhiteSpace(filesToUpload))
                    {
                        var fileUploadResult = UploadHelper.UpdateUploadedFiles(filesToUpload, postEntryToEdit.image + postEntryToEdit.document, "Post");
                        postEntryToEdit.image    = fileUploadResult.ImagesToUpload;
                        postEntryToEdit.document = fileUploadResult.DocsToUpload;
                    }
                    unitOfWOrk.PostRepository.Update(postEntryToEdit);
                    unitOfWOrk.Save();
                    UnitOfWork editContext = new UnitOfWork();
                    var        post        = editContext.PostRepository.GetByID(postEntryToEdit.postID);
                    return(Json(new
                    {
                        Success = true,
                        Result = RenderPartialViewHelper.RenderPartialView(this, "PostPartial", post),
                        Message = Resource.Resource.editedSuccessfully
                    }));
                }
                throw new ModelStateException(this.ModelState);
            }
            throw new JsonCustomException(ControllerError.ajaxErrorPostEdit);
        }
Beispiel #2
0
        public async Task GenerateExternalUserName(Guid userProfileId, Guid gameId)
        {
            var user = await this.context.UserProfiles.Include(up => up.ExternalUserNames).FirstOrDefaultAsync(up => up.Id == userProfileId);

            if (user.HasExternalUserName(gameId))
            {
                return;
            }

            var game = await this.context.Games.Include(g => g.GameExternalUserNameGenerator).ThenInclude(geung => geung.ExternalUserNameGenerator).FirstOrDefaultAsync(g => g.Id == gameId);

            var generator = game.GameExternalUserNameGenerator?.ExternalUserNameGenerator;

            if (generator == null)
            {
                return;
            }

            try
            {
                var userNameGenerator = Activator.CreateInstance(Type.GetType(generator.Type), this.context) as IExternalUserNameGenerator;
                var userName          = await userNameGenerator.Create(userProfileId);

                if (userName == null)
                {
                    return;
                }
                var externalUserName = new EF.Models.ExternalUserName(userName.UserName, userName.LogoURL, userName.ServiceName, gameId);
                await this.authorizationService.AddPermission(userProfileId, AuthorizationHelper.GenerateARN(typeof(ExternalUserName), externalUserName.Id.ToString(), Shared.Permissions.ExternalUserName.All));

                user.ExternalUserNames.Add(externalUserName);
                this.context.UserProfiles.Update(user);
            }
            catch (Exception ex)
            {
                Sentry.SentrySdk.CaptureException(ex);
            }
        }
        public void TestMissingPolicy()
        {
            Mock <IAuthorizationPolicyProvider> authorizationPolicyMock = new Mock <IAuthorizationPolicyProvider>();

            authorizationPolicyMock.Setup(x => x.GetPolicyAsync(It.IsAny <string>()))
            .Returns(() =>
            {
                return(Task.FromResult <AuthorizationPolicy>(null));
            });

            Mock <IAuthorizationHandlerProvider> authorizationHandlerMock = new Mock <IAuthorizationHandlerProvider>();
            Mock <HttpContext> httpContextMock = new Mock <HttpContext>();

            ServiceCollection services = new ServiceCollection();

            services.AddSingleton(authorizationPolicyMock.Object);
            services.AddSingleton(authorizationHandlerMock.Object);

            Assert.ThrowsAsync <InvalidOperationException>(
                async() => await AuthorizationHelper.CheckAuthorization(services.BuildServiceProvider(), "test", httpContextMock.Object),
                "No security policy found named 'test'."
                );
        }
        public ActionResult Create([Bind(Include = "sessionSubject,sessionDesc,endDate")] GroupSession groupSessionToCreate, string GId, string filesToUpload)
        {
            NullChecker.NullCheck(new object[] { GId });
            if (ModelState.IsValid)
            {
                var gid   = EncryptionHelper.Unprotect(GId);
                var group = unitOfWork.GroupRepository.GetByID(gid);
                if (group.Admins.Any(a => AuthorizationHelper.isRelevant(a.UserId)))
                {
                    var fileUploadResult = UploadHelper.UpdateUploadedFiles(filesToUpload, null, "GSession");
                    groupSessionToCreate.image    = fileUploadResult.ImagesToUpload;
                    groupSessionToCreate.document = fileUploadResult.DocsToUpload;

                    groupSessionToCreate.groupId   = (int)gid;
                    groupSessionToCreate.startDate = DateTime.UtcNow;
                    unitOfWork.GroupSessionRepository.Insert(groupSessionToCreate);
                    unitOfWork.Save();
                    return(Json(new { Success = true, Url = Url.Action("Detail", new { SsId = groupSessionToCreate.sessionId, GSName = StringHelper.URLName(groupSessionToCreate.sessionSubject) }) }));
                }
                throw new JsonCustomException(ControllerError.ajaxError);
            }
            throw new ModelStateException(this.ModelState);
        }
        public ActionResult Edit(string StId)
        {
            NullChecker.NullCheck(new object[] { StId });
            var StToEdit = unitOfWork.StoreNotExpiredRepository
                           .GetByID((int)EncryptionHelper.Unprotect(StId));

            if (!StToEdit.Admins.Any(c => AuthorizationHelper.isRelevant(c.UserId)))
            {
                return(new RedirectToNotFound());
            }

            CountriesViewModel countries = new CountriesViewModel();

            ViewBag.CountryDropDown = countries.counts(StToEdit.State);
            ViewBag.StateDropDown   = countries.states(StToEdit.State);

            var catss = StToEdit.Categories.Select(u => u.catID);

            ViewData["Cats"]  = String.Join(",", catss);
            ViewData["store"] = StId;

            return(View(StToEdit));
        }
Beispiel #6
0
        public ActionResult Create([Bind(Include = "groupName,groupDesc,isPublic")] Group group, string Cats, string professionTags, string UserTags)
        {
            if (ModelState.IsValid)
            {
                if (AuthorizationHelper.isAdmin())
                {
                    UpSertGroupCats(Cats, group);
                    UpSertGroupProffs(professionTags, group);
                    UpSertGroupAdmins(UserTags, group);
                    UpSertGroupMembers(UserTags, group);
                    group.registerDate = DateTime.UtcNow;

                    unitOfWork.GroupRepository.Insert(group);


                    unitOfWork.Save();

                    return(Json(new { Success = true, Url = Url.Action("GroupPage", new { GId = group.groupId, GName = StringHelper.URLName(group.groupName) }) }));
                }
                throw new JsonCustomException(ControllerError.ajaxError);
            }
            throw new ModelStateException(this.ModelState);
        }
Beispiel #7
0
        public ActionResult ProfilePic(string UId, int x, int y, int w, int h, string picToUpload)
        {
            NullChecker.NullCheck(new object[] { UId });
            var uid = EncryptionHelper.Unprotect(UId);

            if (!AuthorizationHelper.isRelevant((int)uid))
            {
                throw new JsonCustomException(ControllerError.ajaxError);
            }
            UploadHelper.CropImage(x, y, w, h, picToUpload);
            UploadHelper.moveFile(picToUpload, "Profile");
            var user = unitOfWork.ActiveUserRepository.GetByID(uid);

            if (user.image != null)
            {
                UploadHelper.deleteFile(user.image, "Profile");
            }
            user.image = picToUpload;
            unitOfWork.ActiveUserRepository.Update(user);
            unitOfWork.Save();

            return(Json(new { Success = true }));
        }
Beispiel #8
0
        public StrokeDto AddStroke(Guid noteId, [FromBody] NewStrokeInput strokeInput)
        {
            var user = AuthorizationHelper.GetAuthorizedUser();
            var note = user.Notes.FirstOrDefault(n => n.Id == noteId);

            if (strokeInput.Path == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var stroke = note.AddStroke(
                new BrushColor(strokeInput.R, strokeInput.B, strokeInput.G, strokeInput.A)
            {
            },
                new BrushSize(strokeInput.Radius)
            {
            },
                strokeInput.Path);

            var strokeDto = new StrokeDto(stroke.ToData());

            return(strokeDto);
        }
Beispiel #9
0
        public void CreateXacmlJsonMultipleRequest_TC01()
        {
            // Arrange
            List <string> actionTypes = new List <string> {
                "read", "write"
            };
            List <Instance> instances = CreateInstances();

            // Act
            XacmlJsonRequestRoot requestRoot = AuthorizationHelper.CreateMultiDecisionRequest(CreateUserClaims(1), instances, actionTypes);

            // Assert
            // Checks it has the right number of attributes in each category
            Assert.Single(requestRoot.Request.AccessSubject);
            Assert.Equal(2, requestRoot.Request.Action.Count());
            Assert.Equal(3, requestRoot.Request.Resource.Count());
            Assert.Equal(4, requestRoot.Request.Resource.First().Attribute.Count());
            Assert.Equal(6, requestRoot.Request.MultiRequests.RequestReference.Count());
            foreach (var refrenceId in requestRoot.Request.MultiRequests.RequestReference)
            {
                Assert.Equal(3, refrenceId.ReferenceId.Count());
            }
        }
Beispiel #10
0
        public void SetImage()
        {
            //Pega o nome do usuário para exibir na barra de navegação
            SistemaApi username = new SistemaApi();

            try
            {
                username     = AuthorizationHelper.GetSystem();
                ViewBag.User = username.Usuario.ChaveAmericas;
                if (username != null)
                {
                    var imgUser = AuthorizationHelper.GetUserImage(username.Usuario.ChaveAmericas);
                    ViewBag.UserPhoto = imgUser;
                }
            }
            catch
            {
                var imgUser = AuthorizationHelper.GetUserImage("");

                ViewBag.User      = "";
                ViewBag.UserPhoto = imgUser;
            }
        }
        public ActionResult LogoPic(int x, int y, int w, int h, string picToUpload, string company)
        {
            NullChecker.NullCheck(new object[] { company });

            var currentUser   = WebSecurity.CurrentUserId;
            var companyToEdit = unitOfWork.NotExpiredCompanyRepository
                                .GetByID(EncryptionHelper.Unprotect(company));

            if (companyToEdit.Admins.Any(a => AuthorizationHelper.isRelevant(a.UserId)))
            {
                UploadHelper.CropImage(x, y, w, h, picToUpload);
                UploadHelper.moveFile(picToUpload, "Company");
                if (companyToEdit.logo != null)
                {
                    UploadHelper.deleteFile(companyToEdit.logo, "Company");
                }
                companyToEdit.logo = picToUpload;
                unitOfWork.CompanyRepository.Update(companyToEdit);
                unitOfWork.Save();
                return(Json(new { Success = true }));
            }
            throw new JsonCustomException(ControllerError.ajaxError);
        }
Beispiel #12
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            log.Debug("OnActionExecuting called");

            var resultadoAutorizacao = CheckUserAuthorization();

            log.Debug("resultadoAutorizacao: " + resultadoAutorizacao);

            switch (resultadoAutorizacao)
            {
            case TipoResultadoAutorizacao.AUTORIZADO:
                break;

            case TipoResultadoAutorizacao.NAO_AUTENTICADO:
                string url = $"{FormsAuthentication.LoginUrl}?returnUrl=/{filterContext.RouteData.Values["controller"]}/{filterContext.RouteData.Values["action"]}";
                filterContext.Result = new RedirectResult(url);
                break;

            case TipoResultadoAutorizacao.USUARIO_INATIVO:
                TempData["_AuthenticationError"] = "Usuário Inativo";
                filterContext.Result             = new RedirectResult("/Login/UnauthorizedAccess");
                AuthorizationHelper.LimparRegistroAutenticacao();
                break;

            case TipoResultadoAutorizacao.USUARIO_NAO_CADASTRADO:
                TempData["_AuthenticationError"] = "Usuário não cadastrado";
                filterContext.Result             = new RedirectResult("/Login/UnauthorizedAccess");
                AuthorizationHelper.LimparRegistroAutenticacao();

                break;

            default:
                break;
            }

            base.OnActionExecuting(filterContext);
        }
Beispiel #13
0
        public async Task <string> SendMessageAsync()
        {
            var requestData = new RequestData();

            requestData.PhoneNumber = new List <string>()
            {
                Config._testMobile
            };
            requestData.ExtendCode  = Config._testExtend;
            requestData.MessageBody = new MessageBody();
            requestData.MessageBody.TemplateName  = Config._testTemplateName;
            requestData.MessageBody.TemplateParam = new Dictionary <string, string>();

            var token = AuthorizationHelper.CreateSASToken(Config._keyValue, Config._keyName, TimeSpan.FromSeconds(30));


            string jsonPayload = JsonConvert.SerializeObject(requestData);

            var request = new HttpRequestMessage(HttpMethod.Post, $"{Config._endpoint}")
            {
                Headers =
                {
                    { HttpRequestHeader.Accept.ToString(), "application/json"        },
                    { "MS-RequestId",                      Guid.NewGuid().ToString() },
                    { "Account",                           Config._testCcsAccount    },
                    { "Authorization",                     token                     }
                },
                Content = new StringContent(jsonPayload, Encoding.UTF8)
            };


            var response = await _client.SendAsync(request);

            var json = await response.Content.ReadAsStringAsync();

            return(json);
        }
Beispiel #14
0
        public ActionResult Create(tblPerfis trainingProfile)
        {
            var username = "";

            try
            {
                username = AuthorizationHelper.GetSystem().Usuario.ChaveAmericas;
            }
            catch
            {
                username = "";
            }

            var exits = _trainingProfile.checkIfTrainingProfileAlreadyExits(trainingProfile);

            trainingProfile.UsuarioCriacao = username;
            trainingProfile.DataCriacao    = DateTime.Now;
            trainingProfile.Tipo           = "T";

            if (ModelState.IsValid)
            {
                if (!exits)
                {
                    _trainingProfile.CreateTrainingProfile(trainingProfile);

                    return(RedirectToAction("Index"));
                }
            }


            if (exits)
            {
                ModelState.AddModelError("Nome", "Perfil de Treinamento já existe");
            }

            return(View("Create"));
        }
        public ActionResult <Order> Responce(Order order)
        {
            if (order == null)
            {
                return(new NoContentResult());
            }

            bool hasAutorId = AuthorizationHelper.TryGetCurrentUserId(HttpContext?.User, out int authorId);

            if (!hasAutorId)
            {
                return(new StatusCodeResult(StatusCodes.Status401Unauthorized));
            }

            var  originalOrder    = _orderDirectory.GetOrder(order.Id);
            bool isOrderChanged   = !order.IsEquals(originalOrder);
            bool isNotValidStatus = !string.Equals(originalOrder?.Status, OrderStatus.ACTIVE, System.StringComparison.OrdinalIgnoreCase);

            if (isOrderChanged || isNotValidStatus)
            {
                return(new StatusCodeResult(StatusCodes.Status403Forbidden));
            }

            order.ClientId = authorId;
            order.Status   = OrderStatus.RESPONSED;

            bool succeed = _orderDirectory.TryPutOrder(order);

            if (succeed)
            {
                return(new ActionResult <Order>(order));
            }
            else
            {
                return(new BadRequestResult());
            }
        }
Beispiel #16
0
        private async Task <TeamMembership> DangerouslyCreateTeamMembership(Team team, Guid userId, Guid roleId, string notes)
        {
            var role = await context.TeamRoles.FirstOrDefaultAsync(tr => tr.Id == roleId);

            if (role == null)
            {
                throw new NoNullAllowedException("Role cannot be null");
            }

            var membership = team.AddMember(userId, roleId, notes);

            if (membership != null)
            {
                var permissions          = role.Permissions.Select(p => AuthorizationHelper.GenerateARN(typeof(Team), team.Id.ToString(), p)).ToList();
                var membershipPermission = AuthorizationHelper.GenerateARN(typeof(TeamMembership), membership.Id.ToString(), Shared.Permissions.TeamMembership.All);

                await this.authorizationService.AddPermission(userId, membershipPermission);

                await this.authorizationService.AddPermission(userId, permissions);

                await this.backgroundWorker.SendMessage(this.queues.Contact, new DTO.Marketing.ContactSync(userId), 5);
            }

            var gameId = team.Competition?.GameId;

            if (!gameId.HasValue)
            {
                gameId = (await context.Competitions.Include(c => c.Game).FirstOrDefaultAsync(c => c.Id.Equals(team.CompetitionId)))?.GameId;
            }

            if (gameId.HasValue)
            {
                await this.userUtils.GenerateExternalUserName(userId, gameId.Value);
            }

            return(membership);
        }
        public ActionResult <Order> Post(Order order)
        {
            if (order == null)
            {
                return(new NoContentResult());
            }

            bool succeed = false;

            if (AuthorizationHelper.TryGetCurrentUserId(HttpContext?.User, out int id))
            {
                order.AuthorId = id;
                succeed        = _orderDirectory.TryAddOrder(order);
            }

            if (succeed)
            {
                return(new ActionResult <Order>(order));
            }
            else
            {
                return(new BadRequestResult());
            }
        }
Beispiel #18
0
        private async Task <JWTAuthorizationResponse> GetAuthorizationResponse(string username, string password)
        {
            var identity = await GetIdentity(username, password);

            if (identity == null)
            {
                return(null);
            }
            var jwt = new JwtSecurityToken(
                issuer: AuthorizationHelper.JWT_ISSUER,
                audience: AuthorizationHelper.JWT_AUDIENCE,
                notBefore: DateTime.UtcNow,
                claims: identity.Claims,
                expires: DateTime.UtcNow.Add(AuthorizationHelper.JWT_LIFETIME),
                signingCredentials: new SigningCredentials(AuthorizationHelper.GetSymmetricJWTSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new JWTAuthorizationResponse
            {
                Access_Token = encodedJwt,
                UserName = identity.Name,
                Roles = identity.Claims.Where(s => s.Type == ClaimsIdentity.DefaultRoleClaimType).Select(s => s.Value).ToList()
            });
        }
Beispiel #19
0
    protected void Page_Init(object sender, EventArgs e)
    {
        if (UIContext.EditedObject != null)
        {
            accountInfo = (AccountInfo)UIContext.EditedObject;

            // Initialize account selector
            accountSelector.UniSelector.Enabled                     = AuthorizationHelper.AuthorizedModifyContact(false);
            accountSelector.UniSelector.OnItemsSelected            += UniSelector_OnItemsSelected;
            accountSelector.UniSelector.SelectionMode               = SelectionModeEnum.MultipleButton;
            accountSelector.UniSelector.DialogButton.ResourceString = "om.account.addaccount";

            // Setup UniGrid
            gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
            gridElem.OnAction            += gridElem_OnAction;
            gridElem.ZeroRowsText         = GetString("om.account.noaccountsfound");

            // Initialize dropdown lists
            if (!RequestHelper.IsPostBack())
            {
                drpAction.Items.Add(new ListItem(GetString("general." + Action.SelectAction), Convert.ToInt32(Action.SelectAction).ToString()));
                drpAction.Items.Add(new ListItem(GetString("general.remove"), Convert.ToInt32(Action.Remove).ToString()));
                drpWhat.Items.Add(new ListItem(GetString("om.account." + What.Selected), Convert.ToInt32(What.Selected).ToString()));
                drpWhat.Items.Add(new ListItem(GetString("om.account." + What.All), Convert.ToInt32(What.All).ToString()));
            }

            // Isn't child of someone else
            accountSelector.WhereCondition = "AccountSubsidiaryOfID IS NULL";
            // And isn't recursive parent of edited account
            accountSelector.WhereCondition = SqlHelper.AddWhereCondition(accountSelector.WhereCondition, "AccountID NOT IN (SELECT * FROM Func_OM_Account_GetSubsidiaryOf(" + accountInfo.AccountID + ", 1))");
        }
        else
        {
            StopProcessing = true;
        }
    }
Beispiel #20
0
        public async Task <string> SendMessageAsync(string json)
        {
            var token = AuthorizationHelper.CreateSASToken(Config._keyValue, Config._keyName, TimeSpan.FromSeconds(30));


            var request = new HttpRequestMessage(HttpMethod.Post, $"{Config._endpoint}")
            {
                Headers =
                {
                    { HttpRequestHeader.Accept.ToString(), "application/json"        },
                    { "MS-RequestId",                      Guid.NewGuid().ToString() },
                    { "Account",                           Config._testCcsAccount    },
                    { "Authorization",                     token                     }
                },
                Content = new StringContent(json, Encoding.UTF8)
            };


            var response = await _client.SendAsync(request);

            var ret = await response.Content.ReadAsStringAsync();

            return(ret);
        }
        public ActionResult Edit(string SsId, string filesToUpload)
        {
            NullChecker.NullCheck(new object[] { SsId });
            var session = unitOfWork.GroupSessionRepository.GetByID(EncryptionHelper.Unprotect(SsId));

            if (TryUpdateModel(session, "", new string[] { "sessionSubject", "sessionDesc", "endDate" }))
            {
                if (session.Group.Admins.Any(a => AuthorizationHelper.isRelevant(a.UserId)))
                {
                    if (ITTConfig.CurrentCultureIsNotEN)
                    {
                        var fileUploadResult = UploadHelper.UpdateUploadedFiles(filesToUpload, session.image + session.document, "GSession");

                        session.image    = fileUploadResult.ImagesToUpload;
                        session.document = fileUploadResult.DocsToUpload;
                    }
                    unitOfWork.GroupSessionRepository.Update(session);
                    unitOfWork.Save();
                    return(Json(new { Success = true, Url = Url.Action("Detail", new { SsId = session.sessionId, GSName = StringHelper.URLName(session.sessionSubject) }) }));
                }
                throw new JsonCustomException(ControllerError.ajaxError);
            }
            throw new ModelStateException(this.ModelState);
        }
Beispiel #22
0
        private void OnLogin(object sender, RoutedEventArgs e)
        {
            var userName = UserNameTxt.Text.Trim();

            userName = StringUtil.CheckPhoneNum(userName) ? "+86" + userName : userName;
            var password = PasswordTxt.Password.Trim();
            var captcha  = CaptchaTxt.Text.Trim();

            LoadingIcon.Display();
            AuthorizationHelper.Login(LoginType.ZhiHu, new ZhiHuLoginInfo()
            {
                Captcha = NeedCaptcha ? captcha : null, UserName = userName, Password = password
            }, loginSuccess =>
            {
                if (loginSuccess)
                {
                    PopupMessage.DisplayMessageInRes("LoginSuccess");
                    var info = StorageInfo.Instance.ZhiHuAuthoInfo;
                    if (info == null)
                    {
                        return;
                    }

                    LLQNotifier.Default.Notify(new LoginEvent()
                    {
                        IsLogin = true, UserPhotoUrl = info.avatar
                    });
                    Hide();
                }
                else
                {
                    GetCaptchaImage();
                }
                LoadingIcon.Hide();
            });
        }
Beispiel #23
0
        public async Task <bool> CanReport(Guid matchSeriesId, Guid userProfileId)
        {
            var matchSeries = await this.alexandriaContext.MatchSeries
                              .Include(ms => ms.MatchParticipants)
                              .ThenInclude(mp => mp.Team)
                              .ThenInclude(t => t.TeamMemberships)
                              .ThenInclude(tm => tm.TeamRole)
                              .FirstOrDefaultAsync(ms => ms.Id == matchSeriesId);

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

            var teamMemberships = matchSeries.MatchParticipants.Select(mp => mp.Team).SelectMany(t => t.TeamMemberships);
            var teamMembership  = teamMemberships.FirstOrDefault(tm => tm.UserProfileId == userProfileId);

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

            return(await this.authorizationService.Can(userProfileId, AuthorizationHelper.GenerateARN(typeof(Team), teamMembership.TeamId.ToString(), Shared.Permissions.Team.ReportMatchResult)));
        }
        private static AuthorizationHelper GetAuthorizationHelper(
            bool featureCheckerValue,
            bool isGranted)
        {
            var featureChecker = Substitute.For <IFeatureChecker>();

            featureChecker.GetValueAsync(Arg.Any <string>()).Returns(featureCheckerValue.ToString().ToLower());
            featureChecker.IsEnabledAsync(Arg.Any <string>()).Returns(featureCheckerValue);

            var permissionChecker = Substitute.For <IPermissionChecker>();

            permissionChecker.IsGrantedAsync(Arg.Any <string>()).Returns(isGranted);

            var configuration = Substitute.For <IAuthorizationConfiguration>();

            configuration.IsEnabled.Returns(true);

            var authorizeHelper = new AuthorizationHelper(featureChecker, configuration)
            {
                PermissionChecker = permissionChecker
            };

            return(authorizeHelper);
        }
        public ActionResult Delete(string SsId, string S)
        {
            NullChecker.NullCheck(new object[] { SsId, S });
            var ssid         = EncryptionHelper.Unprotect(SsId);
            var s            = EncryptionHelper.Unprotect(S);
            var sessionToDel = unitOfWork.GroupSessionRepository.GetByID(ssid);

            if (sessionToDel.Group.Admins.Any(a => AuthorizationHelper.isRelevant(a.UserId)) && ssid == s)
            {
                var urlparm = sessionToDel.Group.groupName;
                //sessionToDel.Offers.SelectMany(o => o.Likes.Select(l=>l.likeID as object)).ToList().ForEach(unitOfWork.LikeRepository.Delete);
                //sessionToDel.Offers.SelectMany(c => c.Comments.SelectMany(l => l.Likes.Select(f => f.likeID as object))).ToList().ForEach(unitOfWork.LikeRepository.Delete);
                //sessionToDel.Offers.SelectMany(c => c.Comments.Select(f => f.commentID as object)).ToList().ForEach(unitOfWork.CommentRepository.Delete);
                sessionToDel.Offers.Select(o => o.offerId as object).ToList().ForEach(unitOfWork.GroupSessionOfferRepository.Delete);
                var fileUploadResult = UploadHelper.UpdateUploadedFiles(String.Empty, sessionToDel.image + sessionToDel.document, "GSession");
                if (String.IsNullOrEmpty(fileUploadResult.ImagesToUpload) && String.IsNullOrEmpty(fileUploadResult.DocsToUpload))
                {
                    unitOfWork.GroupSessionRepository.Delete(sessionToDel);
                    unitOfWork.Save();
                }
                return(Json(new { Success = true, Url = Url.Action("GroupPage", "Group", new { GId = sessionToDel.groupId, GName = StringHelper.URLName(urlparm) }) }));
            }
            throw new JsonCustomException(ControllerError.ajaxError);
        }
Beispiel #26
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authContext,
                                                             PlayerCanSeePuzzleRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Puzzle puzzle = await AuthorizationHelper.GetPuzzleFromContext(authContext);

            Event thisEvent = await AuthorizationHelper.GetEventFromContext(authContext);

            if (thisEvent != null && puzzle != null)
            {
                Team team = await UserEventHelper.GetTeamForPlayer(dbContext, thisEvent, puzzleUser);

                if (team != null)
                {
                    IQueryable <PuzzleStatePerTeam> statesQ = PuzzleStateHelper.GetFullReadOnlyQuery(dbContext, thisEvent, puzzle, team);

                    if (statesQ.FirstOrDefault().UnlockedTime != null || thisEvent.AreAnswersAvailableNow)
                    {
                        authContext.Succeed(requirement);
                    }
                }
            }
        }
Beispiel #27
0
        public static async Task <object> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string token = req.Headers.Authorization.ToString();

            if (!AuthorizationHelper.Authorized(token, new string[] { Role.Manager }))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Unauthorized!"));
            }


            //We retrieve the userName field, which comes as a parameter to the function, by deserializing req.Content.
            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data     = JsonConvert.DeserializeObject(jsonContent);
            string  branchID = data.branchID;

            //If there is no username, we return the error message.
            try
            {
                User[] allUsers = null;
                //We get the Connection String in the Function App Settings section we defined.
                var str = Environment.GetEnvironmentVariable("sqldb_connection");

                using (SqlConnection connection = new SqlConnection(str))
                {
                    string text = @"SELECT UserID, email, Firstname, Lastname, Position FROM Users " +
                                  "WHERE branchID = @branchID AND Role NOT IN ('Owner', 'Manager')";

                    SqlCommand command = new SqlCommand(text, connection);
                    command.Parameters.AddWithValue("@branchID", branchID);
                    connection.Open();

                    using (SqlDataReader oReader = command.ExecuteReader())
                    {
                        log.LogInformation("C# HTTP trigger function processed a request. 6");
                        var list = new List <User>();
                        while (oReader.Read())
                        {
                            list.Add(new User
                            {
                                UserID    = oReader["UserID"].ToString(),
                                email     = oReader["email"].ToString(),
                                Firstname = oReader["Firstname"].ToString(),
                                Lastname  = oReader["Lastname"].ToString(),
                                Position  = oReader["Position"].ToString()
                            });
                            allUsers = list.ToArray();
                        }

                        connection.Close();
                    }
                }
                return(req.CreateResponse(HttpStatusCode.OK, allUsers));
            }
            catch
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Something went wrong!"));
            }
        }
 public IsEventAdminOrPlayerOnTeamHandler_Play(AuthorizationHelper authHelper)
 {
     this.authHelper = authHelper;
 }
 public PublisherServiceTests()
 {
     AuthorizationHelper.SetupGoogleAuthCredentials();
 }
Beispiel #30
0
        public IActionResult Put([FromBody] RightsModel fromBodyRightsModel)
        {
            // List of messages to return to the client
            var messages = new List <Message>();

            // Authentication
            var controllerHelper = new ControllerHelper(context);
            var authUserModel    = controllerHelper.Authenticate(HttpContext.User.Identity as ClaimsIdentity);

            if (authUserModel == null)
            {
                return(Unauthorized());
            }

            // Authorization
            if (!AuthorizationHelper.IsAuthorized(authUserModel, (long)SystemDatasetsEnum.Rights, RightsEnum.CRU))
            {
                return(Forbid());
            }

            #region VALIDATIONS

            // Received rights ApplicationId must be the same as of authorized user
            var sharedValidationHelper = new SharedValidationHelper();
            messages = sharedValidationHelper.ValidateApplicationId(fromBodyRightsModel.ApplicationId, authUserModel.ApplicationId);
            if (messages.Count != 0)
            {
                return(BadRequest(messages));
            }
            fromBodyRightsModel.Application = authUserModel.Application;

            // Rights must already exist in the database
            var rightsRepository = new RightsRepository(context);
            var rightsModel      = rightsRepository.GetById(authUserModel.ApplicationId, fromBodyRightsModel.Id);
            if (rightsModel == null)
            {
                messages.Add(new Message(MessageTypeEnum.Error,
                                         4003,
                                         new List <string>()
                {
                    fromBodyRightsModel.Application.LoginApplicationName,
                    fromBodyRightsModel.Id.ToString()
                }));
                Logger.LogMessagesToConsole(messages);
                return(BadRequest(messages));
            }

            // If the rights name was changed, the new one must be unique
            if (rightsModel.Name != fromBodyRightsModel.Name)
            {
                var sameNameRights = rightsRepository.GetByApplicationIdAndName(authUserModel.ApplicationId, fromBodyRightsModel.Name);
                if (sameNameRights.Count() > 0)
                {
                    messages.Add(new Message(MessageTypeEnum.Error,
                                             4001,
                                             new List <string>()
                    {
                        fromBodyRightsModel.Name
                    }));
                    return(BadRequest(messages));
                }
            }

            // Rights data validity and logic validity
            messages = sharedValidationHelper.ValidateRights(authUserModel.Application.ApplicationDescriptor,
                                                             fromBodyRightsModel.DataDictionary);
            if (messages.Count != 0)
            {
                return(BadRequest(messages));
            }

            #endregion

            rightsRepository.SetNameAndData(rightsModel, fromBodyRightsModel.Name, fromBodyRightsModel.DataDictionary);
            messages.Add(new Message(MessageTypeEnum.Info,
                                     4007,
                                     new List <string>()
            {
                fromBodyRightsModel.Name
            }));
            return(Ok(messages));
        }