Пример #1
0
        public IActionResult Delete(string id)
        {
            var post = _postRepository.GetById(id);

            if (post == null)
            {
                return(NotFound(new Message("No such post with this id: " + id)));
            }

            //Check if post is being deleted by its owner or by admin
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAdmin(tokenUser) && !AuthorizationHelpers.IsAuthorizedUser(tokenUser, post.OwnerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Update table
            if (_postRepository.Delete(post))
            {
                return(Ok(new Message("Post with title: " + post.Title + " and with id: " + post.Id + " deleted Successfully")));
            }

            return(BadRequest(new Message("Error when updating post")));
        }
Пример #2
0
        public IActionResult Delete(string id)
        {
            //Get comment from table
            var comment = _commentRepository.GetById(id);

            //Check if such comment exists
            if (comment == null)
            {
                return(BadRequest(new Message("The comment with id: " + id + " doesn't exist.")));
            }

            var tokenUser = HttpContext.User;

            //If request is not sent by owner or by admin, finish here
            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, comment.OwnerId) && !AuthorizationHelpers.IsAdmin(tokenUser))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Update table
            if (_commentRepository.Delete(comment))
            {
                return(Ok(new Message("Comment with id: " + id + " deleted successfully")));
            }

            return(BadRequest(new Message("Error when deleting comment with id: " + id)));
        }
Пример #3
0
        public IActionResult GetByOwnerId(string ownerId,
                                          [FromQuery] int limit,
                                          [FromQuery] bool oldest)
        {
            //Check if request is sent by owner of the posts or by admin
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAdmin(tokenUser) && !AuthorizationHelpers.IsAuthorizedUser(tokenUser, ownerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Create queryable object for limitations and order specifications
            var postsQueryable = _postRepository.Where(p => p.OwnerId == ownerId);

            //Order
            postsQueryable = oldest ? postsQueryable.OrderBy(p => p.SubmitTime) : postsQueryable.OrderByDescending(p => p.SubmitTime);

            //Limitation
            if (limit > 0)
            {
                postsQueryable = postsQueryable.Take(limit);
            }

            return(Ok(postsQueryable.Select(p => _mapper.Map <PostOutDto>(p))));
        }
Пример #4
0
        public ActionResult <CommentOutDto> Update(string id, [FromBody] CommentUpdateDto commentInDto)
        {
            var comment = _commentRepository.GetById(id);

            //Check if this comment exists
            if (comment == null)
            {
                return(BadRequest(new Message("The comment with id: " + id + " doesn't exist.")));
            }

            var tokenUser = HttpContext.User;

            //If request is not sent by owner, finish here
            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, comment.OwnerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            if (!string.IsNullOrEmpty(commentInDto.Content))
            {
                comment.Content = commentInDto.Content;
            }

            //Update table
            if (_commentRepository.Update(comment))
            {
                var commentOutDto = _mapper.Map <CommentOutDto>(comment);

                return(Ok(commentOutDto));
            }

            return(BadRequest(new Message("Error when updating comment with id: " + id)));
        }
Пример #5
0
        public ActionResult <MainCategoryOutDto> Update(string id, [FromBody] MainCategoryCreateDto mainCategoryIn)
        {
            //Check if request is sent by admin.
            if (!AuthorizationHelpers.IsAdmin(HttpContext.User))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            var mainCategory = _mainCategoryRepository.GetById(id);

            if (mainCategory == null)
            {
                return(NotFound(new Message("There is no main category with id: " + id)));
            }

            if (!string.IsNullOrEmpty(mainCategoryIn.Name))
            {
                mainCategory.Name = mainCategoryIn.Name;
            }

            if (_mainCategoryRepository.Update(mainCategory))
            {
                var mainCategoryOutDto = _mapper.Map <MainCategoryOutDto>(mainCategory);

                return(Ok(mainCategoryOutDto));
            }

            return(BadRequest(new Message("Error when updating main category with id: " + id)));
        }
Пример #6
0
        public IActionResult Delete(string id)
        {
            //Check if token is given by admin or authorized user
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAdmin(tokenUser) && !AuthorizationHelpers.IsAuthorizedUser(tokenUser, id))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Find user in table
            var user = _userRepository.Where(u => u.Id == id).Include(u => u.Posts).FirstOrDefault();

            //Check if such user exists
            if (user == null)
            {
                return(BadRequest(new Message("No such user with this id: " + id)));
            }

            if (_userRepository.Delete(user))
            {
                return(Ok(new Message("User with email: " + user.Email + ", id: " + id + " deleted successfully")));
            }

            return(BadRequest(new Message("Error when deleting user with id: " + id)));
        }
