Ejemplo n.º 1
0
        public PartialViewResult SocialMenu()
        {
            var model = new SocialMenuViewModel
            {
                SocialMenu = AsyncHelper.RunSync(() => _userNavigationManager.GetMenusAsync(AbpSession.ToUserIdentifier())),
            };

            return(PartialView("_SocialMenu", model));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected async Task <Tenant> GetCurrentTenantAsync()
        {
            var tenantId = AbpSession.GetTenantId();

            return(await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId)));
        }
        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);
                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
                    });
                }
            }
            catch (UserFriendlyException ex)
            {
                return(new UploadProfilePictureOutput(new ErrorInfo(ex.Message)));
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected Tenant GetCurrentTenant()
        {
            var tenantId = AbpSession.GetTenantId();

            return(UsingDbContext(null, context => context.Tenants.Single(t => t.Id == tenantId)));
        }
        public async Task RemoveDelegation(EntityDto <long> input)
        {
            CheckUserDelegationOperation();

            await _userDelegationManager.RemoveDelegationAsync(input.Id, AbpSession.ToUserIdentifier());
        }
Ejemplo n.º 6
0
        public PartialViewResult Sidebar(string currentPageName = "")
        {
            var sidebarModel = new SidebarViewModel
            {
                Menu            = AsyncHelper.RunSync(() => _userNavigationManager.GetMenuAsync(MpaNavigationProvider.MenuName, AbpSession.ToUserIdentifier())),
                CurrentPageName = currentPageName
            };

            return(PartialView("_Sidebar", sidebarModel));
        }
Ejemplo n.º 7
0
        public PartialViewResult Header(string currentPageName = "")
        {
            var headerModel = new HeaderViewModel();

            if (AbpSession.UserId.HasValue)
            {
                headerModel.LoginInformations = AsyncHelper.RunSync(() => _sessionCache.GetCurrentLoginInformationsAsync());
            }

            headerModel.Languages       = _languageManager.GetLanguages();
            headerModel.CurrentLanguage = _languageManager.CurrentLanguage;

            headerModel.Menu            = AsyncHelper.RunSync(() => _userNavigationManager.GetMenuAsync(FrontEndNavigationProvider.MenuName, AbpSession.ToUserIdentifier()));
            headerModel.CurrentPageName = currentPageName;

            headerModel.IsMultiTenancyEnabled     = _multiTenancyConfig.IsEnabled;
            headerModel.TenantRegistrationEnabled = SettingManager.GetSettingValue <bool>(AppSettings.TenantManagement.AllowSelfRegistration);

            return(PartialView("~/Views/Layout/_Header.cshtml", headerModel));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> CommentTo(long articleId, int replyToCommentId)
        {
            var article = await _articleAppService.GetArticleAsync(articleId);

            var reply = await ReplyToComment(replyToCommentId);

            // publish notification to all subscriber, exclude self
            await _notificationPublisher.PublishAsync(NotificationName.CommentArticle,
                                                      new MessageNotificationData(Url.Action("GetArticle", "Article", new { ArticleId = articleId })),
                                                      new EntityIdentifier(typeof(Blog), articleId),
                                                      excludedUserIds : new[] { new UserIdentifier(AppConsts.DefaultTenant, AbpSession.GetUserId()) });

            // subscribe comment notification
            await _notificationSubscriptionManager.SubscribeAsync(
                new UserIdentifier(AbpSession.TenantId, AbpSession.GetUserId()),
                NotificationName.CommentArticle, new EntityIdentifier(typeof(Blog), articleId));

            return(View("Template/Comment/CommentTo", new CommentToViewModel
            {
                ArticleId = article.ArticleId,
                CommentTitle = article.Title,
                CommentToLink = Url.Action("GetArticle", new { ArticleId = articleId }),
                ReplyToCommentId = reply.Second,
                ReturnUrl = Url.Action("GetArticle", new { ArticleId = articleId }),
                ContentInit = reply.First
            }));
        }
Ejemplo n.º 9
0
        public async Task ChangePassword(ChangePasswordInput input)
        {
            var result = await _userManager.ChangePasswordAsync(AbpSession.GetUserId(), input.CurrentPassword, input.NewPassword);

            result.CheckErrors(LocalizationManager);
        }
Ejemplo n.º 10
0
        public PartialViewResult TopMenu(string activeMenu = "")
        {
            var model = new TopMenuViewModel
            {
                MainMenu           = AsyncHelper.RunSync(() => _userNavigationManager.GetMenuAsync("MainMenu", AbpSession.ToUserIdentifier())),
                ActiveMenuItemName = activeMenu
            };

            return(PartialView("_TopMenu", model));
        }
        private async Task <TenantEmailSettingsEditDto> GetEmailSettingsAsync()
        {
            var useHostDefaultEmailSettings = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.Email.UseHostDefaultEmailSettings, AbpSession.GetTenantId());

            if (useHostDefaultEmailSettings)
            {
                return(new TenantEmailSettingsEditDto
                {
                    UseHostDefaultEmailSettings = true
                });
            }

            var smtpPassword = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Password, AbpSession.GetTenantId());

            return(new TenantEmailSettingsEditDto
            {
                UseHostDefaultEmailSettings = false,
                DefaultFromAddress = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.DefaultFromAddress, AbpSession.GetTenantId()),
                DefaultFromDisplayName = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.DefaultFromDisplayName, AbpSession.GetTenantId()),
                SmtpHost = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Host, AbpSession.GetTenantId()),
                SmtpPort = await SettingManager.GetSettingValueForTenantAsync <int>(EmailSettingNames.Smtp.Port, AbpSession.GetTenantId()),
                SmtpUserName = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.UserName, AbpSession.GetTenantId()),
                SmtpPassword = SimpleStringCipher.Instance.Decrypt(smtpPassword),
                SmtpDomain = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Domain, AbpSession.GetTenantId()),
                SmtpEnableSsl = await SettingManager.GetSettingValueForTenantAsync <bool>(EmailSettingNames.Smtp.EnableSsl, AbpSession.GetTenantId()),
                SmtpUseDefaultCredentials = await SettingManager.GetSettingValueForTenantAsync <bool>(EmailSettingNames.Smtp.UseDefaultCredentials, AbpSession.GetTenantId())
            });
        }
