Beispiel #1
0
        public UserInfoResponse UpdateUserInfo(UserInfoRequest request, out int status, out string message)
        {
            status = 0;
            message = string.Empty;
            var response = new UserInfoResponse();
            try
            {
                IHttpOrderClient client = new HttpOrderClient(Publickey, true);
                var dic = new Dictionary<string, string>();
                var url = GetUrl(BusinessObjectPublicUser.RequestFunction.UpdateUserInfo);
                var result = client.Post(request, url, dic, Appid, Uid);

                if (result != null && result.ResponseData != null)
                {
                    status = result.Status;
                    message = result.Message;
                    ResponseMessage = result.Message;
                    Status = result.Status;
                    return SerializerObject.ProtoBufDeserialize<UserInfoResponse>(result.ResponseData, client.Saltkey);
                }
                return null;
            }
            catch (Exception exception)
            {
                status = 0;
                message = "Lỗi từ user api";
                ResponseMessage = SetResponseMessage(exception);
                return null;
            }
        }
Beispiel #2
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            ShortUserInfo localUserInfo = null;

            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                    return false;
                }

                localUserInfo = Users.GetShortUserInfo(commandParam.LocalUid);
                if (localUserInfo == null)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_USER_NOT_EXIST, commandParam.ParamList);
                    return false;
                }
            }

            if (!commandParam.CheckRequiredParams("email,fields"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            List<UserInfo> userList = new List<UserInfo>();
            List<User> userListResult = new List<User>();

            userList = Discuz.Forum.Users.GetUserListByEmail(commandParam.GetDNTParam("email").ToString().Trim());
            string fields = commandParam.GetDNTParam("fields").ToString();

            foreach (UserInfo userInfo in userList)
            {
                bool loadAuthAttr = true;
                if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
                    loadAuthAttr = userInfo.Uid == localUserInfo.Uid || localUserInfo.Adminid == 1;
                userListResult.Add(UserCommandUtils.LoadSingleUser(userInfo, fields, loadAuthAttr));
            }

            UserInfoResponse uir = new UserInfoResponse();
            uir.user_array = userListResult.ToArray();
            uir.List = true;

            if (commandParam.Format == FormatType.JSON)
            {
                result = Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userListResult.ToArray()));
            }
            else
            {
                //如果userList长度不大于1,则移除空节点会导致客户端反序列化错误
                //result = userListResult.Count > 1 ? Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString()) :
                //SerializationHelper.Serialize(uir);

                result = Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString());
            }
            return true;
        }
 private static string GetIdClaim(UserInfoResponse userInfo) => GetClaim(userInfo, "sub");
        static string GetClaim(UserInfoResponse userInfo, string claimType)
        {
            var claim = userInfo.Claims.FirstOrDefault(x => x.Type == claimType);

            return(claim?.Value);
        }
 private static string GetHasAvatarClaim(UserInfoResponse userInfo)
 => GetClaim(userInfo, CustomClaimTypes.HasAvatar);
 private static string GetNicknameClaim(UserInfoResponse userInfo) => GetClaim(userInfo, "nickname");
Beispiel #7
0
        public ActionResult <SignInResultModel> RefreshToAccess(
            [FromForm] string sRefreshToken)
        {
            //결과용
            ApiResultReady rrResult = new ApiResultReady(this);
            //엑세스 토큰 갱신용 모델
            SignInResultModel rmResult = new SignInResultModel();

            rrResult.ResultObject = rmResult;

            //API 호출 시간
            DateTime dtNow = DateTime.Now;

            //리플레시 토큰 갱신 시도 기록
            GlobalSign.LogAdd_DB(
                1
                , ModelDB.UserSignLogType.RefreshToken
                , 0
                , string.Format("RefreshToAccess 시도 : {0}", sRefreshToken));


            //토큰 갱신 요청
            TokenResponse tr = GlobalStatic.TokenProc.RefreshTokenAsync(sRefreshToken).Result;

            //기존 로그인한 유저 검색
            UserSignIn itemUSI = null;


            if (true == tr.IsError)
            {//토큰 갱신 실패
                //DB에 있는 리플레시 토큰은 수동으로 확인해서 갱신해준다.
                //토큰 정보는 메모리에 저장되기 때문에 서버가 내려갔다 올라오면 토큰정보가 날아간다.
                //이런 예외를 처리하기위해 수동으로 리플레시 토큰을 갱신해야한다.
                using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
                {
                    //기존 로그인한 유저 검색
                    itemUSI
                        = db1.UserSignIn
                          .Where(m => m.RefreshToken == sRefreshToken)
                          .FirstOrDefault();

                    if (null == itemUSI)
                    {//정보 자체가 없다.
                        rrResult.InfoCode = "-101";
                        rrResult.Message  = "갱신실패 : 인증 정보가 없습니다.";
                    }
                    else if (dtNow > itemUSI.RefreshDate)
                    {//인증정보의 유효기간이 지났다.
                        rrResult.InfoCode = "-102";
                        rrResult.Message  = "갱신실패 : 인증가능 기간이 지났습니다.";
                    }
                    else
                    {//토큰이 살아있다.
                        //유저를 검색한다.
                        User findUser
                            = db1.User
                              .Where(w => w.idUser == itemUSI.idUser)
                              .FirstOrDefault();

                        //토큰을 갱신한다.
                        tr
                            = GlobalStatic.TokenProc
                              .RequestTokenAsync(findUser.SignEmail, findUser.Password)
                              .Result;
                    }
                } //end using db1
            }     //end if (true == tr.IsError)


            if (true == rrResult.IsSuccess())
            {
                if (true == tr.IsError)
                {
                    rrResult.InfoCode = "1";
                    rrResult.Message  = "토큰 갱신에 실패하였습니다.";
                }
            }


            if (true == rrResult.IsSuccess())
            {//에러가 없다.
                //유저 정보를 받는다.
                UserInfoResponse inrUser
                    = GlobalStatic.TokenProc.UserInfoAsync(tr.AccessToken).Result;

                //유저 정보 추출
                ClaimModel cm = new ClaimModel(inrUser.Claims);

                using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
                {
                    //기존 로그인한 유저 검색
                    itemUSI
                        = db1.UserSignIn
                          .Where(m => m.idUser == cm.id_int)
                          .FirstOrDefault();

                    if (null == itemUSI)
                    {//기존 로그인 정보가 없다,
                        //이러면 강제로 토큰이 상실된 것일 수 있다.
                        rrResult.InfoCode = "1";
                        rrResult.Message  = "토큰 갱신에 실패하였습니다.";
                    }
                    else
                    {
                        //로그인 되어있는 유저정보 수정
                        itemUSI.RefreshToken = tr.RefreshToken;
                        itemUSI.RefreshDate  = dtNow.AddDays(30);

                        //db 적용
                        db1.SaveChanges();


                        //유저에게 전달할 정보 만들기
                        rmResult.idUser   = cm.id_int;
                        rmResult.Email    = cm.email;
                        rmResult.ViewName = rmResult.Email;

                        rmResult.access_token  = tr.AccessToken;
                        rmResult.refresh_token = tr.RefreshToken;


                        //기록
                        GlobalSign.LogAdd_DB(
                            1
                            , ModelDB.UserSignLogType.RefreshToken
                            , cm.id_int
                            , string.Format("RefreshToAccess 성공 : {0}", rmResult.Email));
                    }
                }//end using db1
            }

            return(rrResult.ToResult(rmResult));
        }
 private static string GetPremiumTokenClaim(UserInfoResponse userInfo)
 => GetClaim(userInfo, CustomClaimTypes.PremiumToken);
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessage(object sender, byte[] message)
        {
            var connection = (IMessageConnection)sender;
            var code       = new MessageReader <MessageCode.Peer>(message).ReadCode();

            Diagnostic.Debug($"Peer message received: {code} from {connection.Username} ({connection.IPAddress}:{connection.Port})");

            try
            {
                switch (code)
                {
                case MessageCode.Peer.SearchResponse:
                    var searchResponse = SearchResponseSlim.FromByteArray(message);
                    if (SoulseekClient.Searches.TryGetValue(searchResponse.Token, out var search))
                    {
                        search.AddResponse(searchResponse);
                    }

                    break;

                case MessageCode.Peer.BrowseResponse:
                    var browseWaitKey = new WaitKey(MessageCode.Peer.BrowseResponse, connection.Username);
                    try
                    {
                        SoulseekClient.Waiter.Complete(browseWaitKey, BrowseResponse.FromByteArray(message));
                    }
                    catch (Exception ex)
                    {
                        SoulseekClient.Waiter.Throw(browseWaitKey, new MessageReadException("The peer returned an invalid browse response.", ex));
                        throw;
                    }

                    break;

                case MessageCode.Peer.InfoRequest:
                    var outgoingInfo = await new ClientOptions()
                                       .UserInfoResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);

                    try
                    {
                        outgoingInfo = await SoulseekClient.Options
                                       .UserInfoResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Failed to resolve UserInfoResponse: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(outgoingInfo.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.BrowseRequest:
                    var browseResponse = await new ClientOptions()
                                         .BrowseResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);

                    try
                    {
                        browseResponse = await SoulseekClient.Options.BrowseResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Failed to resolve BrowseResponse: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(browseResponse.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.InfoResponse:
                    var incomingInfo = UserInfoResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.InfoResponse, connection.Username), incomingInfo);
                    break;

                case MessageCode.Peer.TransferResponse:
                    var transferResponse = TransferResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferResponse, connection.Username, transferResponse.Token), transferResponse);
                    break;

                case MessageCode.Peer.QueueDownload:
                    var queueDownloadRequest = QueueDownloadRequest.FromByteArray(message);

                    var(queueRejected, queueRejectionMessage) =
                        await TryEnqueueDownloadAsync(connection.Username, connection.IPAddress, connection.Port, queueDownloadRequest.Filename).ConfigureAwait(false);

                    if (queueRejected)
                    {
                        await connection.WriteAsync(new QueueFailedResponse(queueDownloadRequest.Filename, queueRejectionMessage).ToByteArray()).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Peer.TransferRequest:
                    var transferRequest = TransferRequest.FromByteArray(message);

                    if (transferRequest.Direction == TransferDirection.Upload)
                    {
                        SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, transferRequest.Filename), transferRequest);
                    }
                    else
                    {
                        var(transferRejected, transferRejectionMessage) = await TryEnqueueDownloadAsync(connection.Username, connection.IPAddress, connection.Port, transferRequest.Filename).ConfigureAwait(false);

                        if (transferRejected)
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, transferRejectionMessage).ToByteArray()).ConfigureAwait(false);

                            await connection.WriteAsync(new QueueFailedResponse(transferRequest.Filename, transferRejectionMessage).ToByteArray()).ConfigureAwait(false);
                        }
                        else
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, "Queued.").ToByteArray()).ConfigureAwait(false);
                        }
                    }

                    break;

                case MessageCode.Peer.QueueFailed:
                    var queueFailedResponse = QueueFailedResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, queueFailedResponse.Filename), new TransferRejectedException(queueFailedResponse.Message));
                    break;

                case MessageCode.Peer.PlaceInQueueResponse:
                    var placeInQueueResponse = PlaceInQueueResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.PlaceInQueueResponse, connection.Username, placeInQueueResponse.Filename), placeInQueueResponse);
                    break;

                case MessageCode.Peer.UploadFailed:
                    var uploadFailedResponse = UploadFailed.FromByteArray(message);
                    var msg = $"Download of {uploadFailedResponse.Filename} reported as failed by {connection.Username}.";

                    var download = SoulseekClient.Downloads.Values.FirstOrDefault(d => d.Username == connection.Username && d.Filename == uploadFailedResponse.Filename);
                    if (download != null)
                    {
                        SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, download.Username, download.Filename), new TransferException(msg));
                        SoulseekClient.Waiter.Throw(download.WaitKey, new TransferException(msg));
                    }

                    Diagnostic.Debug(msg);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled peer message: {code} from {connection.Username} ({connection.IPAddress}:{connection.Port}); {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling peer message: {code} from {connection.Username} ({connection.IPAddress}:{connection.Port}); {ex.Message}", ex);
            }
        }