Пример #7
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary["as:client_id"];

            if (string.IsNullOrWhiteSpace(clientId))
            {
                return;
            }

            var refreshTokenId       = Guid.NewGuid().ToString("N");
            var refreshTokenLifetime = context.OwinContext.Get <string>("as:clientRefreshTokenLifetime");
            var token = new RefreshToken
            {
                Id = AuthorizationHelpers.GetHash(refreshTokenId),
                ClientApplicationId = clientId,
                Subject             = context.Ticket.Identity.Name,
                IssuedAt            = DateTime.UtcNow,
                ExpiresAt           = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifetime))
            };

            context.Ticket.Properties.IssuedUtc  = token.IssuedAt;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresAt;

            token.ProtectedTicket = context.SerializeTicket();

            if (await _userRepository.TryAddRefreshTokenAsync(token))
            {
                context.SetToken(refreshTokenId);
            }
        }
        public DeliveryStateControllerTests(ServerFactory serverFactory)
        {
            _client = serverFactory.CreateClient();

            _userToken    = AuthorizationHelpers.GenerateTokenForRole(AuthorizationConstants.Claims.UserClaim);
            _partnerToken = AuthorizationHelpers.GenerateTokenForRole(AuthorizationConstants.Claims.PartnerClaim);
        }
Пример #9
0
        public ActionResult <MainCategoryOutDto> Create([FromBody] MainCategoryCreateDto mainCategoryIn)
        {
            //Check if request is sent by admin.
            if (!AuthorizationHelpers.IsAdmin(HttpContext.User))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Check if request is valid.
            if (string.IsNullOrEmpty(mainCategoryIn.Name))
            {
                return(BadRequest(new Message("Please give a valid name.")));
            }

            if (_mainCategoryRepository.Where(mc => mc.Name == mainCategoryIn.Name).Any())
            {
                return(BadRequest(new Message("There is already a main category with name: " + mainCategoryIn.Name)));
            }

            var mainCategory = _mapper.Map <MainCategory>(mainCategoryIn);

            if (_mainCategoryRepository.Add(mainCategory))
            {
                var mainCategoryOutDto = _mapper.Map <MainCategoryOutDto>(mainCategory);

                return(Ok(mainCategoryOutDto));
            }

            return(BadRequest(new Message("Error when creating main category")));
        }
Пример #10
0
        public ActionResult <UserOutDto> Get(string id,
                                             [FromQuery] bool posts,
                                             [FromQuery] bool likedPosts,
                                             [FromQuery] bool followings,
                                             [FromQuery] bool followers,
                                             [FromQuery] bool category)
        {
            //Check if token is given by admin or authorized user
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAdmin(tokenUser) && !AuthorizationHelpers.IsAuthorizedUser(tokenUser, id))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Initialize a queryable object for further include operations.
            var userQueryable = _userRepository.Where(u => u.Id == id);

            var rawUser = userQueryable.FirstOrDefault();

            //Check if there exists a user with given id
            if (rawUser == null)
            {
                return(NotFound(new Message("No such user with this id: " + id)));
            }

            if (posts)
            {
                userQueryable = userQueryable.Include(u => u.Posts);
            }

            if (likedPosts)
            {
                userQueryable = userQueryable.Include(u => u.LikedPosts).ThenInclude(lp => lp.Post);
            }

            if (followings)
            {
                userQueryable = userQueryable.Include(u => u.Followings).ThenInclude(uf => uf.Followed);
            }

            if (followers)
            {
                userQueryable = userQueryable.Include(u => u.Followers).ThenInclude(uf => uf.Follower);
            }

            if (category)
            {
                userQueryable = userQueryable.Include(u => u.InterestedCategories).ThenInclude(ic => ic.Category);
            }

            //Get the user object
            var user = userQueryable.FirstOrDefault();

            //Prepare dto object
            var userOutDto = _mapper.Map <UserOutDto>(user);

            return(userOutDto);
        }
