コード例 #1
0
        /// <summary>
        /// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
        /// Throws exception if it's null.
        /// </summary>
        protected async Task <User> GetCurrentUserAsync()
        {
            var userId = AbpSession.GetUserId();

            return(await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId)));
        }
コード例 #2
0
        public async Task SetNotificationAsRead(EntityDto <Guid> input)
        {
            var userNotification = await _userNotificationManager.GetUserNotificationAsync(AbpSession.TenantId, input.Id);

            if (userNotification.UserId != AbpSession.GetUserId())
            {
                throw new ApplicationException(string.Format("Given user notification id ({0}) is not belong to the current user ({1})", input.Id, AbpSession.GetUserId()));
            }

            await _userNotificationManager.UpdateUserNotificationStateAsync(AbpSession.TenantId, input.Id, UserNotificationState.Read);
        }
コード例 #3
0
        public async Task MarkAllUnreadMessagesOfUserAsRead(MarkAllUnreadMessagesOfUserAsReadInput input)
        {
            var userId   = AbpSession.GetUserId();
            var tenantId = AbpSession.TenantId;

            // receiver messages
            var messages = await _chatMessageRepository
                           .GetAll()
                           .Where(m =>
                                  m.UserId == userId &&
                                  m.TargetTenantId == input.TenantId &&
                                  m.TargetUserId == input.UserId &&
                                  m.ReadState == ChatMessageReadState.Unread)
                           .ToListAsync();

            if (!messages.Any())
            {
                return;
            }

            foreach (var message in messages)
            {
                message.ChangeReadState(ChatMessageReadState.Read);
            }

            // sender messages
            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var reverseMessages = await _chatMessageRepository.GetAll()
                                      .Where(m => m.UserId == input.UserId && m.TargetTenantId == tenantId && m.TargetUserId == userId)
                                      .ToListAsync();

                if (!reverseMessages.Any())
                {
                    return;
                }

                foreach (var message in reverseMessages)
                {
                    message.ChangeReceiverReadState(ChatMessageReadState.Read);
                }
            }

            var userIdentifier   = AbpSession.ToUserIdentifier();
            var friendIdentifier = input.ToUserIdentifier();

            _userFriendsCache.ResetUnreadMessageCount(userIdentifier, friendIdentifier);

            var onlineUserClients = _onlineClientManager.GetAllByUserId(userIdentifier);

            if (onlineUserClients.Any())
            {
                await _chatCommunicator.SendAllUnreadMessagesOfUserReadToClients(onlineUserClients, friendIdentifier);
            }

            var onlineFriendClients = _onlineClientManager.GetAllByUserId(friendIdentifier);

            if (onlineFriendClients.Any())
            {
                await _chatCommunicator.SendReadStateChangeToClients(onlineFriendClients, userIdentifier);
            }
        }
コード例 #4
0
        public UploadProfilePictureOutput UploadProfilePicture()
        {
            try
            {
                var profilePictureFile = Request.Form.Files.First();

                //Check input
                if (profilePictureFile == null)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Change_Error"));
                }

                if (profilePictureFile.Length > MaxProfilePictureSize)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit", AppConsts.MaxProfilPictureBytesUserFriendlyValue));
                }

                byte[] fileBytes;
                using (var stream = profilePictureFile.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif))
                {
                    throw new Exception("Uploaded file is not an accepted image file !");
                }

                //Delete old temp profile pictures
                AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "userProfileImage_" + AbpSession.GetUserId());

                //Save new picture
                var    fileInfo = new FileInfo(profilePictureFile.FileName);
                string ext      = fileInfo.Extension.ToLower().Trim();
                if (ext.Equals(".jpg") || ext.Equals(".png") || ext.Equals(".gif") || ext.Equals(".jpeg"))
                {
                    var tempFileName = "userProfileImage_" + AbpSession.GetUserId() + fileInfo.Extension;
                    var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName);
                    System.IO.File.WriteAllBytes(tempFilePath, fileBytes);

                    using (var bmpImage = new Bitmap(tempFilePath))
                    {
                        return(new UploadProfilePictureOutput
                        {
                            FileName = tempFileName,
                            Width = bmpImage.Width,
                            Height = bmpImage.Height
                        });
                    }
                }
                else
                {
                    throw new UserFriendlyException("Uploaded file format is not correct !");
                }
            }
            catch (Exception ex)
            {
                return(new UploadProfilePictureOutput(new ErrorInfo(ex.Message)));
            }
        }
