Beispiel #1
0
        public UserModel GetUser(object identity, UserIdentityType identityType = UserIdentityType.Username)
        {
            List <UserModel> matchedUsers = new List <UserModel>();

            switch (identityType)
            {
            case UserIdentityType.Email:
                matchedUsers = Users.Where(x => x.Email == (string)identity).ToList();
                break;

            case UserIdentityType.Role:
                matchedUsers = Users.Where(x => x.Role == identity).ToList();
                break;

            case UserIdentityType.Username:
                matchedUsers = Users.Where(x => x.Username == (string)identity).ToList();
                break;
            }

            if (matchedUsers.Count == 0)
            {
                throw new ArgumentOutOfRangeException($"Can't find User by {identityType} {identity}");
            }

            if (matchedUsers.Count > 1)
            {
                throw new ArgumentOutOfRangeException($"There is more than one use with {identityType} {identity}");
            }
            return(matchedUsers.First());
        }
Beispiel #2
0
 public IdentityApiRequestBuilder UserIdentity(UserIdentityType identityType, string identityValue)
 {
     if (this.userIdentities == null)
     {
         this.UserIdentities(new Dictionary <UserIdentityType, string>());
     }
     this.userIdentities[identityType] = identityValue;
     return(this);
 }
        public async Task <IHttpActionResult> SendMessage(string userId, string message, bool tempSilence = false,
                                                          UserIdentityType idType = UserIdentityType.IdCode)
        {
            if (userId == "*")
            {
                foreach (var client in SteamBotCoordinator.Sessions.Values.Select(c => c.Client))
                {
                    await client.BroadcastMessage(message);
                }
            }
            else
            {
                KeylolUser user;
                switch (idType)
                {
                case UserIdentityType.UserName:
                    user = await _userManager.FindByNameAsync(userId);

                    break;

                case UserIdentityType.IdCode:
                    user = await _userManager.FindByIdCodeAsync(userId);

                    break;

                case UserIdentityType.Id:
                    user = await _userManager.FindByIdAsync(userId);

                    break;

                case UserIdentityType.SteamId:
                    user = await _userManager.FindBySteamIdAsync(userId);

                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(idType), idType, null);
                }

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

                await _userManager.SendSteamChatMessageAsync(user, message, tempSilence);
            }
            return(Ok());
        }
        public async Task <IHttpActionResult> GetOnePlayTimeByUser(string id, int steamAppId,
                                                                   UserIdentityType idType = UserIdentityType.Id)
        {
            string userId;

            switch (idType)
            {
            case UserIdentityType.UserName:
            {
                var user = await _userManager.FindByNameAsync(id);

                userId = user.Id;
                break;
            }

            case UserIdentityType.IdCode:
            {
                var user = await _userManager.FindByIdCodeAsync(id);

                if (user == null)
                {
                    return(NotFound());
                }
                userId = user.Id;
                break;
            }

            case UserIdentityType.Id:
                userId = id;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(idType), idType, null);
            }

            var gameRecord = await _dbContext.UserGameRecords
                             .Where(r => r.UserId == userId && r.SteamAppId == steamAppId)
                             .SingleOrDefaultAsync();

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

            return(Ok(gameRecord.TotalPlayedTime));
        }
Beispiel #5
0
        internal static Condition GetIdentityCondition(string identity, out UserIdentityType identityType)
        {
            if (string.IsNullOrWhiteSpace(identity))
            {
                throw new ArgumentNullException(nameof(identity));
            }

            if (identity.Contains("@"))
            {
                identityType = UserIdentityType.Email;
                return(Condition.Equal(nameof(IUser.Email), identity));
            }

            if (identity.IsDigits(out var digits))
            {
                identityType = UserIdentityType.Phone;
                return(Condition.Equal(nameof(IUser.Phone), digits));
            }

            identityType = UserIdentityType.Name;
            return(Condition.Equal(nameof(IUser.Name), identity));
        }
