コード例 #1
0
        private string GetTenancyNameOrNull()
        {
            if (!AbpSession.TenantId.HasValue)
            {
                return(null);
            }

            return(_tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName);
        }
コード例 #2
0
ファイル: TenantIdAccessor.cs プロジェクト: llenroc/Movie
        /// <summary>
        /// This method is called on request beginning to obtain current tenant id.
        /// </summary>
        public void SetCurrentTenantId()
        {
            var tenancyName = _tenancyNameFinder.Value.GetCurrentTenancyNameOrNull();

            if (tenancyName == null)
            {
                CurrentTenantId = null;
                return;
            }
            CurrentTenantId = _tenantCache.GetOrNull(tenancyName)?.Id;
        }
コード例 #3
0
        protected virtual UserWithFriendsCacheItem GetUserFriendsCacheItemInternal(UserIdentifier userIdentifier)
        {
            var tenancyName = userIdentifier.TenantId.HasValue ?
                              _tenantCache.GetOrNull(userIdentifier.TenantId.Value)?.TenancyName : null;



            using (_unitOfWorkManager.Current.SetTenantId(userIdentifier.TenantId))
            {
                var friendCacheItems = _friendshipRepository.GetAll()
                                       .Where(friendship => friendship.UserId == userIdentifier.UserId)
                                       .Select(friendship => new FriendCacheItem
                {
                    FriendUserId           = friendship.FriendUserId,
                    FriendTenantId         = friendship.FriendTenantId,
                    State                  = friendship.State,
                    FriendUserName         = friendship.FriendUserName,
                    FriendTenancyName      = friendship.FriendTenancyName,
                    FriendProfilePictureId = friendship.FriendProfilePictureId,
                    UnreadMessageCount     =
                        _chatMessageRepository.GetAll().Count(cm => cm.ReadState == ChatMessageReadState.Unread &&
                                                              cm.UserId == userIdentifier.UserId &&
                                                              cm.TenantId == userIdentifier.TenantId &&
                                                              cm.TargetUserId == friendship.FriendUserId &&
                                                              cm.TargetTenantId == friendship.FriendTenantId &&
                                                              cm.Side == ChatSide.Receiver)
                }).ToList();



                var user = _userManager.Users.AsQueryable().FirstOrDefault(o => o.Id == userIdentifier.UserId);

                return(new UserWithFriendsCacheItem
                {
                    TenantId = userIdentifier.TenantId,
                    UserId = userIdentifier.UserId,
                    TenancyName = tenancyName,
                    UserName = user.UserName,
                    ProfilePictureId = user.ProfilePictureId,
                    Friends = friendCacheItems
                });
            }
        }
コード例 #4
0
        private string GetTenancyNameOrNull(string emailAddress)
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
            {
                User user = _userManager.FindByEmail(emailAddress);

                if (user != null)
                {
                    if (user.TenantId == null)
                    {
                        return(null);
                    }

                    Tenant tenant = _tenantManager.GetById((int)user.TenantId);

                    return(tenant.TenancyName);
                }
            }

            return(_tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName);
        }
コード例 #5
0
        protected virtual UserWithFriendsCacheItem GetUserFriendsCacheItemInternal(UserIdentifier userIdentifier)
        {
            var tenancyName = userIdentifier.TenantId.HasValue
                ? _tenantCache.GetOrNull(userIdentifier.TenantId.Value)?.TenancyName
                : null;

            using (_unitOfWorkManager.Current.SetTenantId(userIdentifier.TenantId))
            {
                var friendCacheItems =
                    (from friendship in _friendshipRepository.GetAll()
                     join chatMessage in _chatMessageRepository.GetAll() on
                     new { UserId = userIdentifier.UserId, TenantId = userIdentifier.TenantId, TargetUserId = friendship.FriendUserId, TargetTenantId = friendship.FriendTenantId, ChatSide = ChatSide.Receiver } equals
                     new { UserId = chatMessage.UserId, TenantId = chatMessage.TenantId, TargetUserId = chatMessage.TargetUserId, TargetTenantId = chatMessage.TargetTenantId, ChatSide = chatMessage.Side } into chatMessageJoined
                     join user in _userManager.Users on friendship.FriendUserId equals user.Id
                     where friendship.UserId == userIdentifier.UserId
                     select new FriendCacheItem
                {
                    FriendUserId = friendship.FriendUserId,
                    FriendTenantId = friendship.FriendTenantId,
                    State = friendship.State,
                    FriendUserName = user.Name,
                    FriendTenancyName = friendship.FriendTenancyName,
                    FriendProfilePictureId = user.ProfilePictureId,
                    UnreadMessageCount = chatMessageJoined.Count(cm => cm.ReadState == ChatMessageReadState.Unread)
                }).ToList();

                var currentUser = _userManager.FindById(userIdentifier.UserId);

                return(new UserWithFriendsCacheItem
                {
                    TenantId = userIdentifier.TenantId,
                    UserId = userIdentifier.UserId,
                    TenancyName = tenancyName,
                    UserName = currentUser.UserName,
                    ProfilePictureId = currentUser.ProfilePictureId,
                    Friends = friendCacheItems
                });
            }
        }