Beispiel #10
0
 private void UserInfoLoadingSuccessCallback(UserInfoResponse result)
 {
     Locator.Instance.RootViewModel.UserInfo = result;
 }
Beispiel #11
0
 public AuthCreds(UserInfoResponse result)
 {
     this.UserInfo = result;
 }
        public ActionResult <SignInResultModel> RefreshToAccess(
            [FromForm] string sRefreshToken)
        {
            //결과용
            ApiResultReady rrResult = new ApiResultReady(this);
            //엑세스 토큰 갱신용 모델
            SignInResultModel armResult = new SignInResultModel();

            rrResult.ResultObject = armResult;

            //API 호출 시간
            DateTime dtNow = DateTime.Now;

            //토큰 갱신 요청
            TokenResponse tr = GlobalStatic.TokenProc.RefreshTokenAsync(sRefreshToken).Result;

            if (true == tr.IsError)
            {//에러가 있다.
                rrResult.InfoCode = "1";
                rrResult.Message  = "토큰 갱신에 실패하였습니다.";
            }
            else
            {//에러가 없다.
                //유저 정보를 받는다.
                UserInfoResponse inrUser
                    = GlobalStatic.TokenProc.UserInfoAsync(tr.AccessToken).Result;

                //유저 정보 추출
                ClaimModel cm = new ClaimModel(inrUser.Claims);

                using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
                {
                    //기존 로그인한 유저 검색
                    UserSignIn itemUSI
                        = db1.UserSignIn
                          .Where(m => m.idUser == cm.id_int)
                          .FirstOrDefault();

                    if (null == itemUSI)
                    {//기존 로그인 정보가 없다,
                        //이러면 강제로 토큰이 상실된 것일 수 있다.
                        rrResult.InfoCode = "1";
                        rrResult.Message  = "토큰 갱신에 실패하였습니다.";
                    }
                    else
                    {
                        //로그인 되어있는 유저정보 수정
                        itemUSI.RefreshToken = tr.RefreshToken;
                        itemUSI.RefreshDate  = dtNow;

                        //db 적용
                        db1.SaveChanges();


                        //유저에게 전달할 정보 만들기
                        armResult.idUser   = cm.id_int;
                        armResult.Email    = cm.email;
                        armResult.ViewName = armResult.Email;

                        armResult.access_token  = tr.AccessToken;
                        armResult.refresh_token = tr.RefreshToken;
                    }
                }
            }

            return(rrResult.ToResult(armResult));
        }
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessageRead(object sender, byte[] message)
        {
            var connection = (IMessageConnection)sender;
            var code       = new MessageReader <MessageCode.Peer>(message).ReadCode();

            Diagnostic.Debug($"Peer message received: {code} from {connection.Username} ({connection.IPEndPoint}) (id: {connection.Id})");

            try
            {
                switch (code)
                {
                case MessageCode.Peer.SearchResponse:
                    var searchResponse = SearchResponseSlim.FromByteArray(message);
                    if (SoulseekClient.Searches.TryGetValue(searchResponse.Token, out var search))
                    {
                        search.TryAddResponse(searchResponse);
                    }

                    break;

                case MessageCode.Peer.BrowseResponse:
                    var browseWaitKey = new WaitKey(MessageCode.Peer.BrowseResponse, connection.Username);
                    try
                    {
                        SoulseekClient.Waiter.Complete(browseWaitKey, BrowseResponse.FromByteArray(message));
                    }
                    catch (Exception ex)
                    {
                        SoulseekClient.Waiter.Throw(browseWaitKey, new MessageReadException("The peer returned an invalid browse response", ex));
                        throw;
                    }

                    break;

                case MessageCode.Peer.InfoRequest:
                    UserInfo outgoingInfo;

                    try
                    {
                        outgoingInfo = await SoulseekClient.Options
                                       .UserInfoResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        outgoingInfo = await new SoulseekClientOptions()
                                       .UserInfoResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);

                        Diagnostic.Warning($"Failed to resolve user info response: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(outgoingInfo.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.BrowseRequest:
                    IEnumerable <Directory> browseResponse;

                    try
                    {
                        browseResponse = await SoulseekClient.Options.BrowseResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        browseResponse = await new SoulseekClientOptions()
                                         .BrowseResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);

                        Diagnostic.Warning($"Failed to resolve browse response: {ex.Message}", ex);
                    }

                    var browseResponseMessage = new BrowseResponse(browseResponse.Count(), browseResponse);

                    await connection.WriteAsync(browseResponseMessage.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.FolderContentsRequest:
                    var       folderContentsRequest  = FolderContentsRequest.FromByteArray(message);
                    Directory outgoingFolderContents = null;

                    try
                    {
                        outgoingFolderContents = await SoulseekClient.Options.DirectoryContentsResponseResolver(
                            connection.Username,
                            connection.IPEndPoint,
                            folderContentsRequest.Token,
                            folderContentsRequest.DirectoryName).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Failed to resolve directory contents response: {ex.Message}", ex);
                    }

                    if (outgoingFolderContents != null)
                    {
                        var folderContentsResponseMessage = new FolderContentsResponse(folderContentsRequest.Token, outgoingFolderContents);

                        await connection.WriteAsync(folderContentsResponseMessage.ToByteArray()).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Peer.FolderContentsResponse:
                    var folderContentsResponse = FolderContentsResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.FolderContentsResponse, connection.Username, folderContentsResponse.Token), folderContentsResponse.Directory);
                    break;

                case MessageCode.Peer.InfoResponse:
                    var incomingInfo = UserInfoResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.InfoResponse, connection.Username), incomingInfo);
                    break;

                case MessageCode.Peer.TransferResponse:
                    var transferResponse = TransferResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferResponse, connection.Username, transferResponse.Token), transferResponse);
                    break;

                case MessageCode.Peer.QueueDownload:
                    var queueDownloadRequest = EnqueueDownloadRequest.FromByteArray(message);

                    var(queueRejected, queueRejectionMessage) =
                        await TryEnqueueDownloadAsync(connection.Username, connection.IPEndPoint, queueDownloadRequest.Filename).ConfigureAwait(false);

                    if (queueRejected)
                    {
                        await connection.WriteAsync(new EnqueueFailedResponse(queueDownloadRequest.Filename, queueRejectionMessage).ToByteArray()).ConfigureAwait(false);
                    }
                    else
                    {
                        await TrySendPlaceInQueueAsync(connection, queueDownloadRequest.Filename).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Peer.TransferRequest:
                    var transferRequest = TransferRequest.FromByteArray(message);

                    if (transferRequest.Direction == TransferDirection.Upload)
                    {
                        if (!SoulseekClient.Downloads.IsEmpty && SoulseekClient.Downloads.Values.Any(d => d.Username == connection.Username && d.Filename == transferRequest.Filename))
                        {
                            SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, transferRequest.Filename), transferRequest);
                        }
                        else
                        {
                            // reject the transfer with an empty reason.  it was probably cancelled, but we can't be sure.
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, string.Empty).ToByteArray()).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        var(transferRejected, transferRejectionMessage) = await TryEnqueueDownloadAsync(connection.Username, connection.IPEndPoint, transferRequest.Filename).ConfigureAwait(false);

                        if (transferRejected)
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, transferRejectionMessage).ToByteArray()).ConfigureAwait(false);

                            await connection.WriteAsync(new EnqueueFailedResponse(transferRequest.Filename, transferRejectionMessage).ToByteArray()).ConfigureAwait(false);
                        }
                        else
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, "Queued.").ToByteArray()).ConfigureAwait(false);
                            await TrySendPlaceInQueueAsync(connection, transferRequest.Filename).ConfigureAwait(false);
                        }
                    }

                    break;

                case MessageCode.Peer.QueueFailed:
                    var queueFailedResponse = EnqueueFailedResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, queueFailedResponse.Filename), new TransferRejectedException(queueFailedResponse.Message));
                    break;

                case MessageCode.Peer.PlaceInQueueResponse:
                    var placeInQueueResponse = PlaceInQueueResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.PlaceInQueueResponse, connection.Username, placeInQueueResponse.Filename), placeInQueueResponse);
                    break;

                case MessageCode.Peer.PlaceInQueueRequest:
                    var placeInQueueRequest = PlaceInQueueRequest.FromByteArray(message);
                    await TrySendPlaceInQueueAsync(connection, placeInQueueRequest.Filename).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.UploadFailed:
                    var uploadFailedResponse = UploadFailed.FromByteArray(message);
                    var msg = $"Download of {uploadFailedResponse.Filename} reported as failed by {connection.Username}";

                    var download = SoulseekClient.Downloads.Values.FirstOrDefault(d => d.Username == connection.Username && d.Filename == uploadFailedResponse.Filename);
                    if (download != null)
                    {
                        SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, download.Username, download.Filename), new TransferException(msg));
                    }

                    Diagnostic.Debug(msg);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled peer message: {code} from {connection.Username} ({connection.IPEndPoint}); {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling peer message: {code} from {connection.Username} ({connection.IPEndPoint}); {ex.Message}", ex);
            }
        }