Пример #11
0
        public IActionResult UnlikePost(UserLikePostInDto userLikePostDto)
        {
            //Check if inputs are valid
            if (string.IsNullOrEmpty(userLikePostDto.UserId))
            {
                return(BadRequest(new Message("Please give valid user id.")));
            }

            if (string.IsNullOrEmpty(userLikePostDto.PostId))
            {
                return(BadRequest(new Message("Please give valid post id.")));
            }

            var userIn = _userRepository.GetById(userLikePostDto.UserId);

            //Check if user is deleted
            if (userIn == null)
            {
                return(BadRequest(new Message("User : "******" is no longer exists")));
            }

            var postIn = _postRepository.GetById(userLikePostDto.PostId);

            //Check if post is deleted
            if (postIn == null)
            {
                return(BadRequest(new Message("Post : " + userLikePostDto.PostId + " is no longer exists")));
            }

            //Check if token is given by authorized user
            var tokenUser = HttpContext.User;

            //If follower user is not authorized, finish here
            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, userLikePostDto.UserId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Get the user like relation from table
            var userLikePost = _userLikePostRepository
                               .Where(ulp => ulp.UserId == userLikePostDto.UserId && ulp.PostId == userLikePostDto.PostId)
                               .FirstOrDefault();

            //Check if there exists such relation
            if (userLikePost == null)
            {
                return(BadRequest(new Message("User : "******" hasn't been liked the post : " +
                                              userLikePostDto.PostId)));
            }

            //Delete relation from table
            if (_userLikePostRepository.Delete(userLikePost))
            {
                return(Ok(new Message("User : "******" is not being liked the post : " +
                                      userLikePostDto.PostId + " anymore")));
            }

            return(BadRequest(new Message("Error when post unlike with user :"******" and post : " + userLikePostDto.PostId)));
        }
Пример #12
0
        public DeliveryControllerTests(ServerFactory serverFactory)
        {
            _client = serverFactory.CreateClient();

            var token = AuthorizationHelpers.GenerateTokenForRole(AuthorizationConstants.Claims.SystemClaim);

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
        }
