Esempio n. 1
0
        private questStatus read(FMSEntities dbContext, UserSessionId userSessionId, out Quest.Services.Dbio.FMS.UserSessions userSession)
        {
            // Initialize
            userSession = null;


            try
            {
                userSession = dbContext.UserSessions.Where(r => r.Id == userSessionId.Id).SingleOrDefault();
                if (userSession == null)
                {
                    return(new questStatus(Severity.Error, String.Format("ERROR: {0}.{1}: {2}",
                                                                         this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                         String.Format("Id {0} not found", userSessionId.Id))));
                }
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);

                String fullErrorMessage = string.Join("; ", errorMessages);
                String exceptionMessage = string.Concat(ex.Message, " The DbEntityValidationException errors are: ", fullErrorMessage);
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     exceptionMessage)));
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     ex.InnerException != null ? ex.InnerException.Message : ex.Message)));
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 2
0
        // Describe User / Session

        public async Task <SessionDetails> GetSessionDetailsAsync(ClaimsPrincipal principal)
        {
            var sessionId = GetSessionId(principal);

            if (sessionId == null)
            {
                return(null);
            }

            var session = await _persistence.UserSessions.GetAsync(UserSessionId.FromString(sessionId));

            var user = await _persistence.Users.GetAsync(session.UserId);

            return(new SessionDetails()
            {
                Id = session.Id,
                CreationTime = session.CreationTime,
                LogoutTime = session.LogoutTime,
                User = new UserDetails()
                {
                    Id = user.Id,
                    Username = user.Username,
                    EmailAddress = user.EmailAddress
                }
            });
        }