コード例 #5
0
        public JsonResult UploadProfilePicture()
        {
            try
            {
                //Check input
                if (Request.Files.Count <= 0 || Request.Files[0] == null)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Change_Error"));
                }

                var file = Request.Files[0];

                if (file.ContentLength > 5242880) //1MB.
                {
                    throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit"));
                }

                //Check file type & format
                var fileImage = Image.FromStream(file.InputStream);
                if (!fileImage.RawFormat.Equals(ImageFormat.Jpeg) && !fileImage.RawFormat.Equals(ImageFormat.Png))
                {
                    throw new ApplicationException("Uploaded file is not an accepted image file !");
                }

                //Delete old temp profile pictures
                AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "userProfileImage_" + AbpSession.GetUserId());

                //Save new picture
                var fileInfo     = new FileInfo(file.FileName);
                var tempFileName = "userProfileImage_" + AbpSession.GetUserId() + fileInfo.Extension;
                var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName);
                file.SaveAs(tempFilePath);

                using (var bmpImage = new Bitmap(tempFilePath))
                {
                    return(Json(new AjaxResponse(new { fileName = tempFileName, width = bmpImage.Width, height = bmpImage.Height })));
                }
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
コード例 #6
0
        public async Task LogOut()
        {
            if (AbpSession.UserId != null)
            {
                var tokenValidityKeyInClaims = User.Claims.First(c => c.Type == AppConsts.TokenValidityKey);
                await _userManager.RemoveTokenValidityKeyAsync(_userManager.GetUser(AbpSession.ToUserIdentifier()), tokenValidityKeyInClaims.Value);

                _cacheManager.GetCache(AppConsts.TokenValidityKey).Remove(tokenValidityKeyInClaims.Value);

                if (AllowOneConcurrentLoginPerUser())
                {
                    await _securityStampHandler.RemoveSecurityStampCacheItem(AbpSession.TenantId, AbpSession.GetUserId());
                }
            }
        }
コード例 #7
0
        public long GetUserID()
        {
            long a = AbpSession.GetUserId();

            return(a);
        }
コード例 #8
0
        /// <summary>
        /// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
        /// Throws exception if it's null.
        /// </summary>
        protected User GetCurrentUser()
        {
            var userId = AbpSession.GetUserId();

            return(UsingDbContext(context => context.Users.Single(u => u.Id == userId)));
        }