Пример #13
0
        public static async Task <bool> OnlineAppInitAsync(bool updateKeys)
        {
            try
            {
                // Call the init method now and request new app keys
                var returnInfo = await AuthorizationHelpers.OnlineAppInitAsync("uwp." + SystemInformation.DeviceFamily.ToLower() + "." + SystemInformation.OperatingSystemVersion, $"{Package.Current.Id.Version.Major}.{Package.Current.Id.Version.Minor}.{Package.Current.Id.Version.Build}.{Package.Current.Id.Version.Revision}", SettingsService.Instance.AppId, updateKeys);

                if (!returnInfo.Successful)
                {
                    await NavigationService.Current.CallMessageDialogAsync("SoundByte cannot load. The following error was returned from the SoundByte server: " + returnInfo.ErrorTitle + "\n\nPlease restart the app and try again. If this error continues, contact us on Twitter @SoundByteUWP or Facebook fb.com/SoundByteUWP.", "Critical Error");

                    // Don't run anything, app will not work.
                    return(false);
                }

                if (updateKeys)
                {
                    if (returnInfo.AppKeys == null)
                    {
                        await NavigationService.Current.CallMessageDialogAsync(
                            "SoundByte cannot load. The following error was returned from the SoundByte server: App Keys not provided.\n\nPlease restart the app and try again. If this error continues, contact us on Twitter @SoundByteUWP or Facebook fb.com/SoundByteUWP.",
                            "Critical Error");

                        // Don't run anything, app will not work.
                        return(false);
                    }

                    // We have keys! Time to update the app
                    var appKeys = returnInfo.AppKeys;

                    AppKeysHelper.SoundCloudClientId       = appKeys.SoundCloudClientId;
                    AppKeysHelper.SoundCloudPlaybackIds    = appKeys.SoundCloudPlaybackIds;
                    AppKeysHelper.YouTubeLoginClientId     = appKeys.YouTubeLoginClientId;
                    AppKeysHelper.YouTubeClientId          = appKeys.YouTubeClientId;
                    AppKeysHelper.FanburstClientId         = appKeys.FanburstClientId;
                    AppKeysHelper.LastFmClientId           = appKeys.LastFmClientId;
                    AppKeysHelper.GoogleAnalyticsTrackerId = appKeys.GoogleAnalyticsTrackerId;
                    AppKeysHelper.AppCenterClientId        = appKeys.AppCenterClientId;
                    AppKeysHelper.HockeyAppClientId        = appKeys.HockeyAppClientId;
                    AppKeysHelper.SoundByteClientId        = appKeys.SoundByteClientId;
                }

                // Update the app ID (this should be the same as before / update to new value)
                SettingsService.Instance.AppId = returnInfo.AppId;

                return(true);
            }
            catch (Exception e)
            {
                await NavigationService.Current.CallMessageDialogAsync(
                    "SoundByte cannot load. The following error was returned from the SoundByte server: " + e.Message +
                    "\n\nPlease restart the app and try again. If this error continues, contact us on Twitter @SoundByteUWP or Facebook fb.com/SoundByteUWP.",
                    "Critical Error");

                // Don't run anything, app will not work.
                return(false);
            }
        }
Пример #14
0
        public IActionResult RemoveUser([FromBody] UserCategoryInDto userCategoryDto)
        {
            //Check if inputs are valid
            if (string.IsNullOrEmpty(userCategoryDto.UserId))
            {
                return(BadRequest(new Message("Please give valid user id")));
            }

            if (string.IsNullOrEmpty(userCategoryDto.CategoryId))
            {
                return(BadRequest(new Message("Please give valid category id")));
            }

            //Check if user is deleted
            var userIn = _userRepository.GetById(userCategoryDto.UserId);

            if (userIn == null)
            {
                return(BadRequest(new Message("User: "******" no longer exists")));
            }

            //Check if category is deleted
            var categoryIn = _categoryRepository.GetById(userCategoryDto.CategoryId);

            if (categoryIn == null)
            {
                return(BadRequest(new Message("Category: " + userCategoryDto.CategoryId + " no longer exists")));
            }

            var tokenUser = HttpContext.User;

            //Check if request is sent by user (follower of the category) .
            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, userCategoryDto.UserId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Get user-category relation from table
            var userCategory = _userCategoryRepository
                               .Where(uc => uc.CategoryId == userCategoryDto.CategoryId && uc.UserId == userCategoryDto.UserId)
                               .FirstOrDefault();

            //If such relation doesn't exist
            if (userCategory == null)
            {
                return(BadRequest(new Message("User : "******" is not following Category : " + userCategoryDto.CategoryId)));
            }

            //Update table
            if (_userCategoryRepository.Delete(userCategory))
            {
                return(Ok(new Message("User : "******" is deleted from Category : " + userCategory.CategoryId)));
            }

            return(BadRequest(new Message("Error when deleting user-category relation")));
        }
Пример #15
0
        public IActionResult GetAll()
        {
            //If request is not sent by admin, finish here
            if (!AuthorizationHelpers.IsAdmin(HttpContext.User))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            return(Ok(_commentRepository.All().Select(c => _mapper.Map <CommentOutDto>(c))));
        }
