Example #1
0
        public GetItemResponse<SessionObject> GetSessionObject(SessionRequest request)
        {
            var response = new GetItemResponse<SessionObject>();
            LogonLog logonLog = new LogonLog();
            logonLog.ID = SequentialGuid.NewDbGuid();
            logonLog.ApplicationID = request.ApplicationID;
            logonLog.HostIPAddress = request.HostIPAddress;
            logonLog.FailureCode = AuthenticationResult.Undefined;
            logonLog.LoginUsername = request.Username.Truncate(50);
            try
            {
                SessionObject sessionObj = null;

                //look for session in cache, if exists return it.
                sessionObj = SessionObjectCache.Instance.GetSession(request.SessionID);
                if (sessionObj != null)
                {
                    //we must clone otherwise wcf may mess up the channel
                    return new GetItemResponse<SessionObject>(sessionObj.Clone());
                }

                if (sessionObj == null)
                {
                    if (request.SessionID != Guid.Empty)
                    {
                        _Log.InfoFormat("Session {0} not in cache", request.SessionID);
                        //log the session expiry - this must be a seperate log with a sepereate id  see IM-4806
                        LogonLog expiryLog = new LogonLog();
                        expiryLog.ID = SequentialGuid.NewDbGuid();
                        expiryLog.ApplicationID = request.ApplicationID;
                        expiryLog.HostIPAddress = request.HostIPAddress;
                        expiryLog.FailureCode = AuthenticationResult.Undefined;
                        expiryLog.LoginUsername = request.Username.Truncate(50);
                        expiryLog.Logon = LogonType.SessionExpired;
                        expiryLog.SessionObjectID = request.SessionID;
                        expiryLog.SecurityEntityID = request.SecurityEntityID;
                        //companyid and userid are unknown
                        SaveLogonLog(new SaveRequest<LogonLog>(expiryLog));
                    }
                    SecurityEntity entity;
                    bool impersonation = false;
                    if (request.SecurityEntityID != Guid.Empty)
                    {
                        var seResponse = GetSecurityEntity(new IDRequest(request.SecurityEntityID));
                        ErrorHandler.Check(seResponse);
                        entity = seResponse.Item;
                        impersonation = true;
                        logonLog.Logon = LogonType.Impersonation;
                        if (entity != null)
                        {
                            logonLog.FailureCode = AuthenticationResult.Success;
                            logonLog.LoginUsername = entity.LoginUsername;
                        }
                        else
                        {
                            logonLog.FailureCode = AuthenticationResult.Undefined;
                            logonLog.LoginUsername = "******";
                        }
                    }
                    else
                    {
                        logonLog.FailureCode = Authenticate(request.Username, request.Password, request.Mode, request.EntityType, out entity);
                        logonLog.Logon = LogonType.UserLogon;
                    }
                    string msg = string.Format("SecurityEntity: {0} for `{1}` -> {2}/{3}", entity, request.Username, logonLog.Logon, logonLog.FailureCode);
                    _Log.Info(msg);
                    response.StatusMessage = msg;

                    if (entity == null)
                    {
                        response.Status = false;
                        logonLog.FailureCode = AuthenticationResult.SecurityEntityNotFound;
                        logonLog.Success = false;
                        logonLog.SessionObjectID = Guid.Empty;
                        logonLog.SecurityEntityID = Guid.Empty;
                    }
                    else
                    {
                        logonLog.CompanyID = entity.CompanyID;
                        logonLog.SecurityEntityID = entity.ID;
                        logonLog.UserID = entity.UserID;

                        if (logonLog.FailureCode == AuthenticationResult.Success)
                        {
                            var permissionList = GetSecurityPermissionList(request.ApplicationID, entity)
                                    .ConvertAll<Guid>(permission => permission.SecurityObjectID);

                            // Check if this it is the Imarda Admin Console trying to log in thru the provioning service
                            // in that case Flags == 2, and the IAC login security object must be linked to the security entity of the user
                            if (request.Mode == LoginMode.IAC && !permissionList.Contains(AuthToken.ImardaAdminServiceLogin))
                            {
                                msg = string.Format("IAC login {0} failed, IAC permission for {1} not found", request.Username, entity);
                                _Log.Info(msg);
                                response.Status = false;
                                response.StatusMessage = msg;
                                logonLog.FailureCode = AuthenticationResult.IACPermissionNotFound;
                                logonLog.Success = false;
                                logonLog.SessionObjectID = Guid.Empty;
                                SaveLogonLog(new SaveRequest<LogonLog>(logonLog));
                                return response;
                            }

                            sessionObj = new SessionObject
                            {
                                ApplicationID = request.ApplicationID,
                                SessionID = Guid.NewGuid(),
                                CRMID = entity.CRMId,
                                SecurityEntityID = entity.ID,
                                CompanyID = entity.CompanyID,
                                Username = entity.LoginUsername,
                                Password = entity.LoginPassword,
                                PermissionsList = permissionList,
                                Impersonation = impersonation,
                                TimeZoneKey = entity.TimeZone,
                                EntityName = entity.EntityName,
                                EntityType = entity.EntityType,
                                EnableTimeZoneSelect = entity.EnableTimeZoneSelect,
                            };
                            logonLog.Success = true;
                            logonLog.SessionObjectID = sessionObj.SessionID;
                            SessionObjectCache.Instance.StoreSession(sessionObj);
                            _Log.InfoFormat("Store new session: {0}", sessionObj);
                        }
                    }
                    SaveLogonLog(new SaveRequest<LogonLog>(logonLog));
                }
                return new GetItemResponse<SessionObject>(sessionObj) {ErrorCode = logonLog.FailureCode.ToString()}; // StatusMessage = response.StatusMessage};
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle<GetItemResponse<SessionObject>>(ex);
            }
        }
 public BusinessMessageResponse SetAcessTokenOnSession(SessionRequest request)
 {
     try
     {
         ImardaSecurityBusiness.IImardaSecurity service = ImardaProxyManager.Instance.IImardaSecurityProxy;
         ChannelInvoker.Invoke(delegate(out IClientChannel channel)
         {
             channel = service as IClientChannel;
             //response = service.SetDeletedSecurityEntityByCRMID(request);
         });
         return null; // response;
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle(ex);
     }
 }
 public BusinessMessageResponse Logout(SessionRequest request)
 {
     try
     {
         var session = SessionObjectCache.Instance.GetSession(request.SessionID);
         if (session == null)
         {
             return new BusinessMessageResponse();
         }
         var resp = new BusinessMessageResponse();
         var service2 = ImardaProxyManager.Instance.IImardaConfigurationProxy;
         ChannelInvoker.Invoke(delegate(out IClientChannel channel2)
                                                     {
                                                         channel2 = service2 as IClientChannel;
                                                         var request2 = new ConfigListRequest(null, session.CompanyID, session.CRMID);
                                                         resp = service2.RemoveFromCache(request2);
                                                     });
         SessionObjectCache.Instance.DeleteSession(request.SessionID);
         //save logonlog
         if (resp.Status)
         {
             var service3 = ImardaProxyManager.Instance.IImardaSecurityProxy;
             ChannelInvoker.Invoke(delegate(out IClientChannel channel3)
             {
                 channel3 = service3 as IClientChannel;
                 LogonLog logonLog = new LogonLog();
                 logonLog.ID = SequentialGuid.NewDbGuid();
                 logonLog.ApplicationID = request.ApplicationID;
                 logonLog.HostIPAddress = request.HostIPAddress;
                 logonLog.CompanyID = session.CompanyID;
                 logonLog.SecurityEntityID = session.SecurityEntityID;
                 logonLog.SessionObjectID = session.SessionID;
                 logonLog.LoginUsername = session.Username;
                 logonLog.UserID = session.CRMID;
                 logonLog.Logon = (request.Username == null) ? LogonType.UserLogoff : LogonType.AutoLogoff;
                 var request3 = new SaveRequest<LogonLog>(logonLog);
                 resp = service3.SaveLogonLog(request3);
             });
         }
         return resp;
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle(ex);
     }
 }
        public GetItemResponse<ConfiguredSessionObject> Login(SessionRequest request)
        {
            try
            {
                SessionObject session;
                if (request.Username != null)
                {
                    if (request.SessionID != Guid.Empty)
                    {
                        Logout(request);
                        request.SessionID = Guid.Empty;
                    }
                    // this clears old session id if user name is used to log in otherwise we are logging in with somebody else's old session id!!
                    session = null;
                }
                else
                {
                    session = SessionObjectCache.Instance.GetSession(request.SessionID);
                }

                if (session == null)
                {
                    GetItemResponse<SessionObject> resp1 = null;
                    var service0 = ImardaProxyManager.Instance.IImardaSecurityProxy;
                    ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                    {
                        channel = service0 as IClientChannel;
                        resp1 = service0.GetSessionObject(request);
                        if (request.Mode == LoginMode.Normal) ErrorHandler.Check(resp1);
                        session = resp1.Item;
                    });
                    if (session == null)
                    {
                        var statusMessage = "Authentication failed";
                        if (resp1 != null)
                        {
                            if (resp1.ErrorCode == "-1")
                                statusMessage = "Invalid user";
                            if (resp1.ErrorCode == "0")
                                statusMessage = "Success";
                            else if (resp1.ErrorCode == "1")
                                statusMessage = "Invalid username";
                            else if (resp1.ErrorCode == "2")
                                statusMessage = "User has no login permission";
                            if (resp1.ErrorCode == "3")
                                statusMessage = "Login is disabled";
                            else if (resp1.ErrorCode == "4")
                                statusMessage = "Invalid password";
                        }
                        return new GetItemResponse<ConfiguredSessionObject> { Status = false, StatusMessage = statusMessage, ErrorCode = resp1.ErrorCode };
                    }
                }
                else
                {
                    var service1 = ImardaProxyManager.Instance.IImardaSecurityProxy;
                    ChannelInvoker.Invoke(delegate(out IClientChannel channel3)
                    {
                        channel3 = service1 as IClientChannel;
                        var resp3 = service1.GetSecurityEntity(new IDRequest(session.SecurityEntityID));
                        SecurityEntity se = resp3.Item;
                        session.TimeZoneKey = se.TimeZone;
                    });
                }

                var config = new SessionConfigGroup();

                var service2 = ImardaProxyManager.Instance.IImardaConfigurationProxy;
                ConfiguredSessionObject cfgSession = null;
                ChannelInvoker.Invoke(delegate(out IClientChannel channel2)
                {
                    channel2 = service2 as IClientChannel;
                    Guid[] ids = ConfigGroup.GetIDs(config);
                    var request2 = new ConfigListRequest(ids, session.CompanyID, session.CRMID);
                    service2.RemoveFromCache(request2);
                    var resp2b = service2.GetConfigValueList(request2);
                    if (request.Mode == LoginMode.Normal) ErrorHandler.Check(resp2b);
                    ConfigValue[] values = resp2b.List.ToArray();
                    ConfigGroup.SetValues(config, values);

                    cfgSession = new ConfiguredSessionObject(session, config, request.Mode);
                    config.PreferredMeasurementUnits = CultureHelper.CalcPreferences(config, service2);

                    var cacheSession = cfgSession.StripConfig(request.Mode);
                    SessionObjectCache.Instance.StoreSession(cacheSession);
                });

                var sb = new StringBuilder();
                sb.AppendKV("User", cfgSession.Username)
                    .AppendKV("AppID", cfgSession.ApplicationID.ToString().ToUpperInvariant())
                    .AppendKV("Locale", cfgSession.PreferredCulture) // used in formatter for notification templates!
                    .AppendKV("Region", cfgSession.Configuration.Region)
                    .AppendKV("Impers", cfgSession.Impersonation)
                    .AppendKV("EvTime", DateTime.UtcNow, "~");
                var logonEventID = new Guid("4c2f21cb-fcdd-4d6b-a6bd-a928680bee05");

                AlertTaskHelper.SaveAlertTask(
                    cfgSession.CompanyID,
                    logonEventID,
                    cfgSession.CRMID,
                    cfgSession.CRMID,
                    cfgSession.Username,
                    Guid.Empty,
                    sb,
                    TimeZoneInfo.FindSystemTimeZoneById(cfgSession.TimeZoneKey),
                    Guid.Empty);

                cfgSession.Password = null; // clear password hash before returning
                return new GetItemResponse<ConfiguredSessionObject>
                {
                    Item = cfgSession,
                    Status = true
                };
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle<GetItemResponse<ConfiguredSessionObject>>(ex);
            }
        }
 public BusinessMessageResponse IsAuthenticated(SessionRequest request)
 {
     throw new NotImplementedException(); // does not need to be implemented, only required by IImardaSecurity
 }
 public GetItemResponse<ConfiguredSessionObject> GetSessionByID(SessionRequest request)
 {
     throw new NotImplementedException(); // does not need to be implemented, only required by IImardaSecurity
 }