Beispiel #6
0
 //单击登录
 private void btn_login_Click(object sender, EventArgs e)
 {
     try
     {
         if (cbox_userIdentity.Text != "")
         {
             string addr = "";
             int    port = 8906;
             try
             {
                 addr               = cbox_serverIP.Text;
                 port               = Convert.ToInt32(cbox_port.Text);
                 m_userName         = cbox_userName.Text;
                 m_userIdentity     = (UserIdentityType)cbox_userIdentity.SelectedIndex;
                 m_identityPriority = Int32.Parse(cbox_identityPriority.Text);
             }
             catch (Exception)
             {
                 ShowMessage("配置有误");
             }
             if (hallForm != null && !hallForm.bReleased)
             {
                 AnyChatCoreSDK.Logout();
                 AnyChatCoreSDK.Release();
             }
             SystemSetting.Init(this.Handle);
             AnyChatCoreSDK.Connect(addr, port);
         }
         else
         {
             ShowMessage("用户名不能为空");
         }
     }
     catch (Exception ex)
     {
         Log.SetLog("QueueClient.Login.btn_login_Click       btn_login_Click:" + ex.Message.ToString());
         ShowMessage(ex.Message.ToString());
     }
 }
Beispiel #7
0
        //单击登录
        private void btn_login_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbox_userIdentity.Text != "")
                {
                    string addr = "";
                    int    port = 8906;
                    try
                    {
                        addr               = cbox_serverIP.Text;
                        port               = Convert.ToInt32(cbox_port.Text);
                        m_userName         = cbox_userName.Text;
                        m_userIdentity     = (UserIdentityType)cbox_userIdentity.SelectedIndex;
                        m_identityPriority = Int32.Parse(cbox_identityPriority.Text);
                        if (m_userIdentity == UserIdentityType.Agent)
                        {
                            if (cmbBox_Router.SelectedIndex == 1)
                            {
                                m_isAutoRouter = true;
                            }
                            else
                            {
                                m_isAutoRouter = false;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        ShowMessage("配置有误");
                    }
                    if (hallForm != null && !hallForm.bReleased)
                    {
                        AnyChatCoreSDK.Logout();
                        AnyChatCoreSDK.Release();
                    }
                    SystemSetting.Init(this.Handle);

                    /* AnyChat可以连接自主部署的服务器、也可以连接AnyChat视频云平台;
                     * 连接自主部署服务器的地址为自设的服务器IP地址或域名、端口;
                     * 连接AnyChat视频云平台的服务器地址为:cloud.anychat.cn;端口为:8906
                     */
                    AnyChatCoreSDK.Connect(addr, port);

                    /*
                     * AnyChat支持多种用户身份验证方式,包括更安全的签名登录,
                     * 详情请参考:http://bbs.anychat.cn/forum.php?mod=viewthread&tid=2211&highlight=%C7%A9%C3%FB
                     */
                    int ret = AnyChatCoreSDK.Login(m_userName, "123", 0);//登录系统

                    RecordLoginTrace();
                }
                else
                {
                    ShowMessage("用户名不能为空");
                }
            }
            catch (Exception ex)
            {
                Log.SetLog("QueueClient.Login.btn_login_Click       btn_login_Click:" + ex.Message.ToString());
                ShowMessage(ex.Message.ToString());
            }
        }
        public async Task <IHttpActionResult> GetOneByUser(string id,
                                                           bool profilePointBackgroundImage = false,
                                                           bool security           = false,
                                                           bool steam              = false,
                                                           bool steamBot           = false,
                                                           bool subscribeCount     = false,
                                                           bool stats              = false,
                                                           bool subscribed         = false,
                                                           bool moreOptions        = false,
                                                           bool commentLike        = false,
                                                           bool coupon             = false,
                                                           bool reviewStats        = false,
                                                           UserIdentityType idType = UserIdentityType.Id)
        {
            KeylolUser user;
            var        visitorId = User.Identity.GetUserId();

            switch (idType)
            {
            case UserIdentityType.UserName:
                user = await _userManager.FindByNameAsync(id);

                break;

            case UserIdentityType.IdCode:
                user = await _userManager.FindByIdCodeAsync(id);

                break;

            case UserIdentityType.Id:
                if (id == "current" && string.IsNullOrWhiteSpace(visitorId))
                {
                    return(Unauthorized());
                }
                user = await _userManager.FindByIdAsync(id == "current"?visitorId : id);

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(idType), idType, null);
            }

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

            if (user.Id == visitorId)
            {
                // 每日访问奖励
                if (DateTime.Now.Date > user.LastDailyRewardTime.Date)
                {
                    user.LastDailyRewardTime = DateTime.Now;
                    user.FreeLike            = 5; // 免费认可重置
                    try
                    {
                        await _dbContext.SaveChangesAsync();

                        await _coupon.Update(user, CouponEvent.每日访问);
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                    }
                }
            }

            var getSelf = visitorId == user.Id || User.IsInRole(KeylolRoles.Operator);

            var userDto = new UserDto(user);

            if (moreOptions)
            {
                userDto.SteamNotifyOnArticleReplied = user.SteamNotifyOnArticleReplied;
                userDto.SteamNotifyOnCommentReplied = user.SteamNotifyOnCommentReplied;
                userDto.SteamNotifyOnArticleLiked   = user.SteamNotifyOnArticleLiked;
                userDto.SteamNotifyOnCommentLiked   = user.SteamNotifyOnCommentLiked;
                userDto.AutoSubscribeEnabled        = user.AutoSubscribeEnabled;
                userDto.AutoSubscribeDaySpan        = user.AutoSubscribeDaySpan;
            }

            if (profilePointBackgroundImage)
            {
                userDto.ProfilePointBackgroundImage = user.ProfilePoint.BackgroundImage;
            }

            userDto.Roles = await _userManager.GetRolesAsync(user.Id);

            if (security)
            {
                if (!getSelf)
                {
                    return(Unauthorized());
                }
                userDto.LockoutEnabled = user.LockoutEnabled;
                userDto.Email          = user.Email;
            }

            if (steam)
            {
                if (!getSelf)
                {
                    return(Unauthorized());
                }
                userDto.SteamId = await _userManager.GetSteamIdAsync(user.Id);

                userDto.SteamProfileName = user.SteamProfileName;
            }

            if (steamBot)
            {
                if (!getSelf)
                {
                    return(Unauthorized());
                }
                if (user.SteamBotId != null)
                {
                    userDto.SteamBot = new SteamBotDto(user.SteamBot)
                    {
                        Online = user.SteamBot.IsOnline()
                    }
                }
                ;
            }

            if (coupon)
            {
                if (!getSelf)
                {
                    return(Unauthorized());
                }
                userDto.Coupon = user.Coupon;
            }

            if (subscribeCount)
            {
                userDto.SubscribedPointCount =
                    await _dbContext.Users.Where(u => u.Id == user.Id).SelectMany(u => u.SubscribedPoints).CountAsync();
            }

            if (stats)
            {
                var statsResult = await _dbContext.Users.Where(u => u.Id == user.Id)
                                  .Select(u =>
                                          new
                {
                    subscriberCount = u.ProfilePoint.Subscribers.Count,
                    articleCount    = u.ProfilePoint.Articles.Count(a => a.Archived == ArchivedState.None)
                })
                                  .SingleOrDefaultAsync();

                userDto.SubscriberCount = statsResult.subscriberCount;
                userDto.ArticleCount    = statsResult.articleCount;
            }

            if (reviewStats)
            {
                var reviewStatsResult = await _dbContext.Users.Where(u => u.Id == user.Id)
                                        .Select(u => new
                {
                    reviewCount      = u.ProfilePoint.Articles.Count(a => a.Type == ArticleType.评),
                    shortReviewCount =
                        u.ProfilePoint.Articles.Count(a => a.Type == ArticleType.简评)
                })
                                        .SingleOrDefaultAsync();

                userDto.ReviewCount      = reviewStatsResult.reviewCount;
                userDto.ShortReviewCount = reviewStatsResult.shortReviewCount;
            }

            if (subscribed)
            {
                userDto.Subscribed = await _dbContext.Users.Where(u => u.Id == visitorId)
                                     .SelectMany(u => u.SubscribedPoints)
                                     .Select(p => p.Id)
                                     .ContainsAsync(user.Id);
            }

            if (commentLike)
            {
                if (!getSelf)
                {
                    return(Unauthorized());
                }
                userDto.MessageCount = string.Join(",", new[]
                {
                    await _dbContext.Messages.Where(m => m.ReceiverId == user.Id && m.Unread &&
                                                    m.Type >= 0 && (int)m.Type <= 99)
                    .CountAsync(),
                    await _dbContext.Messages.Where(m => m.ReceiverId == user.Id && m.Unread &&
                                                    (int)m.Type >= 100 && (int)m.Type <= 199)
                    .CountAsync(),
                    await _dbContext.Messages.Where(m => m.ReceiverId == user.Id && m.Unread &&
                                                    (int)m.Type >= 200 && (int)m.Type <= 299)
                    .CountAsync()
                });
            }

            return(Ok(userDto));
        }
    }