Пример #16
0
        public IActionResult UnFollow(UserDoFollowDto userFollowDto)
        {
            //Check if inputs are valid
            if (string.IsNullOrEmpty(userFollowDto.FollowerId))
            {
                return(BadRequest(new Message("Please give valid follower id.")));
            }

            if (string.IsNullOrEmpty(userFollowDto.FollowedId))
            {
                return(BadRequest(new Message("Please give valid followed id.")));
            }

            //Check if any of the users is deleted
            if (_userRepository.GetById(userFollowDto.FollowerId) == null)
            {
                return(BadRequest(new Message("Follower user : "******" is no longer exists")));
            }

            if (_userRepository.GetById(userFollowDto.FollowedId) == null)
            {
                return(BadRequest(new Message("Followed user : "******" is no longer exists")));
            }

            //Check if token is given by authorized user
            var tokenUser = HttpContext.User;

            //If follower user is not authorized, finish here
            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, userFollowDto.FollowerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Get follow relation from table
            var userFollow = _userFollowRepository.Where(uf =>
                                                         uf.FollowerId == userFollowDto.FollowerId && uf.FollowedId == userFollowDto.FollowedId)
                             .FirstOrDefault();

            //If such relation doesn't exist , finish here.
            if (userFollow == null)
            {
                return(BadRequest(new Message("User : "******" is not following user : "******"User : "******" is not following user : "******" anymore.")));
            }

            return(BadRequest(new Message("Error when unfollow, with follower :" + userFollowDto.FollowerId + " and followed : " + userFollowDto.FollowedId)));
        }
Пример #17
0
        public IActionResult GetAll()
        {
            //Check if token is given by admin
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAdmin(tokenUser))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            return(Ok(_userRepository.All().Select(u => _mapper.Map <UserOutDto>(u))));
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     using (MiniProfiler.Current.Step("Assiduity Validation Filter"))
     {
         string className = filterContext.GetValue <string>(classNameField);
         // User 2 doesn't have access to xpto.dll
         if (Membership.CurrentUserId == 2 && className == "xpto.dll")
         {
             AuthorizationHelpers.NoPermissions(filterContext);
         }
         base.OnActionExecuting(filterContext);
     }
 }
Пример #19
0
        public IActionResult GetAll()
        {
            //Check if request is sent by admin
            var tokenUser = HttpContext.User;

            //Check if request is sent by admin.
            if (!AuthorizationHelpers.IsAdmin(tokenUser))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            return(Ok(_categoryRepository.All().OrderBy(c => c.Name).Select(c => _mapper.Map <CategoryOutDto>(c)).OrderBy(c => c.Name)));
        }