コード例 #6
0
        public async Task <bool> ExcuteAsync(WeChatMiniProgramLoginContext ct)
        {
            this.httpContext  = ct.HttpContext;
            this.httpResponse = httpContext.Response;
            if (AbpSession.TenantId.HasValue)
            {
                this.tenancyName = _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName;
            }

            //尝试做第三发登录(内部通过openid找到本地账号做登录),
            var loginResult = await _logInManager.LoginAsync(new UserLoginInfo(MiniProgramConsts.AuthenticationScheme, ct.WeChatUser.openid, MiniProgramConsts.AuthenticationSchemeDisplayName), tenancyName);

            //根据登录结果,若成功则直接返回jwtToken 或者自动注册后返回
            switch (loginResult.Result)
            {
            case AbpLoginResultType.Success:
            {
                var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));

                //User是聚合跟,因此查它的Claims性能差点,方式没毛病;即使这里不获取所有Claim,UserManager.ReplaceClaimAsync内部也会尝试查询全部,若我们查了,它就不会查了
                var claims = await userManager.GetClaimsAsync(loginResult.User);

                //ReplaceClaimAsync abp 5.4版本有bug,
                //var sessionKeyClaim = claims.Single(c => c.Type == "session_key");
                // var claimRT = await userManager.ReplaceClaimAsync(loginResult.User, sessionKeyClaim, new Claim("session_key", ct.WeChatUser.session_key));

                await userManager.RemoveClaimsAsync(loginResult.User, claims.Where(c => c.Type == "session_key"));

                await userManager.AddClaimAsync(loginResult.User, new Claim("session_key", ct.WeChatUser.session_key));

                #region 处理前端传递来的除code以外的其它数据
                //var tttt = ct.WeChatUser.Input.EnumerateArray();//json格式的数组对象才能这样
                //这样的方式才可以正常遍历前端传来的除code以外的其它数据
                //foreach (var property in ct.WeChatUser.Input.EnumerateObject())
                //{
                //    property.Name.Value..
                //}
                //或者用下面的方式按需更新
                //if (ct.WeChatUser.Input.TryGetProperty("nickName", out var k))
                //{
                //    var claim = claims.Single(c => c.Type == "nickName");
                //    await userManager.ReplaceClaimAsync(loginResult.User, claim, new Claim("", ""));
                //}
                #endregion

                //await UnitOfWorkManager.Current.SaveChangesAsync();//必须加

                await WriteJsonAsync(new
                    {
                        AccessToken          = accessToken,
                        EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
                        ExpireInSeconds      = (int)_configuration.Expiration.TotalSeconds
                    });

                return(true);
            }

            case AbpLoginResultType.UnknownExternalLogin:
            {
                //若未找到关联的本地账号则自动注册,再返回jwtToken
                var newUser = await RegisterExternalUserAsync(new ExternalAuthUserInfo
                    {
                        Provider     = MiniProgramConsts.AuthenticationScheme,
                        ProviderKey  = ct.WeChatUser.openid,
                        Name         = Guid.NewGuid().ToString("N"),
                        EmailAddress = Guid.NewGuid().ToString("N") + "@mp.com",
                        Surname      = "a"
                    });

                //if (!newUser.IsActive)
                //{
                //    return new ExternalAuthenticateResultModel
                //    {
                //        WaitingForActivation = true
                //    };
                //}

                // Try to login again with newly registered user!
                loginResult = await _logInManager.LoginAsync(new UserLoginInfo(MiniProgramConsts.AuthenticationScheme, ct.WeChatUser.openid, MiniProgramConsts.AuthenticationSchemeDisplayName), tenancyName);

                if (loginResult.Result != AbpLoginResultType.Success)
                {
                    //throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
                    //    loginResult.Result,
                    //    openid,
                    //    tenancyName
                    //);
                    await WriteJsonAsync(new { msg = "注册失败" });
                }
                //保存微信用户信息(排出openid,因为它存储在userlogins里)
                // await userManager.AddClaimsAsync(loginResult.User, t.Principal.Claims.Where(c => c.Type != ClaimTypes.NameIdentifier));

                else
                {
                    await userManager.AddClaimAsync(loginResult.User, new Claim("session_key", ct.WeChatUser.session_key));
                    await WriteJsonAsync(new
                        {
                            AccessToken     = CreateAccessToken(CreateJwtClaims(loginResult.Identity)),
                            ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
                        });
                }
                return(true);
            }

            default:
            {
                await WriteJsonAsync(new { msg = "登录失败!" });

                //throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
                //    loginResult.Result,
                //    openid,
                //    tenancyName
                //);
            }
                return(true);
            }
        }
コード例 #7
0
ファイル: TenantStore.cs プロジェクト: longhuynh/studiox
        public TenantInfo Find(int tenantId)
        {
            var tenant = tenantCache.GetOrNull(tenantId);

            return(tenant == null ? null : new TenantInfo(tenant.Id, tenant.TenancyName));
        }