Beispiel #1
0
        public IActionResult Modify([FromBody] GroupModifyDto data)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!context.UserGroups.Any(a => a.GroupId == data.Id && a.UserId == userId && a.Relation == GroupRelation.Owner))
            {
                return(BadRequest());
            }

            var group = context.Groups.FirstOrDefault(a => a.Id == data.Id);

            group.Name        = data.Name;
            group.Description = data.Description;
            group.IsPrivate   = data.IsPrivate;

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #2
0
        public IActionResult AskForInvite([FromBody] GroupInviteDto data)
        {
            var userId = ClaimsReader.GetUserId(Request);
            var group  = context.Groups.SingleOrDefault(a => a.Id == data.Id);

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

            var connection = new UserGroup
            {
                UserId   = userId,
                GroupId  = group.Id,
                Relation = group.IsPrivate ? GroupRelation.Requesting : GroupRelation.User
            };

            context.UserGroups.Add(connection);

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #3
0
        public IActionResult Modify([FromQuery] int id, [FromBody] PostModifyDto data)
        {
            if (string.IsNullOrEmpty(data.Content))
            {
                return(BadRequest());
            }

            var userId = ClaimsReader.GetUserId(Request);
            var post   = context.Posts.FirstOrDefault(a => a.Id == id && a.UserId == userId);

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

            post.EditDate = DateTime.UtcNow;
            post.Content  = data.Content;

            try
            {
                context.SaveChanges();

                return(Ok(new { post.EditDate }));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #4
0
        public IActionResult ResolveGroupInvite([FromBody] GroupInviteResolveDto data)
        {
            var userId     = ClaimsReader.GetUserId(Request);
            var connection = context.UserGroups.SingleOrDefault(a => a.UserId == userId && a.GroupId == data.Id);

            if (data.Value)
            {
                connection.Relation = GroupRelation.User;
            }
            else
            {
                context.UserGroups.Remove(connection);
            }

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #5
0
        public IActionResult ResolveApplication([FromBody] GroupAccessAcceptanceDto data)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!CheckAdminPriviliges(userId, data.GroupId))
            {
                return(BadRequest());
            }

            var targetId   = context.Users.SingleOrDefault(a => a.Id == data.UserId).Id;
            var group      = context.Groups.SingleOrDefault(a => a.Id == data.GroupId);
            var connection = context.UserGroups.SingleOrDefault(a => a.UserId == targetId && a.GroupId == data.GroupId);

            if (data.Accepted)
            {
                connection.Relation = GroupRelation.User;
            }
            else
            {
                context.UserGroups.Remove(connection);
            }

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #6
0
        public IActionResult GetAdminGroupDetails([FromQuery] int id)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!CheckAdminPriviliges(userId, id))
            {
                return(BadRequest());
            }

            var group = context.Groups
                        .Include(a => a.Users)
                        .ThenInclude(a => a.User)
                        .FirstOrDefault(a => a.Id == id);

            var result = new GroupAdminDetailsDto
            {
                Name        = group.Name,
                Description = group.Description,
                IsPrivate   = group.IsPrivate,
                Candidates  = group.Users
                              .Where(a => a.Relation == GroupRelation.Requesting)
                              .Select(a => new GroupCandidateDto
                {
                    UserId    = a.UserId,
                    UserLogin = a.User.Login
                }).ToList()
            };

            return(Ok(result));
        }
Beispiel #7
0
        public IActionResult Get([FromQuery] GroupQueryDto query)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!context.UserGroups.Any(a => a.GroupId == query.GroupId && a.UserId == userId && (a.Relation == GroupRelation.Owner || a.Relation == GroupRelation.User)))
            {
                return(BadRequest());
            }

            var result = context.Posts
                         .Where(a => a.GroupId == query.GroupId)
                         .OrderByDescending(a => a.DateAdded)
                         .ThenBy(a => a.DateAdded)
                         .Skip(query.PageSize * (query.Page - 1))
                         .Take(query.PageSize)
                         .Select(a => new PostDto
            {
                Id        = a.Id,
                DateAdded = a.DateAdded,
                Content   = a.Content,
                EditDate  = a.EditDate,
                IsOwner   = a.UserId == userId,
                Owner     = a.User.Login,
                Comments  = a.Comments.OrderBy(b => b.DateAdded).Select(b => new CommentDto
                {
                    Id        = b.Id,
                    DateAdded = b.DateAdded,
                    Content   = b.Content,
                    IsOwner   = b.UserId == userId,
                    Owner     = b.User.Login
                }).ToList()
            }).ToList();

            return(Ok(result));
        }
        /// <inheritdoc />
        public async Task <HubOnConnectionState> OnConnected([JetBrains.Annotations.NotNull] Hub hubConnectedTo)
        {
            if (hubConnectedTo == null)
            {
                throw new ArgumentNullException(nameof(hubConnectedTo));
            }

            //We should never be here unless auth worked
            //so we can assume that and just try to request character session data
            //for the account.
            CharacterSessionDataResponse characterSessionDataResponse = await SocialToGameClient.GetCharacterSessionDataByAccount(ClaimsReader.GetUserIdInt(hubConnectedTo.Context.User))
                                                                        .ConfigureAwait(false);

            //TODO: To support website chat we shouldn't disconnect just because they don't have a zone session.
            //If the session data request fails we should just abort
            //and disconnect, the user shouldn't be connecting
            if (!characterSessionDataResponse.isSuccessful)
            {
                if (Logger.IsEnabled(LogLevel.Warning))
                {
                    Logger.LogWarning($"Failed to Query SessionData for AccountId: {ClaimsReader.GetUserId(hubConnectedTo.Context.User)} Reason: {characterSessionDataResponse.ResultCode}");
                }

                //TODO: Eventually we don't want to do this.
                return(HubOnConnectionState.Abort);
            }

            //This is ABSOLUTELY CRITICAL we need to validate that the character header they sent actually
            //is the character they have a session as
            //NOT CHECKING THIS IS EQUIVALENT TO LETTING USERS PRETEND THEY ARE ANYONE!
            if (hubConnectedTo.Context.UserIdentifier != characterSessionDataResponse.CharacterId.ToString())
            {
                //We can log account name and id here, because they were successfully authed.
                if (Logger.IsEnabled(LogLevel.Warning))
                {
                    Logger.LogWarning($"User with AccountId: {ClaimsReader.GetUserName(hubConnectedTo.Context.User)}:{ClaimsReader.GetUserId(hubConnectedTo.Context.User)} attempted to spoof as CharacterId: {hubConnectedTo.Context.UserIdentifier} but had session for CharacterID: {characterSessionDataResponse.CharacterId}.");
                }

                return(HubOnConnectionState.Abort);
            }

            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Recieved SessionData: Id: {characterSessionDataResponse.CharacterId} ZoneId: {characterSessionDataResponse.ZoneId}");
            }

            //Registers for lookup so that we can tell where a connection is zone-wise.
            ZoneLookupService.Register(hubConnectedTo.Context.ConnectionId, characterSessionDataResponse.ZoneId);

            //TODO: We should have group name builders. Not hardcoded
            //Join the zoneserver's chat channel group
            await hubConnectedTo.Groups.AddToGroupAsync(hubConnectedTo.Context.ConnectionId, $"zone:{characterSessionDataResponse.ZoneId}", hubConnectedTo.Context.ConnectionAborted)
            .ConfigureAwait(false);

            return(HubOnConnectionState.Success);
        }