Пример #20
0
        public async Task <bool> TryCreateClientAsync(ClientApplication clientApplication)
        {
            var existingClient = await _context.ClientApplications.FindAsync(clientApplication.Id);

            if (existingClient != null)
            {
                return(false);
            }

            clientApplication.Secret = AuthorizationHelpers.GetHash(clientApplication.Secret ?? string.Empty);
            _context.ClientApplications.Add(clientApplication);
            return(await _context.SaveChangesAsync() > 0);
        }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Get the field through the helper
        string className = filterContext.GetValue <string>(classNameField);

        // User 2 doesn't have access to xpto.dll
        if (Membership.CurrentUserId == 2 && className == "xpto.dll")
        {
            AuthorizationHelpers.NoPermissions(filterContext);
        }

        base.OnActionExecuting(filterContext);     // Execute base
    }
        public static async Task <bool> OnlineAppInitAsync(bool updateKeys)
        {
            try
            {
                var package = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, 0);

                // Call the init method now and request new app keys
                var returnInfo = await AuthorizationHelpers.OnlineAppInitAsync($"android.{Build.VERSION.Release}", package.VersionName, SettingsService.Instance.AppId, updateKeys);

                if (!returnInfo.Successful)
                {
                    Toast.MakeText(Application.Context, "SoundByte cannot load. The following error was returned from the SoundByte server: " + returnInfo.ErrorTitle + "\n\nPlease restart the app and try again. If this error continues, contact us on Twitter @SoundByteUWP or Facebook fb.com/SoundByteUWP.", ToastLength.Long);
                    // Don't run anything, app will not work.
                    return(false);
                }

                if (updateKeys)
                {
                    if (returnInfo.AppKeys == null)
                    {
                        Toast.MakeText(Application.Context, "SoundByte cannot load. The following error was returned from the SoundByte server: App Keys not provided.\n\nPlease restart the app and try again. If this error continues, contact us on Twitter @SoundByteUWP or Facebook fb.com/SoundByteUWP.", ToastLength.Long);
                        // Don't run anything, app will not work.
                        return(false);
                    }

                    // We have keys! Time to update the app
                    var appKeys = returnInfo.AppKeys;

                    AppKeysHelper.SoundCloudClientId       = appKeys.SoundCloudClientId;
                    AppKeysHelper.SoundCloudPlaybackIds    = appKeys.SoundCloudPlaybackIds;
                    AppKeysHelper.YouTubeLoginClientId     = appKeys.YouTubeLoginClientId;
                    AppKeysHelper.YouTubeClientId          = appKeys.YouTubeClientId;
                    AppKeysHelper.FanburstClientId         = appKeys.FanburstClientId;
                    AppKeysHelper.LastFmClientId           = appKeys.LastFmClientId;
                    AppKeysHelper.GoogleAnalyticsTrackerId = appKeys.GoogleAnalyticsTrackerId;
                    AppKeysHelper.AppCenterClientId        = appKeys.AppCenterClientId;
                    AppKeysHelper.HockeyAppClientId        = appKeys.HockeyAppClientId;
                    AppKeysHelper.SoundByteClientId        = appKeys.SoundByteClientId;
                }

                // Update the app ID (this should be the same as before / update to new value)
                SettingsService.Instance.AppId = returnInfo.AppId;

                return(true);
            }
            catch (Exception e)
            {
                Toast.MakeText(Application.Context, "SoundByte cannot load. The following error was returned from the SoundByte server: " + e.Message + "\n\nPlease restart the app and try again. If this error continues, contact us on Twitter @SoundByteUWP or Facebook fb.com/SoundByteUWP.", ToastLength.Long);
                return(false);
            }
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId, clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (clientId == null)
            {
                context.SetError("client_id_not_found", "ClientID should be sent.");
                return;
            }

            var clientApplication = await _userRepository.FindClientAsync(clientId);

            if (clientApplication == null)
            {
                context.SetError("invalid_client_id", string.Format("Client '{0}' is not registered in the system.", clientId));
                return;
            }

            // Only native apps are supposed to contain a secret
            // Javascript apps cannot store the secret safely anyway
            if (clientApplication.ApplicationType == ApplicationType.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("client_secret_not_found", "Client secret should be sent.");
                    return;
                }

                if (clientApplication.Secret != AuthorizationHelpers.GetHash(clientSecret))
                {
                    context.SetError("invalid_client_secret", "Client secret is invalid");
                    return;
                }
            }

            if (!clientApplication.IsActive)
            {
                context.SetError("client_inactive", "Client is inactive");
                return;
            }

            context.OwinContext.Set("as:clientAllowedOrigin", clientApplication.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifetime", clientApplication.RefreshTokenLifeTime.ToString());
            context.Validated();
        }
Пример #24
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            var hashedTokenId = AuthorizationHelpers.GetHash(context.Token);

            var refreshToken = await _userRepository.FindRefreshTokenAsync(hashedTokenId);

            if (refreshToken != null)
            {
                context.DeserializeTicket(refreshToken.ProtectedTicket);
                await _userRepository.TryRemoveRefreshTokenAsync(hashedTokenId);
            }
        }