Ejemplo n.º 12
0
 public void TestSession()
 {
     AbpSession.ShouldNotBe(null);
     AbpSession.TenantId.ShouldBe(1);
     AbpSession.UserId.ShouldBe(42);
 }
Ejemplo n.º 13
0
 public async Task UpdateUiManagementSettings(ThemeSettingsDto settings)
 {
     var themeCustomizer = _uiThemeCustomizerFactory.GetUiCustomizer(settings.Theme);
     await themeCustomizer.UpdateUserUiManagementSettingsAsync(AbpSession.ToUserIdentifier(), settings);
 }
Ejemplo n.º 14
0
        public virtual async Task <JsonResult> UpdateFromAoxiang(UpdateFromAoxiangViewModel input)
        {
            if (input.Password != input.PasswordAgain)
            {
                throw new UserFriendlyException("`password` should be same with `password again`");
            }

            await _userAppService.UpdateInfoFromAoxiangAsync(new UpdateUserInfoFromAoxiangInput
            {
                Password = input.Password
            });

            await _notificationPublisher.PublishAsync(NotificationName.CheckProfile,
                                                      new MessageNotificationData(Url.Action("UserProfile")),
                                                      userIds : new[] { new UserIdentifier(AppConsts.DefaultTenant, AbpSession.GetUserId()) });

            return(Json(new AjaxResponse()));
        }
Ejemplo n.º 15
0
 public async Task SetAllNotificationsAsRead()
 {
     await _userNotificationManager.UpdateAllUserNotificationStatesAsync(AbpSession.ToUserIdentifier(), UserNotificationState.Read);
 }
Ejemplo n.º 16
0
 public async Task PrepareCollectedData()
 {
     await _backgroundJobManager.EnqueueAsync <UserCollectedDataPrepareJob, UserIdentifier>(AbpSession.ToUserIdentifier());
 }
Ejemplo n.º 17
0
        public async Task SetNotificationAsRead(IdInput <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);
        }
