public override async Task <QueryDataResponse> QueryData(QueryDataRequest request, ServerCallContext context)
        {
            QueryDataResponse response   = new QueryDataResponse();
            IConnection       connection = null;

            try
            {
                _log.LogDebug("got a request: {0}", request);
                connection = _connections.Get(request.PluginContext.DataSourceInstanceSettings);

                var uaQueries      = request.Queries.Select(q => new OpcUAQuery(q));
                var invalidQueries = GetInvalidQueries(uaQueries);//uaQueries.Where(a => a.nodePath != null).ToLookup(a => a.refId);

                var queryGroups = uaQueries.Where(a => !invalidQueries.ContainsKey(a.refId)).ToLookup(o => o.readType);
                var nsTable     = connection.Session.NamespaceUris;
                foreach (var queryGroup in queryGroups)
                {
                    var queries = queryGroup.ToArray();
                    try
                    {
                        Result <DataResponse>[] responses = null;
                        switch (queryGroup.Key)
                        {
                        case "ReadNode":
                            responses = ReadNodes(connection.Session, queries, nsTable);
                            break;

                        case "Subscribe":
                            responses = SubscribeDataValues(connection.Session, connection.DataValueSubscription, queries, nsTable);
                            break;

                        case "ReadDataRaw":
                            responses = ReadHistoryRaw(connection.Session, queries, nsTable);
                            break;

                        case "ReadDataProcessed":
                            responses = ReadHistoryProcessed(connection.Session, queries, nsTable);
                            break;

                        case "ReadEvents":
                            responses = ReadEvents(connection.Session, connection.EventDataResponse, queries, nsTable);
                            break;

                        case "SubscribeEvents":
                            responses = SubscribeEvents(connection.Session, connection.EventSubscription, queries, nsTable);
                            break;

                        case "Resource":
                            responses = null;
                            break;
                        }
                        if (responses != null)
                        {
                            int i = 0;
                            foreach (var dataResponse in responses)
                            {
                                if (dataResponse.Success)
                                {
                                    response.Responses[queries[i++].refId] = dataResponse.Value;
                                }
                                else
                                {
                                    var dr = new DataResponse();
                                    dr.Error = string.Format("{0} {1}", dataResponse.StatusCode.ToString(), dataResponse.Error);
                                    _log.LogError(dr.Error);
                                    response.Responses[queries[i++].refId] = dr;
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        foreach (var q in queries)
                        {
                            var dr = new DataResponse();
                            dr.Error = e.ToString();
                            response.Responses[q.refId] = dr;
                        }
                        _log.LogError(e.ToString());
                    }
                }
                foreach (var invalidQuery in invalidQueries)
                {
                    var refId   = invalidQuery.Key;
                    var message = invalidQuery.Value;
                    var dr      = new DataResponse();
                    dr.Error = message;
                    response.Responses[refId] = dr;
                    _log.LogError(message);
                }
            }
            catch (Exception ex)
            {
                // Close out the client connection.
                _log.LogError("Error: {0}", ex);
                connection?.Close();
            }

            return(await Task.FromResult(response));
        }
Esempio n. 2
0
        public ActionResult Index(string code = "")
        {
            //return Content(String.Format("access code: {0}", code));
            if (SystemManager.IsDesignMode || SystemManager.IsPreviewMode)
            {
                return(View("Index"));
            }
            this.CreateOrUpdateCookie("cd", code);

            QueryDataResponse <HelixIndividual> qryIndv = new QueryDataResponse <HelixIndividual>()
            {
                ResponseStatus = ResponseStatus.Warning
            };
            //VisitUserModel bfAuth = this.GetSetAppSiteUser();
            VisitUserModel authUser  = new VisitUserModel(); //this.GetSessionInforByUserId(this.MyId()).ToVisitUserModel();
            string         returnUrl = this.GetCookieValue("reqUri");

#if DEBUG
            log.InfoFormat("myId in login:{0}, code:{1}", this.MyId(), code);
#endif

            // if not login & have a code then do authentication
            if ((this.MyId().IsNullOrEmptyGuid() || this.MyId().IsOneGuid()) && !String.IsNullOrEmpty(code))
            {
                this.SiteAppRunner().AppServiceClient
                .Then(cl =>
                {
                    HelixServiceClient client = cl as HelixServiceClient;
                    HelixIndividual helixIndv = new HelixIndividual();

                    client.ActivateHelixbyCode(code);
                    qryIndv = client.DataResponse();
                    if (qryIndv.ResponseStatus.Is(ResponseStatus.Success))
                    {
                        helixIndv = qryIndv.Result;

                        // RWB 20171013 Test
                        this.CreateOrUpdateCookie("IAFC", $"ContactId={helixIndv.MembershipId}&Password=H5erUjDICjI7EM4zJG3%2byg%3d%3d");
                        // RWB 20171013 Test

                        // RWB 20171012 - Username must be an email address for new accounts
                        helixIndv.UserName   = helixIndv.Email;
                        VisitUserModel _vusr = helixIndv;     // derived from the same class base
                        _vusr.ClientId       = helixIndv.Client_id;
                        _vusr.Title          = helixIndv.Title;
                        _vusr.ClientToken    = new ServiceTokenModel()
                        {
                            ClientId      = helixIndv.MembershipId,
                            ClientName    = helixIndv.Email,
                            Token         = helixIndv.access_token,
                            IssueTime     = DateTime.UtcNow,
                            ExpireTime    = DateTime.UtcNow.AddMinutes(12),
                            Refresh_token = helixIndv.Refresh_token,
                            Message       = (new HelixIndividual()
                            {
                                Title = helixIndv.Title, Client_id = helixIndv.Client_id, MembershipId = helixIndv.MembershipId
                            }).SerializeToString()
                                            //Message = (new { Title = helixIndv.Title, MembershipId = helixIndv.MembershipId, Client_id = helixIndv.Client_id }).ToJson()
                        };
                        _vusr.ReturnUrl = returnUrl;
                        _vusr.Profile   = new VisitorProfile()
                        {
                            Roles = new List <UserRole>()
                            {
                                new UserRole()
                                {
                                    Name = "NonMember"
                                }
                            }
                        };

                        /*if (!String.IsNullOrEmpty(helixIndv.MembershipId))
                         * {
                         *  _vusr.Profile.Roles = new List<UserRole>() { new UserRole() { Name = "Member" } };
                         * }*/
                        if (!String.IsNullOrEmpty(helixIndv.roles) && helixIndv.roles.ToLower().IndexOf("iafcmember") >= 0)
                        {
                            _vusr.Profile.Roles = new List <UserRole>()
                            {
                                new UserRole()
                                {
                                    Name = "Member"
                                }
                            };
                        }


#if DEBUG
                        log.InfoFormat("convert user from Helix is: {0}",
                                       (new
                        {
                            helix = helixIndv,
                            Vuser = _vusr,
                            ActivateMis = String.Format("{0}/{1}/{2}/true", ConfigurationManager.AppSettings["iMiSLoginBaseUri"]?.ToString(),
                                                        ConfigurationManager.AppSettings["iMiSLogin"], _vusr.UserName),
                        }).SerializeToString());
#endif

                        /*client
                         * .LoginToIMis(System.Web.HttpContext.Current, ConfigurationManager.AppSettings["iMiSLoginBaseUri"],
                         * ConfigurationManager.AppSettings["iMiSLogin"], ((VisitorModel)_vusr).UserName);*/


                        this.CreateOrUpdateCookie("ud", _vusr.ClientId);


                        QueryDataResponse <VisitUserModel> sfResponse = new QueryDataResponse <VisitUserModel>();
                        client.AuthenticateBy((cnn, _srv) =>
                        {
                            sfResponse = _srv.GetAuthResponse(_vusr);

                            if (sfResponse.ResponseStatus.Is(ResponseStatus.Success))
                            {
                                // login to iMIS

                                /*client
                                 * .LoginToIMis(ConfigurationManager.AppSettings["iMiSLoginBaseUri"],
                                 * ConfigurationManager.AppSettings["iMiSLogin"], ((VisitorModel)_vusr).UserName);*/

                                //this.CreateOrUpdate("hlsession", sfResponse.Result.ClientId);
                                //this.SiteAppRunner().SiteUser = FluentSiteUser<ISiteUser>.Init(sfResponse.Result).Cached(this.SessionId());
                                var _updateModel = sfResponse.Result;
                                var _cacheUser   = new GenericResultSerialized()
                                {
                                    User           = _updateModel.SerializeToString(),
                                    SessionId      = "123",//this.SessionId(),
                                    UserId         = _updateModel.UserId,
                                    Message        = "init from Auth",
                                    CreationDate   = DateTime.UtcNow,
                                    LastChangeDate = DateTime.UtcNow,
                                    // RWB 20170911 - Removed contactID ContactId = helixIndv.MembershipId,
                                    Data = helixIndv.ToJson <HelixIndividual>(),
                                };
                                //_updateModel.UpdateSessionId(this.SessionId());
                                //this.GetSetAppSiteUser(sfResponse.Result);
                                //this.SetAppSiteUser(_updateModel.UserId, _cacheUser);

#if DEBUG
                                log.Info("update user to cache:{0} by id:".Fmt(new
                                {
                                    cache    = _cacheUser,
                                    sessonid = "123",    //this.SessionId(),
                                    data     = _updateModel
                                }.SerializeToString()));
#endif
                            }
                            else
                            {
                                log.Warn("issue with auth with SF:{0}".Fmt(sfResponse.Message));
                            }
                            authUser = _vusr;
                            return(_vusr);
                        });
                    }
                    return(cl);
                });
            }

            // to show as a button then this need to be checked
            if (ShowLoginForm)
            {
                return(View("Index"));
            }
            // or last step is to redirect back

            if (!SystemManager.IsDesignMode || !SystemManager.IsPreviewMode)
            {
                //return Redirect(authUser.ReturnUrl.DefaultIfNullEmpty("/"));
                if (this.MyId().IsNullOrEmptyGuid())
                {
                    log.InfoFormat("auth-noCode:{0}", HttpContext.Request?.Url?.AbsolutePath);
                    return(Redirect("/"));
                }
                return(Redirect(returnUrl.DefaultIfNullEmpty("/")));
                //return Redirect("http://members.iafc.org/helix/MembershipSignIn/ktomko/true");
            }

            return(View("Index"));
        }