Beispiel #14
0
        public string GetInfoByEmail()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return "";
            }

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return "";
            }

            if (!this.CheckRequiredParams("email"))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            List<UserInfo> userList = new List<UserInfo>();
            List<User> userListResult = new List<User>();

            userList = Discuz.Forum.Users.GetUserListByEmail(GetParam("email").ToString().Trim());

            foreach (UserInfo userInfo in userList)
            {
                userListResult.Add(LoadSingleUser(userInfo));
            }

            UserInfoResponse uir = new UserInfoResponse();
            uir.user_array = userListResult.ToArray();
            uir.List = true;

            if (Format == FormatType.JSON)
            {
                return Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userListResult.ToArray()));
            }

            if (userListResult.Count < 1)
            {
                return SerializationHelper.Serialize(uir);
            }
            return Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), GetParam("fields").ToString());
        }
Beispiel #15
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public string GetInfo()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return("");
            }

            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid < 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                    return("");
                }
            }

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return("");
            }

            if (!CheckRequiredParams("uids,fields"))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return("");
            }

            if (!Utils.IsNumericArray(GetParam("uids").ToString().Split(',')))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return("");
            }

            string[] uids = GetParam("uids").ToString().Split(',');

            if (Utils.StrToInt(uids[0], -1) < 1)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return("");
            }

            List <string> fieldlist = new List <string>(GetParam("fields").ToString().Split(','));

            List <User> userlist = new List <User>();
            UserInfo    userInfo;

            for (int i = 0; i < uids.Length; i++)
            {
                int userid = Utils.StrToInt(uids[i], -1);
                if (userid < 1)
                {
                    continue;
                }
                userInfo = Discuz.Forum.Users.GetUserInfo(userid);
                if (userInfo == null)
                {
                    continue;
                }

                User user = new User();

                user = LoadSingleUser(userInfo);

                userlist.Add(user);
            }

            UserInfoResponse uir = new UserInfoResponse();

            uir.user_array = userlist.ToArray();
            uir.List       = true;

            if (Format == FormatType.JSON)
            {
                return(Util.RemoveJsonNull(JsonConvert.SerializeObject(userlist.ToArray())));
            }
            if (userlist.Count < 1)
            {
                return(SerializationHelper.Serialize(uir));
            }
            return(Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), GetParam("fields").ToString()));
        }
Beispiel #16
0
        public async Task <UserInfoResponse> Register([FromBody] UserInfo body)
        {
            UserInfoResponse response = new UserInfoResponse();
            UsersRepository  u        = new UsersRepository();

            if (u.CheckUsersByName(body.UserName) > 0)
            {
                response.ReplyMsg = "用户已存在";
                return(response);
            }
            else if (body.UserName == "")
            {
                response.ReplyMsg = "用户名不能为空";
                return(response);
            }
            else if (body.UserPassword == "")
            {
                response.ReplyMsg = "用户密码不能为空";
                return(response);
            }
            else if (body.Sex == "")
            {
                response.ReplyMsg = "请输入您的性别";
                return(response);
            }
            else if (body.PhoneNum == "")
            {
                response.ReplyMsg = "请输入您的电话号码";
                return(response);
            }
            else if (body.Address == "")
            {
                response.ReplyMsg = "请输入您的收件地址";
                return(response);
            }
            else if (body.PostalCode == "")
            {
                response.ReplyMsg = "请输入您的邮政编码";
                return(response);
            }
            else
            {
                Users user = new Users
                {
                    UserName     = body.UserName,
                    UserPassword = body.UserPassword,
                    Sex          = body.Sex,
                    Address      = body.Address,
                    PhoneNum     = body.PhoneNum,
                    PostalCode   = body.PostalCode
                };
                var count = await u.AddUsers(user);

                if (count > 0)
                {
                    response.ReplyMsg = "注册成功";
                }
                else
                {
                    response.ReplyMsg = "注册失败";
                }
                return(response);
            }
        }