Пример #25
0
        public ActionResult <PostOutDto> Update(string id, [FromBody] PostUpdateDto postInDto)
        {
            if (!ModelState.IsValid || postInDto == null)
            {
                return(BadRequest(new Message("Post not valid or null")));
            }

            //Check if there exist a post with {id}
            var post = _postRepository.GetById(id);

            if (post == null)
            {
                return(NotFound(new Message("No such post with this id: " + id)));
            }

            //Check if post is being updated by its owner
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, post.OwnerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            if (!string.IsNullOrWhiteSpace(postInDto.Title))
            {
                post.Title = postInDto.Title;
            }

            if (!string.IsNullOrWhiteSpace(postInDto.Content))
            {
                post.Content = postInDto.Content;
            }

            if (!string.IsNullOrWhiteSpace(postInDto.CategoryId))
            {
                post.Content = postInDto.CategoryId;
            }

            //Save changes
            if (!_postRepository.Update(post))
            {
                return(BadRequest(new Message("Error when updating post")));
            }

            var postOutDto = _mapper.Map <PostOutDto>(post);

            return(postOutDto);
        }
Пример #26
0
        public ActionResult <PostOutDto> Create([FromBody] PostCreateDto postInDto)
        {
            if (!ModelState.IsValid || postInDto == null)
            {
                return(BadRequest(new Message("Post not valid or null")));
            }

            if (string.IsNullOrEmpty(postInDto.OwnerId))
            {
                return(BadRequest(new Message("Please give valid owner Id")));
            }

            if (string.IsNullOrEmpty(postInDto.CategoryId))
            {
                return(BadRequest(new Message("Please give valid category Id")));
            }

            if (string.IsNullOrEmpty(postInDto.Content))
            {
                return(BadRequest(new Message("Please give valid content")));
            }

            if (string.IsNullOrEmpty(postInDto.Title))
            {
                return(BadRequest(new Message("Please give valid title")));
            }

            var postIn = _mapper.Map <Post>(postInDto);

            //Check if post is being created by its owner
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, postInDto.OwnerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Update previous post, current post and owner.
            if (!_postRepository.Add(postIn))
            {
                return(BadRequest(new Message("Error when adding post into table. Please check owner Id")));
            }

            var postOutDto = _mapper.Map <PostOutDto>(postIn);

            return(postOutDto);
        }
        public TransactionPreviewViewModel(Wallet wallet, TransactionInfo info, TransactionBroadcaster broadcaster,
                                           BuildTransactionResult transaction)
        {
            var destinationAmount = transaction.CalculateDestinationAmount().ToDecimal(MoneyUnit.BTC);

            var fee = transaction.Fee;

            BtcAmountText = $"{destinationAmount} bitcoins ";

            FiatAmountText = $"(≈{(destinationAmount * wallet.Synchronizer.UsdExchangeRate).FormattedFiat()} USD) ";

            Labels = info.Labels.Labels.ToArray();

            AddressText = info.Address.ToString();

            ConfirmationTimeText = $"Approximately {TextHelpers.TimeSpanToFriendlyString(info.ConfirmationTimeSpan)} ";

            BtcFeeText = $"{fee.ToDecimal(MoneyUnit.Satoshi)} satoshis ";

            FiatFeeText =
                $"(≈{(fee.ToDecimal(MoneyUnit.BTC) * wallet.Synchronizer.UsdExchangeRate).FormattedFiat()} USD)";

            NextCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                var transactionAuthorizationInfo = new TransactionAuthorizationInfo(transaction);
                var authDialog       = AuthorizationHelpers.GetAuthorizationDialog(wallet, transactionAuthorizationInfo);
                var authDialogResult = await NavigateDialog(authDialog, authDialog.DefaultTarget);

                if (authDialogResult.Result)
                {
                    IsBusy = true;

                    // Dequeue any coin-joining coins.
                    await wallet.ChaumianClient.DequeueAllCoinsFromMixAsync(DequeueReason.TransactionBuilding);

                    await broadcaster.SendTransactionAsync(transactionAuthorizationInfo.Transaction);
                    Navigate().Clear();

                    IsBusy = false;
                }
                else if (authDialogResult.Kind == DialogResultKind.Normal)
                {
                    await ShowErrorAsync("Authorization", "The Authorization has failed, please try again.", "");
                }
            });
        }
        private async Task <bool> AuthorizeAsync(TransactionAuthorizationInfo transactionAuthorizationInfo)
        {
            if (!_wallet.KeyManager.IsHardwareWallet && string.IsNullOrEmpty(_wallet.Kitchen.SaltSoup()))             // Do not show auth dialog when password is empty
            {
                return(true);
            }

            var authDialog       = AuthorizationHelpers.GetAuthorizationDialog(_wallet, transactionAuthorizationInfo);
            var authDialogResult = await NavigateDialogAsync(authDialog, authDialog.DefaultTarget);

            if (!authDialogResult.Result && authDialogResult.Kind == DialogResultKind.Normal)
            {
                await ShowErrorAsync("Authorization", "The Authorization has failed, please try again.", "");
            }

            return(authDialogResult.Result);
        }
        void Verify_IsAuthorized(WindowsGroupPermission configPermissions, TestAuthorizationRequest authorizationRequest)
        {
            //------------Setup for test--------------------------
            var allowedPermissions = AuthorizationHelpers.ToPermissions(authorizationRequest.AuthorizationContext);
            var expected           = authorizationRequest.UserIsInRole && (configPermissions.Permissions & allowedPermissions) != 0;

            var securityService = new Mock <ISecurityService>();

            securityService.SetupGet(p => p.Permissions).Returns(new[] { configPermissions });
            var authorizationService = new TestServerAuthorizationService(securityService.Object);

            //------------Execute Test---------------------------
            var authorized = authorizationService.IsAuthorized(authorizationRequest);

            //------------Assert Results-------------------------
            Assert.AreEqual(expected, authorized, string.Format("\nUserIsInRole: {0}\nAllowed: {1}\nConfig: {2}\nIsServer: {3}\nURL: {4}",
                                                                authorizationRequest.UserIsInRole, allowedPermissions, configPermissions.Permissions, configPermissions.IsServer, authorizationRequest.Url));
        }