Beispiel #9
0
        public IActionResult GetProfile()
        {
            var userId = ClaimsReader.GetUserId(HttpContext.Request);
            var user   = context.Users.SingleOrDefault(x => x.Id == userId);

            return(Ok(new UserProfileDto
            {
                Login = user.Login,
                Email = user.Email,
                ReceiveNotifications = user.ReceiveNotifications
            }));
        }
Beispiel #10
0
        public IActionResult Create([FromBody] CommentCreateDto data)
        {
            if (string.IsNullOrEmpty(data.Content))
            {
                return(BadRequest());
            }

            var userId = ClaimsReader.GetUserId(Request);
            var post   = context.Posts.FirstOrDefault(a => a.Id == data.PostId);

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

            if (!context.UserGroups.Any(a => a.GroupId == post.GroupId && a.UserId == userId && (a.Relation == GroupRelation.Owner || a.Relation == GroupRelation.User)))
            {
                return(BadRequest());
            }

            var comment = new Comment
            {
                DateAdded = DateTime.UtcNow,
                Content   = data.Content,
                PostId    = data.PostId,
                UserId    = userId
            };

            context.Comments.Add(comment);

            try
            {
                context.SaveChanges();

                var user = context.Users.FirstOrDefault(a => a.Id == userId);

                var result = new CommentDto
                {
                    Id        = comment.Id,
                    Content   = comment.Content,
                    DateAdded = comment.DateAdded,
                    Owner     = user.Login,
                    IsOwner   = true
                };

                return(Ok(result));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #11
0
        public IActionResult Details([FromQuery] int id)
        {
            var userId = ClaimsReader.GetUserId(Request);
            var group  = context.Groups.SingleOrDefault(a => a.Id == id);

            var result = new GroupDetailsDto
            {
                Id          = group.Id,
                Name        = group.Name,
                Description = group.Description,
                IsPrivate   = group.IsPrivate,
                IsOwner     = CheckAdminPriviliges(userId, id)
            };

            return(Ok(result));
        }
Beispiel #12
0
        public IActionResult Get([FromQuery] QueryDto query)
        {
            var userId          = ClaimsReader.GetUserId(Request);
            var formattedFilter = string.IsNullOrEmpty(query.Filter) ? string.Empty : query.Filter.ToLower();

            var result = context.Groups
                         .OrderBy(a => a.Id)
                         .Where(a => !a.IsPrivate && a.Name.ToLower().Contains(formattedFilter) && !a.Users.Any(b => b.UserId == userId))
                         .Skip(query.PageSize * (query.Page - 1))
                         .Take(query.PageSize)
                         .Select(a => new GroupTileDto
            {
                Id   = a.Id,
                Name = a.Name
            }).ToList();

            return(Ok(result));
        }
Beispiel #13
0
        public IActionResult Create([FromBody] PostCreateDto data)
        {
            if (string.IsNullOrEmpty(data.Content))
            {
                return(BadRequest());
            }

            var userId = ClaimsReader.GetUserId(Request);

            if (!context.UserGroups.Any(a => a.GroupId == data.GroupId && a.UserId == userId && (a.Relation == GroupRelation.Owner || a.Relation == GroupRelation.User)))
            {
                return(BadRequest());
            }

            var post = new Post
            {
                DateAdded = DateTime.UtcNow,
                Content   = data.Content,
                GroupId   = data.GroupId,
                UserId    = userId
            };

            context.Posts.Add(post);

            try
            {
                context.SaveChanges();

                var result = new PostDto
                {
                    Id        = post.Id,
                    Content   = post.Content,
                    DateAdded = post.DateAdded,
                    IsOwner   = true,
                    Owner     = context.Users.Find(userId).Login
                };

                return(Ok(result));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #14
0
        public IActionResult GetUserGroups()
        {
            var userId = ClaimsReader.GetUserId(Request);

            var values = context.UserGroups
                         .Include(a => a.Group)
                         .Where(a => a.UserId == userId)
                         .Select(a => new
            {
                a.Relation,
                Value = new
                {
                    a.GroupId,
                    a.Group.Name,
                    a.Group.Description,
                    a.Group.IsPrivate
                }
            }).ToList();

            var result = new UserGroupsWrapperDto();

            result.Participant.AddRange(values.Where(a => a.Relation == GroupRelation.Owner || a.Relation == GroupRelation.User).Select(a => new UserGroupTileDto
            {
                Id          = a.Value.GroupId,
                Name        = a.Value.Name,
                IsOwner     = a.Relation == GroupRelation.Owner,
                IsPrivate   = a.Value.IsPrivate,
                Description = a.Value.Description
            }));

            result.Invited.AddRange(values.Where(a => a.Relation == GroupRelation.Invited).Select(a => new GroupTileDto
            {
                Id   = a.Value.GroupId,
                Name = a.Value.Name
            }));

            result.Waiting.AddRange(values.Where(a => a.Relation == GroupRelation.Requesting).Select(a => new GroupTileDto
            {
                Id   = a.Value.GroupId,
                Name = a.Value.Name
            }));

            return(Ok(result));
        }
Beispiel #15
0
        public IActionResult ChangePassword([FromBody] UserPasswordResetDto model)
        {
            var userId = ClaimsReader.GetUserId(Request.HttpContext.Request);
            var user   = context.Users.SingleOrDefault(a => a.Id == userId);

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

            if (!UserValidators.CheckIfPasswordIsCorrect(model.Password))
            {
                return(BadRequest("Hasło musi posiadać wielką i małą literę, liczbę oraz znak specjalny a także składać się co najmniej z 8 znaków"));
            }

            try
            {
                if (!VerifyPasswordHash(model.OldPassword, user.PasswordHash, user.PasswordSalt))
                {
                    return(BadRequest());
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            CreatePasswordHash(model.Password, out byte[] passwordHash, out byte[] passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            try
            {
                context.SaveChanges();
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Beispiel #16
0
        public async Task SendMessage(string content)
        {
            var currentDate = DateTime.UtcNow;
            var groupId     = dictionary[Context.ConnectionId];
            var userId      = ClaimsReader.GetUserId(Context.User);

            using var scope = provider.CreateScope();
            var dbContext = scope.ServiceProvider.GetService <EngineerContext>();

            var message = new Message
            {
                GroupId   = groupId,
                SenderId  = userId,
                Content   = content,
                DateAdded = currentDate
            };

            dbContext.Messages.Add(message);

            try
            {
                dbContext.SaveChanges();

                var response = new MessageDto
                {
                    Content   = content,
                    DateAdded = DateTime.UtcNow,
                    Owner     = dbContext.Users.Find(userId).Login
                };

                if (GetReceivers(groupId, out IClientProxy clients))
                {
                    await clients.SendAsync("appendMessage", response);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #17
0
        public async Task <IActionResult> DeleteFile([FromQuery] int id)
        {
            var record = await context.Set <DBFile>().FirstOrDefaultAsync(a => a.Id == id);

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

            var userId = ClaimsReader.GetUserId(Request);

            if (record.UserId != userId)
            {
                return(BadRequest());
            }

            try
            {
                System.IO.File.Delete(record.FilePath);

                await context.SaveChangesAsync();

                context.Set <DBFile>().Remove(record);

                return(NoContent());
            }
            catch (DbUpdateException ex)
            {
                Logger.Log($"{nameof(FilesController)} {nameof(DeleteFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
            catch (Exception ex)
            {
                Logger.Log($"{nameof(FilesController)} {nameof(DeleteFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
        }
Beispiel #18
0
        public IActionResult Delete(int id)
        {
            var userId  = ClaimsReader.GetUserId(Request);
            var comment = context.Comments.FirstOrDefault(a => a.Id == id && a.UserId == userId);

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

            context.Comments.Remove(comment);

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #19
0
        public ActionResult <IEnumerable <FileDto> > GetFiles([FromQuery] GroupQueryDto query)
        {
            var userId          = ClaimsReader.GetUserId(Request);
            var formattedFilter = string.IsNullOrEmpty(query.Filter) ? string.Empty : query.Filter.ToLower();

            var result = context.Set <DBFile>()
                         .Include(a => a.User)
                         .OrderByDescending(a => a.DateAdded)
                         .Where(a => a.GroupId == query.GroupId)
                         .Skip(query.PageSize * (query.Page - 1))
                         .Take(query.PageSize)
                         .Select(a => new FileDto
            {
                Id        = a.Id,
                Owner     = a.User.Login,
                DateAdded = a.DateAdded,
                FileName  = a.FileName,
                IsOwner   = a.UserId == userId,
                Size      = a.Size
            }).ToList();

            return(Ok(result));
        }
Beispiel #20
0
        public IActionResult ChangeNotificationSettings()
        {
            var userId = ClaimsReader.GetUserId(Request.HttpContext.Request);
            var user   = context.Users.SingleOrDefault(a => a.Id == userId);

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

            user.ReceiveNotifications = !user.ReceiveNotifications;

            try
            {
                context.SaveChanges();
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Beispiel #21
0
        public IActionResult Get([FromQuery] GroupQueryDto query)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!context.UserGroups.Any(a => a.GroupId == query.GroupId && a.UserId == userId && (a.Relation == GroupRelation.Owner || a.Relation == GroupRelation.User)))
            {
                return(BadRequest());
            }

            var result = context.Messages
                         .Where(a => a.GroupId == query.GroupId)
                         .OrderByDescending(a => a.DateAdded)
                         .Skip(query.PageSize * (query.Page - 1))
                         .Take(query.PageSize)
                         .Select(a => new MessageDto
            {
                DateAdded = a.DateAdded,
                Content   = a.Content,
                Owner     = a.Sender.Login
            }).ToList();

            return(Ok(result));
        }
Beispiel #22
0
        public IActionResult InviteUser([FromBody] InviteUserDto data)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!CheckAdminPriviliges(userId, data.GroupId))
            {
                return(BadRequest());
            }

            var targetId = context.Users.SingleOrDefault(a => a.Login.Equals(data.UserIdentifier) || a.Email.Equals(data.UserIdentifier)).Id;
            var group    = context.Groups.Include(a => a.Users).SingleOrDefault(a => a.Id == data.GroupId);

            if (group.Users.Any(a => a.UserId == targetId))
            {
                return(BadRequest($"Relacja pomiędzy tą grupą oraz użytkownikiem z identyfikatorem {data.UserIdentifier} już istnieje"));
            }

            var connection = new UserGroup
            {
                UserId   = targetId,
                GroupId  = group.Id,
                Relation = GroupRelation.Invited
            };

            context.UserGroups.Add(connection);

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #23
0
        public IActionResult Create([FromBody] GroupCreateDto data)
        {
            if (string.IsNullOrEmpty(data.Name))
            {
                return(BadRequest());
            }

            var group = new Group
            {
                IsPrivate   = data.IsPrivate,
                Name        = data.Name,
                Description = data.Description
            };

            var userId = ClaimsReader.GetUserId(Request);

            var connection = new UserGroup
            {
                UserId   = userId,
                Group    = group,
                Relation = GroupRelation.Owner
            };

            context.Groups.Add(group);
            context.UserGroups.Add(connection);

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #24
0
        public IActionResult Delete(int id)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (CheckAdminPriviliges(userId, id))
            {
                return(BadRequest());
            }

            var group = context.Groups.SingleOrDefault(a => a.Id == id);

            context.Groups.Remove(group);

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #25
0
        public IActionResult RemoveUser([FromBody] RemoveGroupUserDto data)
        {
            var userId = ClaimsReader.GetUserId(Request);

            if (!CheckAdminPriviliges(userId, data.GroupId))
            {
                return(BadRequest());
            }

            var connection = context.UserGroups.SingleOrDefault(a => a.UserId == data.UserId && a.GroupId == data.GroupId);

            context.UserGroups.Remove(connection);

            try
            {
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
        public async Task <IActionResult> RequestWorldDownloadUrl(
            [FromRoute(Name = "id")] long worldId,
            [FromServices] IWorldEntryRepository worldEntryRepository,
            [FromServices] IStorageUrlBuilder urlBuilder,
            [FromServices] IContentDownloadAuthroizationValidator downloadAuthorizer)
        {
            if (worldEntryRepository == null)
            {
                throw new ArgumentNullException(nameof(worldEntryRepository));
            }

            //TODO: We want to rate limit access to this API
            //TODO: We should use both app logging but also another logging service that always gets hit

            //TODO: Consolidate this shared logic between controllers
            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Recieved {nameof(RequestWorldDownloadUrl)} request from {ClaimsReader.GetUserName(User)}:{ClaimsReader.GetUserId(User)}.");
            }

            //TODO: We should probably check the flags of world to see if it's private (IE hidden from user). Or if it's unlisted or removed.
            //It's possible a user is requesting a world that doesn't exist
            //Could be malicious or it could have been deleted for whatever reason
            if (!await worldEntryRepository.ContainsAsync(worldId).ConfigureAwait(false))
            {
                return(Json(new ContentDownloadURLResponse(ContentDownloadURLResponseCode.NoContentId)));
            }

            //TODO: Refactor this into a validation dependency
            //Now we need to do some validation to determine if they should even be downloading this world
            //we do not want people downloading a world they have no business of going to
            int userId = ClaimsReader.GetUserIdInt(User);

            if (!await downloadAuthorizer.CanUserAccessWorldContet(userId, worldId))
            {
                return(Json(new ContentDownloadURLResponse(ContentDownloadURLResponseCode.AuthorizationFailed)));
            }

            //We can get the URL from the urlbuilder if we provide the world storage GUID
            string downloadUrl = await urlBuilder.BuildRetrivalUrl(UserContentType.World, (await worldEntryRepository.RetrieveAsync(worldId)).StorageGuid);

            //TODO: Should we be validating S3 availability?
            if (String.IsNullOrEmpty(downloadUrl))
            {
                if (Logger.IsEnabled(LogLevel.Error))
                {
                    Logger.LogError($"Failed to create world upload URL for {ClaimsReader.GetUserName(User)}:{ClaimsReader.GetUserId(User)} with ID: {worldId}.");
                }

                return(Json(new ContentDownloadURLResponse(ContentDownloadURLResponseCode.ContentDownloadServiceUnavailable)));
            }

            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Success. Sending {ClaimsReader.GetUserName(User)} URL: {downloadUrl}");
            }

            return(Json(new ContentDownloadURLResponse(downloadUrl)));
        }
        public async Task <IActionResult> RequestWorldUploadUrl([FromServices] IWorldEntryRepository worldEntryRepository, [FromServices] IStorageUrlBuilder urlBuilder)
        {
            if (worldEntryRepository == null)
            {
                throw new ArgumentNullException(nameof(worldEntryRepository));
            }

            //TODO: We want to rate limit access to this API
            //TODO: We should use both app logging but also another logging service that always gets hit

            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Recieved {nameof(RequestWorldUploadUrl)} request from {ClaimsReader.GetUserName(User)}:{ClaimsReader.GetUserId(User)}.");
            }

            int userId = ClaimsReader.GetUserIdInt(User);

            //TODO: We should send this if we can't get a user id
            //return new JsonResult(RequestedUrlResponseModel.CreateFailure("Failed to authorize action.", RequestedUrlResponseCode.AuthorizationFailed));
            //TODO: Abstract this behind an issuer
            Guid worldGuid = Guid.NewGuid();

            //TODO: Check if the result is valid? We should maybe return bool from this API (we do return bool from this API now)
            //The idea is to create an entry which will contain a GUID. From that GUID we can then generate the upload URL
            WorldEntryModel world  = new WorldEntryModel(userId, this.HttpContext.Connection.RemoteIpAddress.ToString(), worldGuid);
            bool            result = await worldEntryRepository.TryCreateAsync(world);  //TODO: Ok to just provide a guid right?

            //TODO: Check world's worldid has been set

            string uploadUrl = await urlBuilder.BuildUploadUrl(UserContentType.World, worldGuid);

            if (String.IsNullOrEmpty(uploadUrl))
            {
                if (Logger.IsEnabled(LogLevel.Error))
                {
                    Logger.LogError($"Failed to create world upload URL for {ClaimsReader.GetUserName(User)}:{ClaimsReader.GetUserId(User)} with GUID: {worldGuid}.");
                }

                return(new JsonResult(RequestedUrlResponseModel.CreateFailure("Upload service unavailable.", RequestedUrlResponseCode.ServiceUnavailable)));
            }

            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Success. Sending {ClaimsReader.GetUserName(User)} URL: {uploadUrl}");
            }

            return(new JsonResult(RequestedUrlResponseModel.CreateSuccess(uploadUrl, world.WorldId)));
        }
Beispiel #28
0
        public async Task <IActionResult> UploadFile([FromQuery] int groupId, IFormFile file)
        {
            var size     = file?.Length;
            var sizeInMB = (size / 1024f) / 1024f;

            if (size <= 0 || sizeInMB > appSettings.MaxFileSizeInMB)
            {
                return(BadRequest("Niepoprawny format pliku"));
            }

            var fileExtension = MimeTypesMap.GetExtension(file.ContentType);

            var availableFileFormats = new List <string> {
                "docx", "pdf", "jpeg", "png"
            };

            if (!availableFileFormats.Any(a => a.Equals(fileExtension)))
            {
                return(BadRequest("Niepoprawny format pliku"));
            }

            var userId = ClaimsReader.GetUserId(Request);

            var groupRecord = await context.Set <Group>().Include(a => a.Users).FirstOrDefaultAsync(a => a.Id == groupId);

            var userRecord = await context.Set <User>().FindAsync(userId);

            if (groupRecord == null || userRecord == null)
            {
                return(NotFound());
            }

            if (!groupRecord.Users.Any(a => a.UserId == userId))
            {
                return(BadRequest());
            }

            if (!Directory.Exists(appSettings.FilesPath))
            {
                Directory.CreateDirectory(appSettings.FilesPath);
            }

            var filePath = Path.Combine(appSettings.FilesPath, Path.GetRandomFileName());

            try
            {
                using var stream = System.IO.File.Create(filePath);

                await file.CopyToAsync(stream);

                var dbFile = new DBFile
                {
                    DateAdded = DateTime.UtcNow,
                    FilePath  = filePath,
                    FileName  = file.FileName,
                    User      = userRecord,
                    Group     = groupRecord,
                    Size      = GetFileSizeAsString(size.Value),
                    FileType  = fileExtension.Equals(".pdf") || fileExtension.Equals(".docx") ? Enums.FileType.Document : Enums.FileType.Photo
                };

                context.Set <DBFile>().Add(dbFile);

                await context.SaveChangesAsync();

                return(Ok(new FileDto
                {
                    Id = dbFile.Id,
                    Owner = dbFile.User.Login,
                    DateAdded = dbFile.DateAdded,
                    FileName = dbFile.FileName,
                    IsOwner = true
                }));
            }
            catch (ArgumentException ex)
            {
                Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
            catch (DbUpdateException ex)
            {
                System.IO.File.Delete(filePath);

                Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
            catch (Exception ex)
            {
                Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
        }
Beispiel #29
0
        /// <inheritdoc />
        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync()
            .ConfigureAwait(false);

            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Account Connected: {ClaimsReader.GetUserName(Context.User)}:{ClaimsReader.GetUserId(Context.User)}");
            }

            NetworkEntityGuid guid = new NetworkEntityGuidBuilder()
                                     .WithId(int.Parse(Context.UserIdentifier))
                                     .WithType(EntityType.Player)
                                     .Build();

            //Register interest and then lock
            //We need to lock on the entity so only 1 connection for the entity can go through this process at a time.
            await EntityLockService.RegisterEntityInterestAsync(guid)
            .ConfigureAwait(false);

            using (await EntityLockService.AquireEntityLockAsync(guid).ConfigureAwait(false))
            {
                try
                {
                    foreach (var listener in OnConnectionHubListeners)
                    {
                        HubOnConnectionState connectionState = await listener.OnConnected(this).ConfigureAwait(false);

                        //if the listener indicated we need to abort for whatever reason we
                        //should believe it and just abort.
                        if (connectionState == HubOnConnectionState.Abort)
                        {
                            Context.Abort();
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    if (Logger.IsEnabled(LogLevel.Error))
                    {
                        Logger.LogInformation($"Account: {ClaimsReader.GetUserName(Context.User)}:{ClaimsReader.GetUserId(Context.User)} failed to properly connect to hub. Error: {e.Message}\n\nStack: {e.StackTrace}");
                    }

                    Context.Abort();
                }
            }
        }