Beispiel #17
0
        public ActionResult CertificateList(Certificates certificates, string que, string save, string deletingCerts,
                                            string toContactList, Guid?userId)
        {
            var js       = new JavaScriptSerializer();
            var delCerts = (List <string>)js.Deserialize(deletingCerts, typeof(List <string>));

            string           status = "";
            Guid             token  = CheckSessionAuthState(CurrentUser, _authService);
            AddressBookModel model;

            if (token == Guid.Empty)
            {
                status       = "logoff";
                model        = new AddressBookModel();
                model.Status = status;
                return(View(model));
            }

            //удаление сертов
            if (delCerts != null && delCerts.Count > 0 && que == null)
            {
                foreach (string delCert in delCerts)
                {
                    _cryptxService.DeleteRecipientRelation(delCert, (userId == null ? Guid.Empty : (Guid)userId), token);
                }
            }

            try
            {
                CertificatesResponse response = _cryptxService.GetUserCertificates(certificates.SearchString,
                                                                                   certificates.Sort, certificates.Filter, (userId == null ? Guid.Empty : (Guid)userId), token, 0);
                model = new AddressBookModel(response);
            }
            catch (Exception exception)
            {
                model  = new AddressBookModel();
                status = "logoff";
            }
            var navigation = new MyNavigation();

            if (userId != null && userId != Guid.Empty)
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Администрирование",
                    Action     = "Index",
                    Controller = "Administration",
                    IsUrl      = true
                });
                UserInfoResponse responseUser = _authService.GetUserDataByID((Guid)userId);
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 3,
                    Name  = responseUser.User.Name,
                    IsUrl = false
                });
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 4,
                    Name  = "Список сертификатов",
                    IsUrl = false
                });
            }
            else
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Адресная книга",
                    Action     = "Index",
                    Controller = "AddressBook",
                    IsUrl      = false
                });
            }
            navigation.Navigations = navigation.Navigations.OrderBy(x => x.Depth).ToList();
            ViewBag.nav            = Helper.HtmlNavElement(navigation, Request.RequestContext);

            model.Status   = status;
            ViewBag.UserId = (userId == null ? Guid.Empty : (Guid)userId);
            return(View(model));
        }
Beispiel #18
0
 private static string GetEmailMd5Claim(UserInfoResponse userInfo)
 => GetClaim(userInfo, CustomClaimTypes.EmailMd5);
Beispiel #19
0
        public ActionResult CertificateList(Guid?userId)
        {
            string           status = "";
            Guid             token  = CheckSessionAuthState(CurrentUser, _authService);
            AddressBookModel model;

            if (token == Guid.Empty)
            {
                status       = "logoff";
                model        = new AddressBookModel();
                model.Status = status;
                return(View(model));
                //return RedirectToAction("LogOff", "Account");
            }
            try
            {
                CertificatesResponse response = _cryptxService.GetUserCertificates("", CertificateSort.FriendlyNameASC,
                                                                                   CertificateFilter.Active, (userId == null ? Guid.Empty : (Guid)userId), token, 0);
                model = new AddressBookModel(response);
            }
            catch (Exception exception)
            {
                throw;
            }

            var navigation = new MyNavigation();

            if (userId != null && userId != Guid.Empty)
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Администрирование",
                    Action     = "Index",
                    Controller = "Administration",
                    IsUrl      = true
                });
                UserInfoResponse responseUser = _authService.GetUserDataByID((Guid)userId);
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 3,
                    Name  = responseUser.User.Name,
                    IsUrl = false
                });
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 4,
                    Name  = "Список сертификатов",
                    IsUrl = false
                });
            }
            else
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Адресная книга",
                    Action     = "Index",
                    Controller = "AddressBook",
                    IsUrl      = false
                });
            }
            navigation.Navigations = navigation.Navigations.OrderBy(x => x.Depth).ToList();
            ViewBag.nav            = Helper.HtmlNavElement(navigation, Request.RequestContext);


            ViewBag.UserId = (userId == null ? Guid.Empty : (Guid)userId);
            model.Status   = status;

            return(View(model));
        }
Beispiel #20
0
 private static string GetUsernameClaim(UserInfoResponse userInfo) => GetClaim(userInfo, "preferred_username");
Beispiel #21
0
        public ActionResult ContactList(Contacts contacts, Guid?userId)
        {
            string status = "";
            Guid   token  = CheckSessionAuthState(CurrentUser, _authService);

            if (token == Guid.Empty)
            {
                status = "logoff";
                return(View(new AddressBookModel {
                    Status = status
                }));
            }

            ElFinder.CryptxService.UserAddressBookResponse response = _cryptxService.GetAddressBook(contacts.SearchString, contacts.Sort,
                                                                                                    contacts.Filter, (userId == null ? Guid.Empty : (Guid)userId), token, 0);
            var model = new AddressBookModel(response);

            model.Status   = status;
            ViewBag.UserId = userId == null ? Guid.Empty : (Guid)userId;
            var navigation = new MyNavigation();

            if (userId != null && userId != Guid.Empty)
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Администрирование",
                    Action     = "Index",
                    Controller = "Administration",
                    IsUrl      = true
                });
                UserInfoResponse responseUser = _authService.GetUserDataByID((Guid)userId);
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 3,
                    Name  = responseUser.User.Name,
                    IsUrl = false
                });
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 4,
                    Name  = "Список контактов",
                    IsUrl = false
                });
            }
            else
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Адресная книга",
                    Action     = "Index",
                    Controller = "AddressBook",
                    IsUrl      = false
                });
            }
            navigation.Navigations = navigation.Navigations.OrderBy(x => x.Depth).ToList();
            ViewBag.nav            = Helper.HtmlNavElement(navigation, Request.RequestContext);

            return(View(model));
        }
Beispiel #22
0
 private static List <string> GetRoleClaims(UserInfoResponse userInfo)
 => userInfo.Claims.Where(x => x.Type == "role").Select(x => x.Value).ToList();