Beispiel #9
0
		internal static Comparer GetUserIdentityComparer(string identity, string @namespace, Comparer comparer, UserEntity entity, out UserIdentityType identityType)
		{
			if(string.IsNullOrWhiteSpace(identity))
				throw new ArgumentNullException("identity");

			string text;

			// 默认条件
			comparer = comparer & comparer.Compare(entity.Namespace, "=", TrimNamespace(@namespace));

			if(Zongsoft.Text.TextRegular.Web.Email.IsMatch(identity, out text))
			{
				identityType = UserIdentityType.Email;

				comparer = comparer & comparer.Compare(entity.Email, "=", text);
			}
			else if(Zongsoft.Text.TextRegular.Chinese.Cellphone.IsMatch(identity, out text))
			{
				identityType = UserIdentityType.Phone;

				comparer = comparer & comparer.Compare(entity.PhoneNumber, "=", text);
			}
			else
			{
				identityType = UserIdentityType.Name;

				comparer = comparer & comparer.Compare(entity.Name, "=", text);
			}

			return comparer;
		}
Beispiel #10
0
        //单击登录
        private void btn_login_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbox_userIdentity.Text != "")
                {
                    string addr = "";
                    int port = 8906;
                    try
                    {
                        addr = cbox_serverIP.Text;
                        port = Convert.ToInt32(cbox_port.Text);
                        m_userName = cbox_userName.Text;
                        m_userIdentity = (UserIdentityType)cbox_userIdentity.SelectedIndex;
                        m_identityPriority = Int32.Parse(cbox_identityPriority.Text);
                    }
                    catch (Exception)
                    {
                        ShowMessage("配置有误");
                    }
                    if (hallForm != null && !hallForm.bReleased)
                    {
                        AnyChatCoreSDK.Logout();
                        AnyChatCoreSDK.Release();

                    }
                    SystemSetting.Init(this.Handle);
                    AnyChatCoreSDK.Connect(addr, port);
                }
                else
                    ShowMessage("用户名不能为空");
            }
            catch (Exception ex)
            {
                Log.SetLog("QueueClient.Login.btn_login_Click       btn_login_Click:" + ex.Message.ToString());
                ShowMessage(ex.Message.ToString());
            }
        }
		internal static ConditionCollection GetUserIdentityConditions(string identity, string @namespace, out UserIdentityType identityType)
		{
			if(string.IsNullOrWhiteSpace(identity))
				throw new ArgumentNullException("identity");

			string text;
			var conditions = new Condition[2];
			conditions[0] = new Condition("Namespace", TrimNamespace(@namespace));

			if(Zongsoft.Text.TextRegular.Web.Email.IsMatch(identity, out text))
			{
				identityType = UserIdentityType.Email;
				conditions[1] = new Condition("Email", text);
			}
			else if(Zongsoft.Text.TextRegular.Chinese.Cellphone.IsMatch(identity, out text))
			{
				identityType = UserIdentityType.Phone;
				conditions[1] = new Condition("PhoneNumber", text);
			}
			else
			{
				identityType = UserIdentityType.Name;
				conditions[1] = new Condition("Name", identity);
			}

			return new ConditionCollection(ConditionCombine.And, conditions);
		}