Ejemplo n.º 18
0
        public async Task <GetProfilePictureOutput> GetFriendProfilePictureById(GetFriendProfilePictureByIdInput input)
        {
            if (!input.ProfilePictureId.HasValue || await _friendshipManager.GetFriendshipOrNullAsync(AbpSession.ToUserIdentifier(), new UserIdentifier(input.TenantId, input.UserId)) == null)
            {
                return(new GetProfilePictureOutput(string.Empty));
            }

            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var bytes = await GetProfilePictureByIdOrNull(input.ProfilePictureId.Value);

                if (bytes == null)
                {
                    return(new GetProfilePictureOutput(string.Empty));
                }

                return(new GetProfilePictureOutput(Convert.ToBase64String(bytes)));
            }
        }
Ejemplo n.º 19
0
        public async Task <ActionResult> Index()
        {
            var output = await _tenantSettingsAppService.GetAllSettings();

            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

            var timezoneItems = await _timingAppService.GetTimezoneComboboxItems(new GetTimezoneComboboxItemsInput
            {
                DefaultTimezoneScope = SettingScopes.Tenant,
                SelectedTimezoneId   = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId())
            });

            var model = new SettingsViewModel
            {
                Settings      = output,
                TimezoneItems = timezoneItems
            };

            return(View(model));
        }
Ejemplo n.º 20
0
        public async Task <GetNotificationSettingsOutput> GetNotificationSettings()
        {
            var output = new GetNotificationSettingsOutput();

            output.ReceiveNotifications = await SettingManager.GetSettingValueAsync <bool>(NotificationSettingNames.ReceiveNotifications);

            //Get general notifications, not entity related notifications.
            var notificationDefinitions = (await _notificationDefinitionManager.GetAllAvailableAsync(AbpSession.ToUserIdentifier())).Where(nd => nd.EntityType == null);

            output.Notifications = ObjectMapper.Map <List <NotificationSubscriptionWithDisplayNameDto> >(notificationDefinitions);

            var subscribedNotifications = (await _notificationSubscriptionManager
                                           .GetSubscribedNotificationsAsync(AbpSession.ToUserIdentifier()))
                                          .Select(ns => ns.NotificationName)
                                          .ToList();

            output.Notifications.ForEach(n => n.IsSubscribed = subscribedNotifications.Contains(n.Name));

            return(output);
        }
Ejemplo n.º 21
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)));
        }
        private async Task <List <Dashboard> > GetDefaultDashboardValue(string application)
        {
            string dashboardConfigAsJsonString;

            if (AbpSession.MultiTenancySide == MultiTenancySides.Host)
            {
                dashboardConfigAsJsonString = await SettingManager.GetSettingValueForApplicationAsync(GetSettingName(application));
            }
            else
            {
                dashboardConfigAsJsonString = await SettingManager.GetSettingValueForTenantAsync(GetSettingName(application), AbpSession.GetTenantId());
            }

            return(string.IsNullOrWhiteSpace(dashboardConfigAsJsonString)
                ? null
                : JsonConvert.DeserializeObject <List <Dashboard> >(dashboardConfigAsJsonString));
        }