Beispiel #23
0
        public ActionResult EditContact(Guid contactId, Guid?userId)
        {
            Guid token = CheckSessionAuthState(CurrentUser, _authService);

            if (token == Guid.Empty)
            {
                ViewBag.login = true;
                return(View());
            }
            Contact contact = _cryptxService.GetContact(contactId, (userId == null ? Guid.Empty : (Guid)userId), token);

            var model = new ContactCertificatesModel();

            model.ID     = contact.ID;
            model.Name   = contact.Name;
            model.Email  = contact.Email;
            model.Sort   = CertificateSort.FriendlyNameASC;
            model.Filter = CertificateFilter.All;
            //model.Certificates = contact.Certificates;
            foreach (ContactCertificateRelationship contactCertificateRelationship in contact.Certificates)
            {
                var certificate = new ContactCertificate();
                certificate.ContactId    = contact.ID;
                certificate.Id           = contactCertificateRelationship.CertificateID;
                certificate.FriendlyName = contactCertificateRelationship.FriendlyName;
                certificate.Thumbprint   = contactCertificateRelationship.CertificateInfo.Thumbprint;
                certificate.SubjectName  = contactCertificateRelationship.CertificateInfo.SubjectName;
                certificate.IsTest       = contactCertificateRelationship.CertificateInfo.IsTest;

                if (DateTime.Now < contactCertificateRelationship.CertificateInfo.NotBefore)
                {
                    certificate.TimeMessage = "Недействителен до " +
                                              contactCertificateRelationship.CertificateInfo.NotBefore.Date
                                              .ToShortDateString().Replace("/", ".");
                }
                if (DateTime.Now > contactCertificateRelationship.CertificateInfo.NotBefore &&
                    DateTime.Now < contactCertificateRelationship.CertificateInfo.NotAfter)
                {
                    certificate.TimeMessage = "Действителен до " +
                                              contactCertificateRelationship.CertificateInfo.NotAfter.Date
                                              .ToShortDateString().Replace("/", ".");
                }
                else
                {
                    certificate.TimeMessage = "Недействителен с " +
                                              contactCertificateRelationship.CertificateInfo.NotAfter.Date
                                              .ToShortDateString().Replace("/", ".");
                    certificate.TimeMessageStyle = "color: red";
                }
                if (contactCertificateRelationship.CertificateInfo != null &&
                    !string.IsNullOrEmpty(contactCertificateRelationship.CertificateInfo.Organization))
                {
                    certificate.Organization = contactCertificateRelationship.CertificateInfo.Organization;
                }
                if (contactCertificateRelationship.CertificateInfo != null &&
                    !string.IsNullOrEmpty(contactCertificateRelationship.CertificateInfo.INN))
                {
                    certificate.INN = "ИНН " + contactCertificateRelationship.CertificateInfo.INN;
                }

                model.Certificates.Add(certificate);
            }

            var navigation = new MyNavigation();

            if (userId != null && userId != Guid.Empty)
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Администрирование",
                    Action     = "Index",
                    Controller = "Administration",
                    IsUrl      = true
                });
                UserInfoResponse responseUser = _authService.GetUserDataByID((Guid)userId);
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 3,
                    Name  = responseUser.User.Name,
                    IsUrl = false
                });
                navigation.Navigations.Add(new NavElement
                {
                    Depth = 4,
                    Name  = "Контакт: " + contact.Name,
                    IsUrl = false
                });
            }
            else
            {
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 1,
                    Name       = "Адресная книга",
                    Action     = "Index",
                    Controller = "AddressBook",
                    IsUrl      = true
                });
                navigation.Navigations.Add(new NavElement
                {
                    Depth      = 2,
                    Name       = model.Name,
                    Action     = "",
                    Controller = "",
                    IsUrl      = false
                });
            }
            navigation.Navigations = navigation.Navigations.OrderBy(x => x.Depth).ToList();
            ViewBag.nav            = Helper.HtmlNavElement(navigation, Request.RequestContext);
            ViewBag.UserId         = userId == null ? Guid.Empty : (Guid)userId;
            return(View(model));
        }
Beispiel #24
0
 private static string GetAvatarUrlClaim(UserInfoResponse userInfo)
 => GetClaim(userInfo, CustomClaimTypes.AvatarUrl);
Beispiel #25
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            ShortUserInfo localUserInfo = null;

            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                    return(false);
                }

                localUserInfo = Users.GetShortUserInfo(commandParam.LocalUid);
                if (localUserInfo == null)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_USER_NOT_EXIST, commandParam.ParamList);
                    return(false);
                }
            }

            if (!commandParam.CheckRequiredParams("uids,fields"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            string[] uIds = commandParam.GetDNTParam("uids").ToString().Split(',');

            //单次最多接受查询100个用户
            if (!Utils.IsNumericArray(uIds) || Utils.StrToInt(uIds[0], -1) < 1 || uIds.Length > 100)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            List <User> userList = new List <User>();
            UserInfo    userInfo;

            for (int i = 0; i < uIds.Length; i++)
            {
                int userid = Utils.StrToInt(uIds[i], -1);
                if (userid < 1)
                {
                    continue;
                }
                userInfo = Discuz.Forum.Users.GetUserInfo(userid);
                if (userInfo == null)
                {
                    continue;
                }

                bool loadAuthAttr = true;
                if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
                {
                    loadAuthAttr = userInfo.Uid == localUserInfo.Uid || localUserInfo.Adminid == 1;
                }

                userList.Add(UserCommandUtils.LoadSingleUser(userInfo, commandParam.GetDNTParam("fields").ToString(), loadAuthAttr));
            }

            UserInfoResponse uir = new UserInfoResponse();

            uir.user_array = userList.ToArray();
            uir.List       = true;

            if (commandParam.Format == FormatType.JSON)
            {
                result = Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userList.ToArray()));
            }
            else
            {
                //如果userList长度不大于1,则移除空节点会导致客户端反序列化错误
                //result = userList.Count > 1 ? Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString()) :
                //SerializationHelper.Serialize(uir);

                result = Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString());
            }
            return(true);
        }
        private async Task <IEnumerable <Claim> > GetUserInfoClaimsAsync(string accessToken)
        {
            IEnumerable <Claim> userData = new List <Claim>();
            //Get UserInfo data when correct scope is set for SIWI and Get App now flows
            var userInfoClient = new UserInfoClient(AppController.userinfoEndpoint);

            //UserInfoResponse userInfoResponse = await userInfoClient.GetAsync(accessToken);
            UserInfoResponse userInfoResponse = await userInfoClient.GetAsync(RefreshToken);

            if (userInfoResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                //Read UserInfo Details
                userData = userInfoResponse.Json.ToClaims();

                foreach (Claim item in userData)
                {
                    if (item.Type == "sub" && item.Value != null)
                    {
                        sub = item.Value;
                    }
                    if (item.Type == "email" && item.Value != null)
                    {
                        email = item.Value;
                    }
                    if (item.Type == "emailVerified" && item.Value != null)
                    {
                        emailVerified = item.Value;
                    }
                    if (item.Type == "givenName" && item.Value != null)
                    {
                        givenName = item.Value;
                    }
                    if (item.Type == "familyName" && item.Value != null)
                    {
                        familyName = item.Value;
                    }
                    if (item.Type == "phoneNumber" && item.Value != null)
                    {
                        phoneNumber = item.Value;
                    }
                    if (item.Type == "phoneNumberVerified" && item.Value != null)
                    {
                        phoneNumberVerified = item.Value;
                    }

                    if (item.Type == "address" && item.Value != null)
                    {
                        Address jsonObject = JsonConvert.DeserializeObject <Address>(item.Value);

                        if (jsonObject.StreetAddress != null)
                        {
                            streetAddress = jsonObject.StreetAddress;
                        }
                        if (jsonObject.Locality != null)
                        {
                            locality = jsonObject.Locality;
                        }
                        if (jsonObject.Region != null)
                        {
                            region = jsonObject.Region;
                        }
                        if (jsonObject.PostalCode != null)
                        {
                            postalCode = jsonObject.PostalCode;
                        }
                        if (jsonObject.Country != null)
                        {
                            country = jsonObject.Country;
                        }
                    }
                }
            }

            return(userData);
        }
Beispiel #27
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            ShortUserInfo localUserInfo = null;

            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                    return(false);
                }

                localUserInfo = Users.GetShortUserInfo(commandParam.LocalUid);
                if (localUserInfo == null)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_USER_NOT_EXIST, commandParam.ParamList);
                    return(false);
                }
            }

            if (!commandParam.CheckRequiredParams("email,fields"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return(false);
            }

            List <UserInfo> userList       = new List <UserInfo>();
            List <User>     userListResult = new List <User>();

            userList = Discuz.Forum.Users.GetUserListByEmail(commandParam.GetDNTParam("email").ToString().Trim());
            string fields = commandParam.GetDNTParam("fields").ToString();

            foreach (UserInfo userInfo in userList)
            {
                bool loadAuthAttr = true;
                if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
                {
                    loadAuthAttr = userInfo.Uid == localUserInfo.Uid || localUserInfo.Adminid == 1;
                }
                userListResult.Add(UserCommandUtils.LoadSingleUser(userInfo, fields, loadAuthAttr));
            }

            UserInfoResponse uir = new UserInfoResponse();

            uir.user_array = userListResult.ToArray();
            uir.List       = true;

            if (commandParam.Format == FormatType.JSON)
            {
                result = Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userListResult.ToArray()));
            }
            else
            {
                //如果userList长度不大于1,则移除空节点会导致客户端反序列化错误
                //result = userListResult.Count > 1 ? Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString()) :
                //SerializationHelper.Serialize(uir);

                result = Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString());
            }
            return(true);
        }