Esempio n. 3
0
        public questStatus Logout(UserSessionId userSessionId)
        {
            // Initialize
            questStatus status      = null;
            UserSession userSession = null;

            // Get the user session.
            UserSessionMgr userSessionMgr = new UserSessionMgr(this.UserSession);

            status = userSessionMgr.Read(userSessionId, out userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Set termination date to now.
            userSession.Terminated = DateTime.Now;


            // Update the user session.
            status = userSessionMgr.Update(userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 4
0
 public UserSessionDTO(UserSessionId id, UserId userid, DateTime creationtime, DateTime?logouttime)
 {
     Id           = id;
     UserId       = userid;
     CreationTime = creationtime;
     LogoutTime   = logouttime;
 }
        public ActionResult Login(LoginRequestViewModel loginRequestViewModel)
        {
            // Initialize
            questStatus            status = null;
            LoginResponseViewModel loginResponseViewModel = null;


            /*----------------------------------------------------------------------------------------------------------------------------------
            * Log Operation
            *---------------------------------------------------------------------------------------------------------------------------------*/
            status = LogOperation();
            if (!questStatusDef.IsSuccess(status))
            {
                loginResponseViewModel = new LoginResponseViewModel();
                loginResponseViewModel.UserMessages[0] = new UserMessageModeler(status).UserMessage;
                status.Message = null;
                loginResponseViewModel.questStatus = status;
                TempData["LoginResponseViewModel"] = loginResponseViewModel;
                return(RedirectToAction("Index"));
            }

            /*----------------------------------------------------------------------------------------------------------------------------------
            * Authorize
            *---------------------------------------------------------------------------------------------------------------------------------*/
            status = Authorize();
            if (!questStatusDef.IsSuccess(status))
            {
                loginResponseViewModel = new LoginResponseViewModel();
                loginResponseViewModel.UserMessages[0] = new UserMessageModeler(status).UserMessage;
                status.Message = null;
                loginResponseViewModel.questStatus = status;
                TempData["LoginResponseViewModel"] = loginResponseViewModel;
                return(RedirectToAction("Index"));
            }

            /*----------------------------------------------------------------------------------------------------------------------------------
            * Login
            *---------------------------------------------------------------------------------------------------------------------------------*/
            UserSessionId  userSessionId  = null;
            AccountModeler accountModeler = new AccountModeler(this.Request, this.UserSession);

            status = accountModeler.Login(Request, loginRequestViewModel, out userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                loginResponseViewModel = new LoginResponseViewModel();
                ////loginResponseViewModel.UserMessages.Add(new UserMessageModeler(new questStatus(Severity.Error, "Invalid username or password")).UserMessage);
                loginResponseViewModel.UserMessages.Add(new UserMessageModeler(new questStatus(status.Severity, status.Message)).UserMessage);
                status.Message = null;
                loginResponseViewModel.questStatus = status;
                TempData["LoginResponseViewModel"] = loginResponseViewModel;
                return(RedirectToAction("Index"));
            }

            /*----------------------------------------------------------------------------------------------------------------------------------
            * Direct user to home page.
            *---------------------------------------------------------------------------------------------------------------------------------*/
            return(RedirectToAction("Index", "Home", new { _ctx = userSessionId.Id }));
        }
Esempio n. 6
0
        // Logout

        public async Task LogoutAsync()
        {
            await _context.HttpContext.SignOutAsync();

            var sessionId = GetSessionId(_context.HttpContext.User);

            if (sessionId != null)
            {
                await _persistence.UserSessions.LogoutAsync(UserSessionId.FromString(sessionId), DateTime.UtcNow);
            }
        }
Esempio n. 7
0
        public questStatus ValidateUserSession(UserSessionId userSessionId, out UserSession userSession)
        {
            // Initialize
            questStatus status = null;

            UserSessionMgr userSessionMgr = new UserSessionMgr(this.UserSession);

            status = userSessionMgr.Read(userSessionId, out userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(new questStatus(status.Severity, "Invalid user session"));
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 8
0
        public questStatus Authorize(int ctx)
        {
            questStatus   status        = null;
            UserSessionId userSessionId = new UserSessionId(ctx);
            UserSession   userSession   = null;

            status = ValidateUserSession(userSessionId, out userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            this._userSession = userSession;
            return(new questStatus(Severity.Success));
        }
Esempio n. 9
0
        public questStatus Delete(UserSessionId userSessionId)
        {
            // Initialize
            questStatus status = null;


            // Delete userSession
            status = _dbUserSessionsMgr.Delete(userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
        public ActionResult Authenticate(LoginRequestViewModel loginRequestViewModel)
        {
            // Initialize
            questStatus        status             = null;
            UserMessageModeler userMessageModeler = null;


            /*----------------------------------------------------------------------------------------------------------------------------------
            * Log Operation
            *---------------------------------------------------------------------------------------------------------------------------------*/
            status = LogOperation();
            if (!questStatusDef.IsSuccess(status))
            {
                userMessageModeler = new UserMessageModeler(status);
                return(Json(userMessageModeler, JsonRequestBehavior.AllowGet));
            }

            /*----------------------------------------------------------------------------------------------------------------------------------
            * Authorize
            *---------------------------------------------------------------------------------------------------------------------------------*/
            status = Authorize();
            if (!questStatusDef.IsSuccess(status))
            {
                userMessageModeler = new UserMessageModeler(status);
                return(Json(userMessageModeler, JsonRequestBehavior.AllowGet));
            }

            /*----------------------------------------------------------------------------------------------------------------------------------
            * Login
            *---------------------------------------------------------------------------------------------------------------------------------*/
            UserSessionId  userSessionId  = null;
            AccountModeler accountModeler = new AccountModeler(this.Request, this.UserSession);

            status = accountModeler.Login(Request, loginRequestViewModel, out userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                userMessageModeler = new UserMessageModeler(status);
                return(Json(userMessageModeler, JsonRequestBehavior.AllowGet));
            }

            /*----------------------------------------------------------------------------------------------------------------------------------
            * Return result.
            *---------------------------------------------------------------------------------------------------------------------------------*/
            BaseUserSessionViewModel baseUserSessionViewModel = new BaseUserSessionViewModel();

            baseUserSessionViewModel._ctx        = userSessionId.Id;
            baseUserSessionViewModel.questStatus = new questStatus(Severity.Success, "Successfully authenticated");
            return(Json(baseUserSessionViewModel, JsonRequestBehavior.AllowGet));
        }
Esempio n. 11
0
        /*==================================================================================================================================
        * Properties
        *=================================================================================================================================*/
        #endregion


        #region Public Methods

        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus Create(UserSession userSession, out UserSessionId userSessionId)
        {
            // Initialize
            userSessionId = null;
            questStatus status = null;


            // Create userSession
            status = _dbUserSessionsMgr.Create(userSession, out userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 12
0
        public questStatus Delete(DbMgrTransaction trans, UserSessionId userSessionId)
        {
            // Initialize
            questStatus status = null;


            // Perform delete in this transaction.
            status = delete((FMSEntities)trans.DbContext, userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                RollbackTransaction(trans);
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
        public questStatus Logout(LogoutRequestViewModel logoutRequestViewModel)
        {
            // Initialize
            questStatus status = null;


            // Perform logout
            UserSessionId userSessionId = new UserSessionId(logoutRequestViewModel.ctx);
            AccountMgr    accountMgr    = new AccountMgr(this.UserSession);

            status = accountMgr.Logout(userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 14
0
        public questStatus Delete(UserSessionId userSessionId)
        {
            // Initialize
            questStatus status = null;


            // Perform delete.
            using (FMSEntities dbContext = new FMSEntities())
            {
                status = delete(dbContext, userSessionId);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 15
0
        public questStatus Create(DbMgrTransaction trans, UserSession userSession, out UserSessionId userSessionId)
        {
            // Initialize
            questStatus status = null;

            userSessionId = null;


            // Data rules.
            userSession.Created = DateTime.Now;


            // Create the user session in this transaction.
            status = create((FMSEntities)trans.DbContext, userSession, out userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 16
0
        public async Task LogoutAsync(UserSessionId id, DateTime utcNow)
        {
            var sqlParams = new
            {
                Id         = id.RawValue,
                LogoutTime = DateTime.UtcNow
            };

            string sql = @";
                UPDATE dbo.UserSessions
                SET LogoutTime = @LogoutTime
                WHERE Id = @Id
                    AND LogoutTime IS NULL;
            ";

            await _db.Execute(async (db) =>
            {
                await db.ExecuteAsync(sql, sqlParams);
            });
        }
Esempio n. 17
0
        public questStatus LoadUserSession(int ictx)
        {
            // Initialize
            questStatus status = null;


            // Get user session and assign as property to this class.
            UserSessionId userSessionId = new UserSessionId(ictx);
            UserSession   userSession   = null;

            status = ValidateUserSession(userSessionId, out userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            this._userSession = userSession;


            return(new questStatus(Severity.Success));
        }
Esempio n. 18
0
        // Validate Login

        public async Task <bool> ValidateLoginAsync(ClaimsPrincipal principal)
        {
            var sessionId = GetSessionId(principal);

            if (sessionId == null)
            {
                return(false);
            }

            var session = await _persistence.UserSessions.GetAsync(UserSessionId.FromString(sessionId));

            if (session.LogoutTime.HasValue)
            {
                return(false);
            }

            // add in options like updating it with a last seen time, expiration, etc
            // add in options like IP Address roaming check

            return(true);
        }
Esempio n. 19
0
        public async Task <UserSessionDTO> GetAsync(UserSessionId id)
        {
            var sqlParams = new
            {
                Id = id.RawValue
            };

            string sql = @"
                SELECT Id,
                       UserId,
                       CreationTime,
                       LogoutTime
                FROM dbo.UserSessions
                WHERE Id = @Id;
            ";

            return(await _db.QuerySingle(async (db) =>
            {
                return await db.FetchAsync <UserSessionDTO>(sql, sqlParams);
            }));
        }
Esempio n. 20
0
        private questStatus update(FMSEntities dbContext, UserSession userSession)
        {
            // Initialize
            questStatus status = null;


            try
            {
                // Read the record.
                UserSessionId userSessionId = new UserSessionId(userSession.Id);
                Quest.Services.Dbio.FMS.UserSessions _userSession = null;
                status = read(dbContext, userSessionId, out _userSession);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }

                // Update the record.
                BufferMgr.TransferBuffer(userSession, _userSession);
                dbContext.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);

                String fullErrorMessage = string.Join("; ", errorMessages);
                String exceptionMessage = string.Concat(ex.Message, " The DbEntityValidationException errors are: ", fullErrorMessage);
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     exceptionMessage)));
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     ex.InnerException != null ? ex.InnerException.Message : ex.Message)));
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 21
0
        public questStatus Read(DbMgrTransaction trans, UserSessionId userSessionId, out UserSession userSession)
        {
            // Initialize
            questStatus status = null;

            userSession = null;


            // Perform read.
            using (FMSEntities dbContext = new FMSEntities())
            {
                Quest.Services.Dbio.FMS.UserSessions _userSession = null;
                status = read((FMSEntities)trans.DbContext, userSessionId, out _userSession);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
                userSession = new UserSession();
                BufferMgr.TransferBuffer(_userSession, userSession);
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 22
0
        public questStatus Read(UserSessionId userSessionId, out UserSession userSession)
        {
            // Initialize
            userSession = null;
            questStatus status = null;


            // Read userSession
            status = _dbUserSessionsMgr.Read(userSessionId, out userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Get the user
            UserId   userId   = new UserId(userSession.UserId);
            User     user     = null;
            UsersMgr usersMgr = new UsersMgr(this.UserSession); // TODO: PLUG UP REAL USER SESSION

            status = usersMgr.Read(userId, out user);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            userSession.User = user;

            // Get user privileges.
            List <Privilege> privilegeList = null;
            DbAccountsMgr    dbAccountsMgr = new DbAccountsMgr(new UserSession()); // TODO: UNSTUB

            status = dbAccountsMgr.GetUserPrivileges(userId, out privilegeList);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            userSession.Privileges = privilegeList;

            return(new questStatus(Severity.Success));
        }
Esempio n. 23
0
        /*----------------------------------------------------------------------------------------------------------------------------------
        * UserSessions
        *---------------------------------------------------------------------------------------------------------------------------------*/
        private questStatus create(FMSEntities dbContext, UserSession userSession, out UserSessionId userSessionId)
        {
            // Initialize
            userSessionId = null;


            // Perform create
            try
            {
                Quest.Services.Dbio.FMS.UserSessions _userSession = new Quest.Services.Dbio.FMS.UserSessions();
                BufferMgr.TransferBuffer(userSession, _userSession);
                dbContext.UserSessions.Add(_userSession);
                dbContext.SaveChanges();
                if (_userSession.Id == 0)
                {
                    return(new questStatus(Severity.Error, "UserSession not created"));
                }
                userSessionId = new UserSessionId(_userSession.Id);
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);

                String fullErrorMessage = string.Join("; ", errorMessages);
                String exceptionMessage = string.Concat(ex.Message, " The DbEntityValidationException errors are: ", fullErrorMessage);
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     exceptionMessage)));
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     ex.InnerException != null ? ex.InnerException.Message : ex.Message)));
            }
            return(new questStatus(Severity.Success));
        }
        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus Login(HttpRequestBase request, LoginRequestViewModel loginRequestViewModel, out UserSessionId userSessionId)
        {
            // Initialize
            questStatus status = null;

            userSessionId = null;


            // Transfer model
            UserSession  userSession  = null;
            LoginRequest loginRequest = new LoginRequest();

            BufferMgr.TransferBuffer(loginRequestViewModel, loginRequest);
            string ipAddress = null;

            status = GetIPAddress(request, out ipAddress);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            loginRequest.IPAddress = ipAddress;
            loginRequest.UserAgent = request.UserAgent;


            // Perform login
            AccountMgr accountMgr = new AccountMgr(this.UserSession);

            status = accountMgr.Login(loginRequest, out userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Return user session Id
            userSessionId = new UserSessionId(userSession.Id);

            return(new questStatus(Severity.Success));
        }
Esempio n. 25
0
        /*==================================================================================================================================
        * Properties
        *=================================================================================================================================*/
        #endregion


        #region Public Methods

        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus Create(UserSession userSession, out UserSessionId userSessionId)
        {
            // Initialize
            questStatus status = null;

            userSessionId = null;


            // Data rules.
            userSession.Created = DateTime.Now;


            // Create the user session
            using (FMSEntities dbContext = new FMSEntities())
            {
                status = create(dbContext, userSession, out userSessionId);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
            }
            return(new questStatus(Severity.Success));
        }
Esempio n. 26
0
        /*==================================================================================================================================
        * Properties
        *=================================================================================================================================*/
        #endregion


        #region Public Methods

        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus Login(LoginRequest loginRequest, User user, out UserSession userSession)
        {
            // Initialize
            questStatus status = null;

            userSession = null;


            // User must be enabled and active.
            // (Intended to be data rule AND business rule).
            if (!user.bEnabled)
            {
                return(new questStatus(Severity.Error, "User is not enabled"));
            }
            if (!user.bActive)
            {
                return(new questStatus(Severity.Error, "User is not active"));
            }


            // Get user privileges
            UserId           userId            = new UserId(user.Id);
            List <Privilege> userPrivilegeList = null;

            status = GetUserPrivileges(userId, out userPrivilegeList);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Build user session
            UserSession _userSession = new UserSession();

            _userSession.IPAddress  = loginRequest.IPAddress;
            _userSession.UserAgent  = loginRequest.UserAgent;
            _userSession.LastAction = DateTime.Now;
            _userSession.UserId     = user.Id;
            _userSession.User       = user;
            _userSession.Privileges = userPrivilegeList;
            _userSession.Created    = DateTime.Now;


            // Write the user session
            UserSessionId     _userSessionId    = null;
            DbUserSessionsMgr dbUserSessionsMgr = new DbUserSessionsMgr(this.UserSession);

            status = dbUserSessionsMgr.Create(_userSession, out _userSessionId);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Return the user session
            UserSession __userSession = null;

            status = dbUserSessionsMgr.Read(_userSessionId, out __userSession);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            userSession            = __userSession;
            userSession.User       = user;
            userSession.Privileges = userPrivilegeList;

            return(new questStatus(Severity.Success));
        }
Esempio n. 27
0
 private void AddSessionIdClaim(ClaimsIdentity identity, UserSessionId sessionId)
 {
     identity.AddClaim(new Claim("sessionId", sessionId.RawValue.ToString()));
 }