Ejemplo n.º 23
0
        public virtual async Task <ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                CheckModelState();

                //Create user
                var user = new User
                {
                    Name         = model.Name,
                    Surname      = model.Surname,
                    EmailAddress = model.EmailAddress,
                    IsActive     = true
                };

                //Get external login info if possible
                ExternalLoginInfo externalLoginInfo = null;
                if (model.IsExternalLogin)
                {
                    externalLoginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

                    if (externalLoginInfo == null)
                    {
                        throw new ApplicationException("Can not external login!");
                    }

                    user.Logins = new List <UserLogin>
                    {
                        new UserLogin
                        {
                            LoginProvider = externalLoginInfo.Login.LoginProvider,
                            ProviderKey   = externalLoginInfo.Login.ProviderKey
                        }
                    };

                    if (model.UserName.IsNullOrEmpty())
                    {
                        model.UserName = model.EmailAddress;
                    }

                    model.Password = Authorization.Users.User.CreateRandomPassword();

                    if (string.Equals(externalLoginInfo.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        user.IsEmailConfirmed = true;
                    }
                }
                else
                {
                    //Username and Password are required if not external login
                    if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("FormIsNotValidMessage"));
                    }
                }

                user.UserName = model.UserName;
                user.Password = new PasswordHasher().HashPassword(model.Password);

                //Switch to the tenant
                _unitOfWorkManager.Current.EnableFilter(AbpDataFilters.MayHaveTenant); //TODO: Needed?
                _unitOfWorkManager.Current.SetTenantId(AbpSession.GetTenantId());

                //Add default roles
                user.Roles = new List <UserRole>();
                foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
                {
                    user.Roles.Add(new UserRole {
                        RoleId = defaultRole.Id
                    });
                }

                //Save user
                CheckErrors(await _userManager.CreateAsync(user));
                await _unitOfWorkManager.Current.SaveChangesAsync();

                //Directly login if possible
                if (user.IsActive)
                {
                    AbpLoginResult <Tenant, User> loginResult;
                    if (externalLoginInfo != null)
                    {
                        loginResult = await _logInManager.LoginAsync(externalLoginInfo.Login, GetTenancyNameOrNull());
                    }
                    else
                    {
                        loginResult = await GetLoginResultAsync(user.UserName, model.Password, GetTenancyNameOrNull());
                    }

                    if (loginResult.Result == AbpLoginResultType.Success)
                    {
                        await SignInAsync(loginResult.User, loginResult.Identity);

                        return(Redirect(Url.Action("Index", "Home")));
                    }

                    Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
                }

                //If can not login, show a register result page
                return(View("RegisterResult", new RegisterResultViewModel
                {
                    TenancyName = GetTenancyNameOrNull(),
                    NameAndSurname = user.Name + " " + user.Surname,
                    UserName = user.UserName,
                    EmailAddress = user.EmailAddress,
                    IsActive = user.IsActive
                }));
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;
                ViewBag.ErrorMessage          = ex.Message;

                return(View("Register", model));
            }
        }
        private async Task<GeneralSettingsEditDto> GetGeneralSettingsAsync()
        {
            var settings = new GeneralSettingsEditDto();

            if (Clock.SupportsMultipleTimezone)
            {
                var timezone = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId());

                settings.Timezone = timezone;
                settings.TimezoneForComparison = timezone;
            }

            var defaultTimeZoneId = await _timeZoneService.GetDefaultTimezoneAsync(SettingScopes.Tenant, AbpSession.TenantId);

            if (settings.Timezone == defaultTimeZoneId)
            {
                settings.Timezone = string.Empty;
            }

            return settings;
        }
Ejemplo n.º 25
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)));
        }
 private async Task UpdateUserLockOutSettingsAsync(UserLockOutSettingsEditDto settings)
 {
     await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, settings.IsEnabled.ToString().ToLowerInvariant());
     await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, settings.DefaultAccountLockoutSeconds.ToString());
     await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, settings.MaxFailedAccessAttemptsBeforeLockout.ToString());
 }
Ejemplo n.º 27
0
 protected virtual Task <Tenant> GetCurrentTenantAsync()
 {
     return(TenantManager.GetByIdAsync(AbpSession.GetTenantId()));
 }
Ejemplo n.º 28
0
        public async Task <ActionResult> Index()
        {
            var output = await _tenantSettingsAppService.GetAllSettings();

            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

            var timezoneItems = await _timingAppService.GetTimezoneComboboxItems(new GetTimezoneComboboxItemsInput
            {
                DefaultTimezoneScope = SettingScopes.Tenant,
                SelectedTimezoneId   = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId())
            });

            var user = await _userManager.GetUserAsync(AbpSession.ToUserIdentifier());

            ViewBag.CurrentUserEmail = user.EmailAddress;

            var tenant = await _tenantManager.FindByIdAsync(AbpSession.GetTenantId());

            ViewBag.TenantId          = tenant.Id;
            ViewBag.TenantLogoId      = tenant.LogoId;
            ViewBag.TenantCustomCssId = tenant.CustomCssId;

            var model = new SettingsViewModel
            {
                Settings      = output,
                TimezoneItems = timezoneItems
            };

            return(View(model));
        }
 public async Task ChangeUiTheme(ChangeUiThemeInput input)
 {
     await SettingManager.ChangeSettingForUserAsync(AbpSession.ToUserIdentifier(), AppSettingNames.UiTheme, input.Theme);
 }
Ejemplo n.º 30
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);
            }
        }