Beispiel #28
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            ShortUserInfo localUserInfo = null;

            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                    return false;
                }

                localUserInfo = Users.GetShortUserInfo(commandParam.LocalUid);
                if (localUserInfo == null)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_USER_NOT_EXIST, commandParam.ParamList);
                    return false;
                }
            }

            if (!commandParam.CheckRequiredParams("uids,fields"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            string[] uIds = commandParam.GetDNTParam("uids").ToString().Split(',');

            //单次最多接受查询100个用户
            if (!Utils.IsNumericArray(uIds) || Utils.StrToInt(uIds[0], -1) < 1 || uIds.Length > 100)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            List<User> userList = new List<User>();
            UserInfo userInfo;
            for (int i = 0; i < uIds.Length; i++)
            {
                int userid = Utils.StrToInt(uIds[i], -1);
                if (userid < 1)
                    continue;
                userInfo = Discuz.Forum.Users.GetUserInfo(userid);
                if (userInfo == null)
                    continue;

                bool loadAuthAttr = true;
                if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
                    loadAuthAttr = userInfo.Uid == localUserInfo.Uid || localUserInfo.Adminid == 1;

                userList.Add(UserCommandUtils.LoadSingleUser(userInfo, commandParam.GetDNTParam("fields").ToString(), loadAuthAttr));
            }

            UserInfoResponse uir = new UserInfoResponse();
            uir.user_array = userList.ToArray();
            uir.List = true;

            if (commandParam.Format == FormatType.JSON)
            {
                result = Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userList.ToArray()));
            }
            else
            {
                //如果userList长度不大于1,则移除空节点会导致客户端反序列化错误
                //result = userList.Count > 1 ? Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString()) :
                //SerializationHelper.Serialize(uir);

                result = Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), commandParam.GetDNTParam("fields").ToString());
            }
            return true;
        }
        /// <summary>
        /// Start code exchange to get the Access Token and Refresh Token
        /// </summary>
        /// <returns></returns>
        public async System.Threading.Tasks.Task performCodeExchange()
        {
            output("Exchanging code for tokens.");

            string id_token            = "";
            string refresh_token       = "";
            string access_token        = "";
            bool   isTokenValid        = false;
            string sub                 = "";
            string email               = "";
            string emailVerified       = "";
            string givenName           = "";
            string familyName          = "";
            string phoneNumber         = "";
            string phoneNumberVerified = "";
            string streetAddress       = "";
            string locality            = "";
            string region              = "";
            string postalCode          = "";
            string country             = "";



            //Request Oauth2 tokens
            var tokenClient = new TokenClient(tokenEndpoint, clientID, clientSecret);

            TokenResponse accesstokenCallResponse = await tokenClient.RequestTokenFromCodeAsync(code, redirectURI);

            if (accesstokenCallResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                //save the refresh token in persistent store so that it can be used to refresh short lived access tokens
                refresh_token = accesstokenCallResponse.RefreshToken;
                if (!dictionary.ContainsKey("refreshToken"))
                {
                    dictionary.Add("refreshToken", refresh_token);
                }


                output("Refresh token obtained.");

                //access token
                access_token = accesstokenCallResponse.AccessToken;
                output("Access token obtained.");

                if (!dictionary.ContainsKey("accessToken"))
                {
                    dictionary.Add("accessToken", access_token);
                }

                //Identity Token (returned only for OpenId scope)
                id_token = accesstokenCallResponse.IdentityToken;
                output("Id token obtained.");

                //validate idToken
                isTokenValid = await isIdTokenValid(id_token);

                output("Validating Id Token.");

                output("Calling UserInfo");
                //get userinfo
                //This will work only for SIWI and Get App Now(OpenId) flows
                //Since C2QB flow does not has the required scopes, you will get exception.
                //Here we will handle the exeception and then finally make Payments api call
                //In your code, based on your workflows/scope, you can choose to not make this call
                UserInfoResponse userInfoResponse = await getUserInfo(access_token, refresh_token);

                if (userInfoResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    //Read UserInfo Details
                    IEnumerable <System.Security.Claims.Claim> userData = userInfoResponse.Json.ToClaims();

                    foreach (System.Security.Claims.Claim item in userData)
                    {
                        if (item.Type == "sub" && item.Value != null)
                        {
                            sub = item.Value;
                        }
                        if (item.Type == "email" && item.Value != null)
                        {
                            email = item.Value;
                        }
                        if (item.Type == "emailVerified" && item.Value != null)
                        {
                            emailVerified = item.Value;
                        }
                        if (item.Type == "givenName" && item.Value != null)
                        {
                            givenName = item.Value;
                        }
                        if (item.Type == "familyName" && item.Value != null)
                        {
                            familyName = item.Value;
                        }
                        if (item.Type == "phoneNumber" && item.Value != null)
                        {
                            phoneNumber = item.Value;
                        }
                        if (item.Type == "phoneNumberVerified" && item.Value != null)
                        {
                            phoneNumberVerified = item.Value;
                        }

                        if (item.Type == "address" && item.Value != null)
                        {
                            Address jsonObject = JsonConvert.DeserializeObject <Address>(item.Value);

                            if (jsonObject.StreetAddress != null)
                            {
                                streetAddress = jsonObject.StreetAddress;
                            }
                            if (jsonObject.Locality != null)
                            {
                                locality = jsonObject.Locality;
                            }
                            if (jsonObject.Region != null)
                            {
                                region = jsonObject.Region;
                            }
                            if (jsonObject.PostalCode != null)
                            {
                                postalCode = jsonObject.PostalCode;
                            }
                            if (jsonObject.Country != null)
                            {
                                country = jsonObject.Country;
                            }
                        }
                    }
                }
            }
            else if (accesstokenCallResponse.HttpStatusCode == HttpStatusCode.Unauthorized && Session["RefreshToken"] != null)
            {
                //Validate if refresh token was already saved in session and use that to regenerate the access token.

                output("Exchanging refresh token for access token.");
                //Handle exception 401 and then make this call
                // Call RefreshToken endpoint to get new access token when you recieve a 401 Status code
                TokenResponse refereshtokenCallResponse = await performRefreshToken(refresh_token);

                if (accesstokenCallResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    //save the refresh token in persistent store so that it can be used to refresh short lived access tokens
                    refresh_token = accesstokenCallResponse.RefreshToken;
                    if (!dictionary.ContainsKey("refreshToken"))
                    {
                        dictionary.Add("refreshToken", refresh_token);
                    }
                    else
                    {
                        dictionary["refreshToken"] = refresh_token;
                    }

                    output("Refresh token obtained.");


                    //access token
                    access_token = accesstokenCallResponse.AccessToken;

                    output("Access token obtained.");
                    if (!dictionary.ContainsKey("accessToken"))
                    {
                        dictionary.Add("accessToken", access_token);
                    }
                    else
                    {
                        dictionary["accessToken"] = access_token;
                    }


                    //Identity Token (returned only for OpenId scope)
                    id_token = accesstokenCallResponse.IdentityToken;
                    output("Id token obtained.");

                    //validate idToken
                    isTokenValid = await isIdTokenValid(id_token);

                    output("Validating Id Token.");


                    output("Calling UserInfo");
                    //get userinfo
                    //This will work only for SIWI and Get App Now(OpenId) flows
                    //Since C2QB flow does not has the required scopes, you will get exception.
                    //Here we will handle the exeception and then finally make Payments api call
                    //In your code, based on your workflows/scope, you can choose to not make this call
                    UserInfoResponse userInfoResponse = await getUserInfo(access_token, refresh_token);

                    if (userInfoResponse.HttpStatusCode == HttpStatusCode.OK)
                    {
                        //Read UserInfo Details
                        IEnumerable <System.Security.Claims.Claim> userData = userInfoResponse.Json.ToClaims();

                        foreach (System.Security.Claims.Claim item in userData)
                        {
                            if (item.Type == "sub" && item.Value != null)
                            {
                                sub = item.Value;
                            }
                            if (item.Type == "email" && item.Value != null)
                            {
                                email = item.Value;
                            }
                            if (item.Type == "emailVerified" && item.Value != null)
                            {
                                emailVerified = item.Value;
                            }
                            if (item.Type == "givenName" && item.Value != null)
                            {
                                givenName = item.Value;
                            }
                            if (item.Type == "familyName" && item.Value != null)
                            {
                                familyName = item.Value;
                            }
                            if (item.Type == "phoneNumber" && item.Value != null)
                            {
                                phoneNumber = item.Value;
                            }
                            if (item.Type == "phoneNumberVerified" && item.Value != null)
                            {
                                phoneNumberVerified = item.Value;
                            }

                            if (item.Type == "address" && item.Value != null)
                            {
                                Address jsonObject = JsonConvert.DeserializeObject <Address>(item.Value);

                                if (jsonObject.StreetAddress != null)
                                {
                                    streetAddress = jsonObject.StreetAddress;
                                }
                                if (jsonObject.Locality != null)
                                {
                                    locality = jsonObject.Locality;
                                }
                                if (jsonObject.Region != null)
                                {
                                    region = jsonObject.Region;
                                }
                                if (jsonObject.PostalCode != null)
                                {
                                    postalCode = jsonObject.PostalCode;
                                }
                                if (jsonObject.Country != null)
                                {
                                    country = jsonObject.Country;
                                }
                            }
                        }
                    }
                }
            }


            //Redirect to pop-up window for C2QB and SIWI flows

            if (dictionary["callMadeBy"] == "OpenId")
            {
                if (Request.Url.Query == "")
                {
                    Response.Redirect(Request.RawUrl);
                }
                else
                {
                    Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""));
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public string GetInfo()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return "";
            }

            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid < 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                    return "";
                }
            }

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return "";
            }

            if (!CheckRequiredParams("uids,fields"))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            if (!Utils.IsNumericArray(GetParam("uids").ToString().Split(',')))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            string[] uids = GetParam("uids").ToString().Split(',');

            if (Utils.StrToInt(uids[0], -1) < 1)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            List<string> fieldlist = new List<string>(GetParam("fields").ToString().Split(','));

            List<User> userlist = new List<User>();
            UserInfo userInfo;
            for (int i = 0; i < uids.Length; i++)
            {
                int userid = Utils.StrToInt(uids[i], -1);
                if (userid < 1)
                    continue;
                userInfo = Discuz.Forum.Users.GetUserInfo(userid);
                if (userInfo == null)
                    continue;

                User user = new User();

                user = LoadSingleUser(userInfo);

                userlist.Add(user);
            }

            UserInfoResponse uir = new UserInfoResponse();
            uir.user_array = userlist.ToArray();
            uir.List = true;

            if (Format == FormatType.JSON)
            {
                return Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userlist.ToArray()));
            }
            if (userlist.Count < 1)
            {
                return SerializationHelper.Serialize(uir);
            }
            return Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), GetParam("fields").ToString());
        }