コード例 #9
0
        /// <summary>
        /// 上传图片文件并上传至微信
        /// </summary>
        /// <returns></returns>
        public async Task <JsonResult> UploadMatialPic()
        {
            try
            {
                var profilePictureFile = Request.Form.Files.First();

                //Check input
                if (profilePictureFile == null)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Change_Error"));
                }

                if (profilePictureFile.Length > 2097152) //2MB.
                {
                    throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit"));
                }

                byte[] fileBytes;
                using (var stream = profilePictureFile.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif))
                {
                    throw new Exception("上传文件非图片文件");
                }

                //Delete old temp profile pictures
                AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "martialPic_" + AbpSession.GetUserId());

                //Save new picture
                var fileInfo     = new FileInfo(profilePictureFile.FileName);
                var tempFileName = "martialPic_" + AbpSession.GetUserId() + Guid.NewGuid().ToString() + fileInfo.Extension;
                var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName);
                await System.IO.File.WriteAllBytesAsync(tempFilePath, fileBytes);

                var virtualPath = _matialFileService.MatialFileTempPath + tempFileName;


                var mediaId = "";
                try
                {
                    mediaId = await _wxMediaAppService.UploadMedia(tempFilePath, "");//上传至微信
                }
                catch (Exception e)
                {
                    Logger.Error("上传微信错误,错误信息:" + e.Message + ";错误堆栈:" + e.StackTrace);
                }

                //var mediaId = "测试";


                return(Json(new AjaxResponse(new { fileName = tempFileName, fileFullPath = tempFilePath, fileVirtualPath = virtualPath, mediaID = mediaId })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
コード例 #10
0
        public async Task SetNotificationAsRead(EntityDto <Guid> input)
        {
            var _user = await UserManager.FindByIdAsync("2");

            if (AbpSession.UserId.HasValue)
            {
                _user = await UserManager.FindByIdAsync(AbpSession.UserId.ToString());
            }
            await _notificationPublisher.PublishAsync(
                "Ali Essa",
                new MessageNotificationData("Has registered on site test"),
                userIds : new[] { _user.ToUserIdentifier() }
                );

            var userNotification = await _userNotificationManager.GetUserNotificationAsync(AbpSession.TenantId, input.Id);

            if (userNotification.UserId != AbpSession.GetUserId())
            {
                throw new Exception(string.Format("Given user notification id ({0}) is not belong to the current user ({1})", input.Id, AbpSession.GetUserId()));
            }

            await _userNotificationManager.UpdateUserNotificationStateAsync(AbpSession.TenantId, input.Id, UserNotificationState.Read);
        }
コード例 #11
0
        public async Task Should_Remove_Expired_TokenValidityKeys()
        {
            //Arrange
            using (_unitOfWorkManager.Begin())
            {
                var user = await _abpUserManager.GetUserByIdAsync(AbpSession.GetUserId());

                await _abpUserManager.AddTokenValidityKeyAsync(
                    user,
                    Guid.NewGuid().ToString(),
                    DateTime.UtcNow
                    );

                await _abpUserManager.AddTokenValidityKeyAsync(
                    user,
                    Guid.NewGuid().ToString(),
                    DateTime.UtcNow.AddDays(1)
                    );

                await _abpUserManager.AddTokenValidityKeyAsync(
                    user,
                    Guid.NewGuid().ToString(),
                    DateTime.UtcNow.AddDays(1)
                    );

                await _unitOfWorkManager.Current.SaveChangesAsync();

                var allTokens = await _userTokenRepository.GetAllListAsync(t => t.UserId == user.Id);

                allTokens.Count.ShouldBe(3);
            }

            using (_unitOfWorkManager.Begin())
            {
                using (_unitOfWorkManager.Current.SetTenantId(null))
                {
                    var user = await _abpUserManager.FindByNameOrEmailAsync(AbpUserBase.AdminUserName);

                    await _abpUserManager.AddTokenValidityKeyAsync(
                        user,
                        Guid.NewGuid().ToString(),
                        DateTime.UtcNow
                        );

                    await _abpUserManager.AddTokenValidityKeyAsync(
                        user,
                        Guid.NewGuid().ToString(),
                        DateTime.UtcNow.AddDays(1)
                        );

                    await _abpUserManager.AddTokenValidityKeyAsync(
                        user,
                        Guid.NewGuid().ToString(),
                        DateTime.UtcNow.AddDays(1)
                        );

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    var allTokens = await _userTokenRepository.GetAllListAsync(t => t.UserId == user.Id);

                    allTokens.Count.ShouldBe(3);
                }
            }

            //Act
            _userTokenExpirationWorker.Start();

            //Assert
            using (_unitOfWorkManager.Begin())
            {
                var user = await _abpUserManager.GetUserByIdAsync(AbpSession.GetUserId());

                var allTokens = await _userTokenRepository.GetAllListAsync(t => t.UserId == user.Id);

                allTokens.Count.ShouldBe(2);
            }

            using (_unitOfWorkManager.Begin())
            {
                using (_unitOfWorkManager.Current.SetTenantId(null))
                {
                    var user = await _abpUserManager.FindByNameOrEmailAsync(AbpUserBase.AdminUserName);

                    var allTokens = await _userTokenRepository.GetAllListAsync(t => t.UserId == user.Id);

                    allTokens.Count.ShouldBe(2);
                }
            }
        }