Пример #30
0
        /// <summary>
        ///     Handles token refreshing when the access token expires
        /// </summary>
        /// <param name="hex">HttpRequestException exception</param>
        /// <param name="type">The service type</param>
        /// <returns>If we refreshed the refresh token</returns>
        private async Task <bool> HandleAuthTokenRefreshAsync(HttpRequestException hex, int type)
        {
            if (!hex.Message.ToLower().Contains("401") || !IsServiceConnected(type))
            {
                return(false);
            }

            try
            {
                // Get the token
                var userToken = Services.FirstOrDefault(x => x.Service == type)?.UserToken;
                if (userToken != null)
                {
                    var newToken = await AuthorizationHelpers.GetNewAuthTokenAsync(type, userToken.RefreshToken);

                    if (!string.IsNullOrEmpty(newToken.AccessToken))
                    {
                        userToken.AccessToken = newToken.AccessToken;
                    }

                    if (!string.IsNullOrEmpty(newToken.RefreshToken))
                    {
                        userToken.RefreshToken = newToken.RefreshToken;
                    }

                    if (!string.IsNullOrEmpty(newToken.ExpireTime))
                    {
                        userToken.ExpireTime = newToken.ExpireTime;
                    }

                    // Reconnect the service
                    ConnectService(type, userToken);

                    return(true);
                }
            }
            catch (SoundByteException)
            {
                DisconnectService(type, "There is an issue with your '" + type + "' account and SoundByte has disconnected it. To connect your account again, go to 'Accounts' and click login.");
            }

            return(false);
        }