Beispiel #31
0
        /// <summary>
        /// 注册用户
        /// </summary>
        public UserInfoResponse AddUser(UserRequest userRequest)
        {
            UserInfoResponse response = ApiRequestHelper.Post <UserRequest, UserInfoResponse>(userRequest);

            return(response);
        }
Beispiel #32
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public string GetInfo()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return "";
            }

            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid < 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                    return "";
                }
            }

            //if (Uid < 1)
            //{
            //    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
            //    return "";
            //}

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return "";
            }

            if (!CheckRequiredParams("uids,fields"))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            if (!Utils.IsNumericArray(GetParam("uids").ToString().Split(',')))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }


            //if (GetParam("uids") == null || GetParam("fields") == null)
            //{
            //    ErrorCode = (int)ErrorType.API_EC_PARAM;
            //    return "";
            //}
            string[] uids = GetParam("uids").ToString().Split(',');

            if (Utils.StrToInt(uids[0], -1) < 1)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            List<string> fieldlist = new List<string>(GetParam("fields").ToString().Split(','));
            

            List<User> userlist = new List<User>();
            UserInfo userInfo;
            for (int i = 0; i < uids.Length; i++)
            {
                int userid = Utils.StrToInt(uids[i], -1);
                if (userid < 1)
                    continue;
                userInfo = Discuz.Forum.Users.GetUserInfo(userid);
                if (userInfo == null)
                    continue;

                User user = new User();
                if (fieldlist.Contains("access_masks"))
                {
                    user.AccessMasks = userInfo.Accessmasks;
                }
                else
                {
                    user.AccessMasks = null;
                }

                if (fieldlist.Contains("admin_id"))
                {
                    user.AdminId = userInfo.Adminid;
                }
                else
                {
                    user.AdminId = null;
                }

                //user.AvatarShowId = userinfo.Avatarshowid;

                if (fieldlist.Contains("birthday"))
                {
                    user.Birthday = userInfo.Bday.Trim();
                }
                else
                {
                    user.Birthday = null;
                }

                if (fieldlist.Contains("credits"))
                {
                    user.Credits = userInfo.Credits;
                }
                else
                {
                    user.Credits = null;
                }

                if (fieldlist.Contains("digest_post_count"))
                {
                    user.DigestPosts = userInfo.Digestposts;
                }
                else
                {
                    user.DigestPosts = null;
                }

                if (fieldlist.Contains("email"))
                {
                    user.Email = userInfo.Email.Trim();
                }
                else
                {
                    user.Email = null;
                }

                if (fieldlist.Contains("ext_credits_1"))
                {
                    user.ExtCredits1 = userInfo.Extcredits1;
                }
                else
                {
                    user.ExtCredits1 = null;
                }

                if (fieldlist.Contains("ext_credits_2"))
                {
                    user.ExtCredits2 = userInfo.Extcredits2;
                }
                else
                {
                    user.ExtCredits2 = null;
                }

                if (fieldlist.Contains("ext_credits_3"))
                {
                    user.ExtCredits3 = userInfo.Extcredits3;
                }
                else
                {
                    user.ExtCredits3 = null;
                }

                if (fieldlist.Contains("ext_credits_4"))
                {
                    user.ExtCredits4 = userInfo.Extcredits4;
                }
                else
                {
                    user.ExtCredits4 = null;
                }

                if (fieldlist.Contains("ext_credits_5"))
                {
                    user.ExtCredits5 = userInfo.Extcredits5;
                }
                else
                {
                    user.ExtCredits5 = null;    
                }

                if (fieldlist.Contains("ext_credits_6"))
                {
                    user.ExtCredits6 = userInfo.Extcredits6;
                }
                else
                {
                    user.ExtCredits6 = null;
                }

                if (fieldlist.Contains("ext_credits_7"))
                {
                    user.ExtCredits7 = userInfo.Extcredits7;
                }
                else
                {
                    user.ExtCredits7 = null;
                }

                if (fieldlist.Contains("ext_credits_8"))
                {
                    user.ExtCredits8 = userInfo.Extcredits8;
                }
                else
                {
                    user.ExtCredits8 = null;
                }

                if (fieldlist.Contains("ext_groupids"))
                {
                    user.ExtGroupids = userInfo.Extgroupids.Trim();
                }
                else
                {
                    user.ExtGroupids = null;
                }

                if (fieldlist.Contains("gender"))
                {
                    user.Gender = userInfo.Gender;
                }
                else
                {
                    user.Gender = null;
                }

                if (fieldlist.Contains("group_expiry"))
                {
                    user.GroupExpiry = userInfo.Groupexpiry;
                }
                else
                {
                    user.GroupExpiry = null;
                }

                if (fieldlist.Contains("group_id"))
                {
                    user.GroupId = userInfo.Groupid;
                }
                else
                {
                    user.GroupId = null;
                }

                if (fieldlist.Contains("invisible"))
                {
                    user.Invisible = userInfo.Invisible;
                }
                else
                {
                    user.Invisible = null;
                }

                if (fieldlist.Contains("join_date"))
                {
                    user.JoinDate = userInfo.Joindate;
                }
                else
                {
                    user.JoinDate = null;
                }

                if (fieldlist.Contains("last_activity"))
                {
                    user.LastActivity = userInfo.Lastactivity;
                }
                else
                {
                    user.LastActivity = null;
                }

                if (fieldlist.Contains("last_ip"))
                {
                    user.LastIp = userInfo.Lastip.Trim();
                }
                else
                {
                    user.LastIp = null;
                }

                if (fieldlist.Contains("last_post"))
                {
                    user.LastPost = userInfo.Lastpost;
                }
                else
                {
                    user.LastPost = null;
                }

                if (fieldlist.Contains("last_post_id"))
                {
                    user.LastPostid = userInfo.Lastpostid;
                }
                else
                {
                    user.LastPostid = null;
                }

                if (fieldlist.Contains("last_post_title"))
                {
                    user.LastPostTitle = userInfo.Lastposttitle;
                }
                else
                {
                    user.LastPostTitle = null;
                }

                if (fieldlist.Contains("last_visit"))
                {
                    user.LastVisit = userInfo.Lastvisit;
                }
                else
                {
                    user.LastVisit = null;
                }

                if (fieldlist.Contains("has_new_pm"))
                {
                    user.NewPm = userInfo.Newpm;
                }
                else
                {
                    user.NewPm = null;
                }

                if (fieldlist.Contains("new_pm_count"))
                {
                    user.NewPmCount = userInfo.Newpmcount;
                }
                else
                {
                    user.NewPmCount = null;
                }

                if (fieldlist.Contains("nick_name"))
                {
                    user.NickName = userInfo.Nickname;
                }
                else
                {
                    user.NickName = null;
                }

                if (fieldlist.Contains("online_state"))
                {
                    user.OnlineState = userInfo.Onlinestate;
                }
                else
                {
                    user.OnlineState = null;
                }

                if (fieldlist.Contains("online_time"))
                {
                    user.OnlineTime = userInfo.Oltime;
                }
                else
                {
                    user.OnlineTime = null;
                }

                if (fieldlist.Contains("page_view_count"))
                {
                    user.PageViews = userInfo.Pageviews;
                }
                else
                {
                    user.PageViews = null;
                }


                //if (Uid > 0 && userid == Uid)
                //{
                    if (fieldlist.Contains("password"))
                    {
                        user.Password = userInfo.Password;
                    }
                    else
                    {
                        user.Password = null;
                    }
                //}

                if (fieldlist.Contains("pm_sound"))
                {
                    user.PmSound = userInfo.Pmsound;
                }
                else
                {
                    user.PmSound = null;
                }

                if (fieldlist.Contains("post_count"))
                {
                    user.Posts = userInfo.Posts;
                }
                else
                {
                    user.Posts = null;
                }

                if (fieldlist.Contains("ppp"))
                {
                    user.Ppp = userInfo.Ppp;
                }
                else
                {
                    user.Ppp = null;
                }

                if (fieldlist.Contains("reg_ip"))
                {
                    user.RegIp = userInfo.Regip;
                }
                else
                {
                    user.RegIp = null;
                }

                if (fieldlist.Contains("secques"))
                {
                    user.Secques = userInfo.Secques;
                }
                else
                {
                    user.Secques = null;
                }

                if (fieldlist.Contains("show_email"))
                {
                    user.ShowEmail = userInfo.Showemail;
                }
                else
                {
                    user.ShowEmail = null;
                }

                //user.SigStatus = userinfo.Sigstatus;

                if (fieldlist.Contains("space_id"))
                {
                    user.SpaceId = userInfo.Spaceid;
                }
                else
                {
                    user.SpaceId = null;
                }

                if (fieldlist.Contains("template_id"))
                {
                    user.Templateid = userInfo.Templateid;
                }
                else
                {
                    user.Templateid = null;
                }

                if (fieldlist.Contains("tpp"))
                {
                    user.Tpp = userInfo.Tpp;
                }
                else
                {
                    user.Tpp = null;
                }

                if (fieldlist.Contains("uid"))
                {
                    user.Uid = userInfo.Uid;
                }
                else
                {
                    user.Uid = null;
                }

                if (fieldlist.Contains("user_name"))
                {
                    user.UserName = userInfo.Username;
                }
                else
                {
                    user.UserName = null;
                }

                if (fieldlist.Contains("custom_status"))
                {
                    user.CustomStatus = userInfo.Customstatus;	//自定义头衔
                }
                else
                {
                    user.CustomStatus = null;
                }


                if (fieldlist.Contains("avatar"))
                {
                    user.Avatar = Avatars.GetAvatarUrl(userInfo.Uid).TrimStart('/');
                }
                else
                {
                    user.Avatar = null;
                }

                //if (fieldlist.Contains("avatar_width"))
                //{
                //    user.AvatarWidth = userinfo.Avatarwidth;	//头像宽度
                //}
                //else
                //{
                //    user.AvatarWidth = null;
                //}

                //if (fieldlist.Contains("avatar_height"))
                //{
                //    user.AvatarHeight = userinfo.Avatarheight;	//头像高度
                //}
                //else
                //{
                //    user.AvatarHeight = null;
                //}

                if (fieldlist.Contains("medals"))
                {
                    user.Medals = userInfo.Medals; //勋章列表
                }
                else
                {
                    user.Medals = null;
                }

                //if没有sessionkey 就不显示个人信息

                if (fieldlist.Contains("web_site"))
                {
                    user.WebSite = userInfo.Website;	//网站
                }
                else
                {
                    user.WebSite = null;
                }

                if (fieldlist.Contains("icq"))
                {
                    user.Icq = userInfo.Icq;	//icq号码
                }
                else
                {
                    user.Icq = null;
                }

                if (fieldlist.Contains("qq"))
                {
                    user.Qq = userInfo.Qq;	//qq号码
                }
                else
                {
                    user.Qq = null;
                }

                if (fieldlist.Contains("yahoo"))
                {
                    user.Yahoo = userInfo.Yahoo;	//yahoo messenger帐号
                }
                else
                {
                    user.Yahoo = null;
                }

                if (fieldlist.Contains("msn"))
                {
                    user.Msn = userInfo.Msn;	//msn messenger帐号
                }
                else
                {
                    user.Msn = null;
                }

                if (fieldlist.Contains("skype"))
                {
                    user.Skype = userInfo.Skype;	//skype帐号
                }
                else
                {
                    user.Skype = null;
                }

                if (fieldlist.Contains("location"))
                {
                    user.Location = userInfo.Location;	//来自
                }
                else
                {
                    user.Location = null;
                }

                if (fieldlist.Contains("about_me"))
                {
                    user.Bio = userInfo.Bio;	//自我介绍
                }
                else
                {
                    user.Bio = null;
                }

                //if (Uid > 1)
                //{
                //    user.Signature = userinfo.Signature;	//签名
                //}

                if (fieldlist.Contains("signhtml"))
                {
                    user.Sightml = userInfo.Sightml;	//签名Html(自动转换得到)
                }
                else
                {
                    user.Sightml = null;
                }


                //user.AuthStr = userinfo.Authstr;	//验证码
                //user.AuthTime = userinfo.Authtime;	//验证码生成日期
                //user.AuthFlag = userinfo.Authflag;	//验证码使用标志(0 未使用,1 用户邮箱验证及用户信息激活, 2 用户密码找回)

                if (fieldlist.Contains("real_name"))
                {
                    user.RealName = userInfo.Realname;  //用户实名
                }
                else
                {
                    user.RealName = null;
                }

                if (fieldlist.Contains("id_card"))
                {
                    user.IdCard = userInfo.Idcard;    //用户身份证件号
                }
                else 
                {
                    user.IdCard = null;
                }

                if (fieldlist.Contains("mobile"))
                {
                    user.Mobile = userInfo.Mobile;    //用户移动电话
                }
                else
                {
                    user.Mobile = null;
                }

                if (fieldlist.Contains("telephone"))
                {
                    user.Phone = userInfo.Phone;     //用户固定电话
                }
                else
                {
                    user.Phone = null;
                }
                userlist.Add(user);
            }

            UserInfoResponse uir = new UserInfoResponse();
            uir.user_array = userlist.ToArray();
            uir.List = true;

            if (Format == FormatType.JSON)
            {
                return Util.RemoveJsonNull(JavaScriptConvert.SerializeObject(userlist.ToArray()));
            }
            if (userlist.Count < 1)
            {
                return SerializationHelper.Serialize(uir);
            }
            return Util.RemoveEmptyNodes(SerializationHelper.Serialize(uir), GetParam("fields").ToString()); 
        }
 public static string GetClaim(this UserInfoResponse userInfo, string type) =>
 userInfo.Claims.SingleOrDefault(c => c.Type == type)?.Value;