Beispiel #12
0
        public async Task <IHttpActionResult> GetListByUser(string userId, UserIdentityType idType,
                                                            string articleTypeFilter = null, int source = 1, int beforeSn = int.MaxValue, int take = 30)
        {
            IQueryable <KeylolUser> userQuery;

            switch (idType)
            {
            case UserIdentityType.Id:
                userQuery = _dbContext.Users.AsNoTracking().Where(u => u.Id == userId);
                break;

            case UserIdentityType.IdCode:
                userQuery = _dbContext.Users.AsNoTracking().Where(u => u.IdCode == userId);
                break;

            case UserIdentityType.UserName:
                userQuery = _dbContext.Users.AsNoTracking().Where(u => u.UserName == userId);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(idType), idType, null);
            }

            if (take > 50)
            {
                take = 50;
            }
            var publishedQuery = userQuery.SelectMany(u => u.ProfilePoint.Articles)
                                 .Where(a => a.SequenceNumber < beforeSn && a.Archived == ArchivedState.None)
                                 .Select(a => new
            {
                article = a,
                reason  = ArticleDto.TimelineReasonType.Publish,
                author  = (KeylolUser)null
            });
            var likedQuery = userQuery.SelectMany(u => u.Likes.OfType <ArticleLike>())
                             .Where(l => l.Article.SequenceNumber < beforeSn && l.Article.Archived == ArchivedState.None)
                             .Select(l => new
            {
                article = l.Article,
                reason  = ArticleDto.TimelineReasonType.Like,
                author  = l.Article.Principal.User
            });
            var published    = (source & 1) != 0;
            var liked        = (source & 1 << 1) != 0;
            var articleQuery = publishedQuery;

            if (published)
            {
                if (liked)
                {
                    articleQuery = articleQuery.Concat(likedQuery);
                }
            }
            else
            {
                if (liked)
                {
                    articleQuery = likedQuery;
                }
                else
                {
                    return(Ok());
                }
            }
            if (articleTypeFilter != null)
            {
                var types = articleTypeFilter.Split(',').Select(s => s.Trim().ToEnum <ArticleType>()).ToList();
                articleQuery = articleQuery.Where(PredicateBuilder.Contains(types, a => a.article.Type, new
                {
                    article = (Models.Article)null,
                    reason  = ArticleDto.TimelineReasonType.Like,
                    author  = (KeylolUser)null
                }));
            }
            var articleEntries = await articleQuery.GroupBy(e => e.article)
                                 .OrderByDescending(g => g.Key.SequenceNumber).Take(() => take)
                                 .Select(g => new
            {
                article    = g.Key,
                candicates = g,
                reason     = g.Max(ee => ee.reason)
            })
                                 .Select(g => new
            {
                g.article,
                g.reason,
                g.candicates.FirstOrDefault(e => e.reason == g.reason).author,
                voteForPoint = g.article.VoteForPoint,
                likeCount    = g.article.Likes.Count,
                commentCount = g.article.Comments.Count,
                type         = g.article.Type
            })
                                 .ToListAsync();

            return(Ok(articleEntries.Select(entry =>
            {
                var articleDto = new ArticleDto(entry.article, true, 256, true)
                {
                    TimelineReason = entry.reason,
                    LikeCount = entry.likeCount,
                    CommentCount = entry.commentCount,
                    TypeName = entry.type.ToString(),
                    VoteForPoint = entry.voteForPoint == null ? null : new NormalPointDto(entry.voteForPoint, true)
                };
                if (string.IsNullOrWhiteSpace(entry.article.ThumbnailImage))
                {
                    articleDto.ThumbnailImage = entry.voteForPoint?.BackgroundImage;
                }
                if (entry.type != ArticleType.简评)
                {
                    articleDto.TruncateContent(128);
                }
                if (entry.reason != ArticleDto.TimelineReasonType.Publish)
                {
                    articleDto.Author = new UserDto(entry.author);
                }
                return articleDto;
            }).ToList()));
        }