Beispiel #1
0
        public LoginProcess GetMultiFactorProcess(string token)
        {
            var session = OpContext.OpenSession();
            var process = GetMutiFactorProcess(session, token, throwIfNotFound: false);

            return(process.ToModel());
        }
Beispiel #2
0
        public LoginResponse CompleteMultiFactorLogin([FromBody] MultifactorLoginRequest request)
        {
            var session = OpContext.OpenSession();
            var process = GetMutiFactorProcess(session, request.ProcessToken);

            OpContext.ThrowIfNull(process, ClientFaultCodes.ObjectNotFound, "processToken", "Login process not found or expired.");
            OpContext.ThrowIf(process.PendingFactors != ExtraFactorTypes.None, ClientFaultCodes.InvalidValue, "PendingFactors",
                              "Multi-factor login process not completed, verification pending: {0}.", process.PendingFactors);
            var login = process.Login;

            var loginService = OpContext.App.GetService <ILoginService>();
            var loginResult  = loginService.CompleteMultiFactorLogin(OpContext, login);
            var displayName  = OpContext.App.GetUserDispalyName(OpContext.User);

            session.SaveChanges();
            return(new LoginResponse()
            {
                Status = LoginAttemptStatus.Success, SessionId = loginResult.SessionId,
                UserName = login.UserName, UserDisplayName = displayName,
                UserId = login.UserId, AltUserId = login.AltUserId, LoginId = login.Id,
                PasswordExpiresDays = login.GetExpiresDays(), Actions = loginResult.Actions,
                LastLoggedInOn = loginResult.PreviousLoginOn,
                AuthenticationToken = CreateAuthToken()
            });
        }//method
        public List <SecretQuestion> GetStandardSecretQuestions()
        {
            var session   = OpContext.OpenSession(); //opening system session, no need for authorization
            var questions = LoginManager.GetAllSecretQuestions(session);

            return(questions.Select(q => q.ToModel()).ToList());
        }
        public string TestConnectionHandling()
        {
            // connection mode should be set in WebCallContextHandlerSettings, and it is reuse by default
            if (OpContext.DbConnectionMode != DbConnectionReuseMode.KeepOpen)
            {
                return("Error: Connection mode is not KeepOpen. Mode: " + OpContext.DbConnectionMode);
            }
            _connectionCloseReport = "(empty)";
            var session = OpContext.OpenSession();
            var bk      = session.EntitySet <IBook>().OrderBy(b => b.Title).First();
            //this should creaet connection and attach to session
            var entSession = (Vita.Entities.Runtime.EntitySession)session;
            var currConn   = entSession.CurrentConnection;

            if (currConn == null)
            {
                return("Connection was not attached to entity session.");
            }
            var sqlConn = (SqlConnection)currConn.DbConnection;

            if (sqlConn.State != ConnectionState.Open)
            {
                return("Connection was not kept open.");
            }
            sqlConn.StateChange += Conn_StateChange;
            return("OK");
        }
    public OpContext op()
    {
        OpContext _localctx = new OpContext(Context, State);

        EnterRule(_localctx, 4, RULE_op);
        int _la;

        try {
            EnterOuterAlt(_localctx, 1);
            {
                State = 29;
                _la   = TokenStream.LA(1);
                if (!(_la == OR || _la == AND))
                {
                    ErrorHandler.RecoverInline(this);
                }
                else
                {
                    ErrorHandler.ReportMatch(this);
                    Consume();
                }
            }
        }
        catch (RecognitionException re) {
            _localctx.exception = re;
            ErrorHandler.ReportError(this, re);
            ErrorHandler.Recover(this, re);
        }
        finally {
            ExitRule();
        }
        return(_localctx);
    }
        private ILogin GetCurrentLogin(IEntitySession session)
        {
            var login = LoginManager.GetLogin(session);

            OpContext.ThrowIfNull(login, ClientFaultCodes.ObjectNotFound, "Login", "Login not found for user: {0}.", OpContext.User.UserName);
            return(login);
        }
Beispiel #7
0
        public User SignupUser([FromBody] UserSignup signup)
        {
            // signup request contains password, so mark it confidential, so the request body will NOT be logged
            //  to prevent passwords appearing in logs
            this.WebContext.Flags |= WebCallFlags.Confidential;

            //Validate
            OpContext.ThrowIfNull(signup, ClientFaultCodes.InvalidValue, "UserSignup", "UserSignup object may not be null.");
            OpContext.ValidateNotEmpty(signup.UserName, "UserName", "UserName may not be empty.");
            OpContext.ValidateNotEmpty(signup.Password, "Password", "Password may not be empty.");
            OpContext.ThrowValidation();
            var session = OpenSession();
            // check if user name is already taken
            var existingUser = session.EntitySet <IUser>().Where(u => u.UserName == signup.UserName).WithOptions(QueryOptions.ForceIgnoreCase).FirstOrDefault();

            OpContext.ThrowIf(existingUser != null, ClientFaultCodes.InvalidValue, "UserName", "User name {0} is already in use. Please choose other name.", signup.UserName);
            // create login and user
            var loginMgr = OpContext.App.GetService <ILoginManagementService>();
            var user     = session.NewUser(signup.UserName, UserType.Customer, signup.UserName);
            var login    = loginMgr.NewLogin(session, signup.UserName, signup.Password, loginId: user.Id, userId: user.Id); //Login.Id is the same as userID

            session.SaveChanges();
            // Let's create custom app event; we test here that this appEvent gets to AppEventLog
            //  log entries in web app are accumulated in buffered log attached to web call, and later
            // dumped to WebCallLog.OperationLog column as text. Except - errors and app events, they are
            // passed to global log as well.
            OpContext.WriteAppEvent("Customer", "Signup", $"Customer {signup.UserName} signed up.");
            return(user.ToModel());
        }
Beispiel #8
0
        public async Task SendPin([FromBody] SendPinRequest request)
        {
            OpContext.WebContext.MarkConfidential();
            OpContext.ThrowIfNull(request, ClientFaultCodes.ContentMissing, "SendPinRequest", "Pin request object must be provided.");
            OpContext.ValidateNotEmpty(request.ProcessToken, "ProcessToken", "Process token should be provided.");
            OpContext.ValidateNotEmpty(request.Factor, "Factor", "Factor (email or phone) should be provided.");
            OpContext.ThrowValidation();
            var session = OpContext.OpenSession();
            var process = GetActiveProcess(session, request.ProcessToken, confirmedOnly: false);

            if (process == null)
            {
                return; //no indication process exist or not
            }
            OpContext.ThrowIf(process.CurrentFactor != null, ClientFaultCodes.InvalidAction, "token", "The previous process step is not completed.");
            var iFactor = ProcessService.FindLoginExtraFactor(process.Login, request.Factor);

            //now having completed at least one extra factor, we can openly indicate that we could not find next factor
            OpContext.ThrowIfNull(iFactor, ClientFaultCodes.InvalidValue, "factor", "Login factor (email or phone) is not found for a user.");
            //Check that factor type is one in the pending steps
            var factorOk = process.PendingFactors.IsSet(iFactor.FactorType);

            OpContext.ThrowIf(!factorOk, ClientFaultCodes.InvalidValue, "factor", "Login factor type attempted (email or phone) is not pending in the process.");
            await ProcessService.SendPinAsync(process, iFactor, request.Factor); //we use factor from request, to avoid unencrypting twice
        }
        public bool SubmitPin(Guid factorId, string pin)
        {
            OpContext.ThrowIfEmpty(pin, ClientFaultCodes.ValueMissing, "pin", "Pin value missing");
            var session = OpenSession();
            var login   = GetCurrentLogin(session);
            var factor  = login.ExtraFactors.FirstOrDefault(f => f.Id == factorId);

            OpContext.ThrowIfNull(factor, ClientFaultCodes.ObjectNotFound, "factor", "Factor not found, ID: {0}", factorId);
            var processService = OpContext.App.GetService <ILoginProcessService>();
            var processes      = processService.GetActiveConfirmationProcesses(factor, LoginProcessType.FactorVerification);

            OpContext.ThrowIf(processes.Count == 0, ClientFaultCodes.ObjectNotFound, "LoginProcess", "Confirmation process not found or expired.");
            try {
                foreach (var process in processes)
                {
                    if (processService.SubmitPin(process, pin))
                    {
                        return(true);
                    }
                }
                return(false);
            } finally {
                session.SaveChanges();
            }
        }
        public BookOrder UpdateOrder(BookOrder order)
        {
            var session = OpenSession();
            var cart    = GetOpenOrder(session, LockType.ForUpdate, create: true);

            foreach (var item in order.Items)
            {
                OpContext.ThrowIf(item.Quantity < 0, ClientFaultCodes.InvalidValue, "Quantity", "Quantity may not be negative.");
                OpContext.ThrowIf(item.Quantity > 10, ClientFaultCodes.InvalidValue, "Quantity", "Quantity may not be more than 10.");
                var orderLine = cart.Lines.FirstOrDefault(ln => ln.Book.Id == item.Book.Id);
                if (orderLine == null)
                {
                    if (item.Quantity > 0)
                    {
                        var bk = session.GetEntity <IBook>(item.Book.Id);
                        OpContext.ThrowIfNull(bk, ClientFaultCodes.ObjectNotFound, "Book", "Book not found.");
                        cart.Add(bk, item.Quantity);
                        continue;
                    }
                }
                else //orderLine != null
                if (item.Quantity == 0)
                {
                    session.DeleteEntity(orderLine);
                }
                else
                {
                    orderLine.Quantity = item.Quantity;
                }
            }
            cart.ScheduleUpdateTotal();
            session.SaveChanges();
            EntityHelper.RefreshEntity(cart); //to make sure total from database is refreshed in entity
            return(cart.ToModel(details: true));
        }
Beispiel #11
0
    public OpContext op()
    {
        OpContext _localctx = new OpContext(Context, State);

        EnterRule(_localctx, 18, RULE_op);
        int _la;

        try {
            EnterOuterAlt(_localctx, 1);
            {
                State = 80;
                _la   = TokenStream.LA(1);
                if (!((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << PLUS) | (1L << ASSIGN) | (1L << MINUS))) != 0)))
                {
                    ErrorHandler.RecoverInline(this);
                }
                else
                {
                    ErrorHandler.ReportMatch(this);
                    Consume();
                }
            }
        }
        catch (RecognitionException re) {
            _localctx.exception = re;
            ErrorHandler.ReportError(this, re);
            ErrorHandler.Recover(this, re);
        }
        finally {
            ExitRule();
        }
        return(_localctx);
    }
        public void UpdateStatus(Guid loginId, [FromQuery] LoginStatusUpdate update)
        {
            var session = OpContext.OpenSession();
            var login   = _adminService.GetLogin(session, loginId);

            OpContext.ThrowIfNull(login, ClientFaultCodes.ObjectNotFound, "Login", "Login not found.");
            _adminService.UpdateStatus(login, update.Disable, update.Suspend);
        }
Beispiel #13
0
        public IList <SecretQuestion> GetUserSecretQuestions(string token)
        {
            var session        = OpContext.OpenSession();
            var process        = GetMutiFactorProcess(session, token);
            var processService = OpContext.App.GetService <ILoginProcessService>();
            var qs             = processService.GetUserSecretQuestions(process.Login);

            return(qs.Select(q => q.ToModel()).ToList());
        }
Beispiel #14
0
        public PasswordStrength EvaluatePasswordStrength([FromBody] PasswordChangeInfo changeInfo)
        {
            OpContext.WebContext.MarkConfidential(); //prevent from logging password
            OpContext.ThrowIfNull(changeInfo, ClientFaultCodes.ContentMissing, "Password", "Password infomation missing.");
            var loginMgr = OpContext.App.GetService <ILoginManagementService>();
            var strength = loginMgr.EvaluatePasswordStrength(changeInfo.NewPassword);

            return(strength);
        }
        public void ChangePassword([FromBody] PasswordChangeInfo changeInfo)
        {
            OpContext.WebContext.MarkConfidential();
            OpContext.ThrowIfNull(changeInfo, ClientFaultCodes.ContentMissing, "Password", "Password change info is missing.");
            var session = OpenSession();
            var login   = GetCurrentLogin(session);

            LoginManager.ChangePassword(login, changeInfo.OldPassword, changeInfo.NewPassword);
            session.SaveChanges();
        }
        public BookOrder SubmitOrder(string coupon = null)
        {
            var session = OpenSession();
            var cart    = GetOpenOrder(session, LockType.ForUpdate);

            OpContext.ThrowIfNull(cart, ClientFaultCodes.InvalidAction, "Cart", "Cart is empty, cannot submit order.");
            cart.CompleteOrder(coupon);
            session.SaveChanges();
            return(cart.ToModel(details: true));
        }
        public void DeleteReview(Guid id)
        {
            var session = OpenSession();
            var review  = session.GetEntity <IBookReview>(id);

            OpContext.ThrowIfNull(review, ClientFaultCodes.ObjectNotFound,
                                  "ReviewId", "Review with ID '{0}' not found.", id);
            session.DeleteEntity(review);
            session.SaveChanges();
        }
Beispiel #18
0
        public void AbortProcess(string token)
        {
            var session = OpContext.OpenSession();
            var process = GetActiveProcess(session, token, confirmedOnly: false);

            if (process != null)
            {
                ProcessService.AbortPasswordReset(process);
            }
        }
Beispiel #19
0
        public bool SubmitQuestionAnswers(string token, [FromBody] SecretQuestionAnswer[] answers)
        {
            OpContext.WebContext.MarkConfidential();
            var session        = OpContext.OpenSession();
            var process        = GetMutiFactorProcess(session, token);
            var processService = OpContext.App.GetService <ILoginProcessService>();
            var result         = processService.CheckAllSecretQuestionAnswers(process, answers);

            return(result);
        }
Beispiel #20
0
        public void VerifyPin([FromBody] VerifyPinRequest request)
        {
            var session = OpContext.OpenSession();
            var process = GetActiveProcess(session, request.ProcessToken, confirmedOnly: false);

            OpContext.ThrowIfEmpty(request.Pin, ClientFaultCodes.ValueMissing, "pin", "Pin value missing");
            if (process != null)
            {
                ProcessService.SubmitPin(process, request.Pin);
            }
        }
        public LoginInfo UpdateLoginInfo([FromBody] LoginInfo loginInfo)
        {
            var session = OpenSession();
            var login   = GetCurrentLogin(session);

            OpContext.ThrowIfNull(login, ClientFaultCodes.ContentMissing, "LoginInfo", "LoginInfo is missing.");
            OpContext.ThrowIf(loginInfo.Id != login.Id, ClientFaultCodes.InvalidValue, "Id", "Invalid login Id, must match current user's login id.");
            LoginManager.UpdateLogin(login, loginInfo);
            session.SaveChanges();
            return(login.ToModel());
        }
        public LoginInfo GetLogin(Guid id)
        {
            var session = OpContext.OpenSession();
            var login   = session.GetEntity <ILogin>(id);

            if (login == null)
            {
                return(null);
            }
            return(login.ToModel());
        }
        public void DeleteFactor(Guid id)
        {
            var session = OpenSession();
            var login   = GetCurrentLogin(session);
            var factor  = login.ExtraFactors.FirstOrDefault(f => f.Id == id);

            OpContext.ThrowIfNull(factor, ClientFaultCodes.ObjectNotFound, "factor", "Factor not found, ID: {0}", id);
            session.DeleteEntity(factor);
            session.SaveChanges();
            LoginManager.CheckLoginFactorsSetupCompleted(login);
        }
Beispiel #24
0
        public LoginProcess GetProcess(string token)
        {
            var session = OpContext.OpenSession();
            var process = GetActiveProcess(session, token);

            if (process == null)
            {
                return(null);
            }
            return(process.ToModel());
        }
        public BookOrder CancelOrder()
        {
            //we use this args object to allow optional coupon parameter
            var session = OpenSession();
            var cart    = GetOpenOrder(session, LockType.ForUpdate);

            OpContext.ThrowIfNull(cart, ClientFaultCodes.InvalidAction, "Cart", "Cart is empty, cannot submit order.");
            cart.Status = OrderStatus.Canceled;
            session.SaveChanges();
            return(cart.ToModel(details: true));
        }
Beispiel #26
0
        private ILoginProcess GetMutiFactorProcess(IEntitySession session, string token, bool throwIfNotFound = true)
        {
            OpContext.ThrowIfEmpty(token, ClientFaultCodes.ValueMissing, "token", "Process token may not be empty.");
            var processService = OpContext.App.GetService <ILoginProcessService>();
            var process        = processService.GetActiveProcess(session, LoginProcessType.MultiFactorLogin, token);

            if (throwIfNotFound)
            {
                OpContext.ThrowIfNull(process, ClientFaultCodes.ObjectNotFound, "LoginProcess", "Invalid login process token - process not found or expired.");
            }
            return(process);
        }
        public string ThrowNullRef()
        {
            //Before we throw, let's write smth to local log;
            OpContext.WriteLogMessage("Throwing NullReference exception...");
            string foo = null;

            if (foo.Length > 10)
            {
                foo = "bar";
            }
            return(foo);
        }
        public Book GetBook(Guid id)
        {
            var session = OpContext.OpenSystemSession();
            var bk      = session.GetEntity <IBook>(id);

            if (bk == null)
            {
                OpContext.WebContext.SetResponse(status: HttpStatusCode.NotFound);
                return(null);
            }
            return(bk.ToModel(details: true));
        }
        public void DeleteOrderItem(Guid id)
        {
            var session = OpenSession();
            var itemEnt = session.GetEntity <IBookOrderLine>(id);

            OpContext.ThrowIfNull(itemEnt, ClientFaultCodes.ObjectNotFound, "BookId", "Book not found.");
            //Lock order
            var cart = GetOpenOrder(session, LockType.ForUpdate);

            session.DeleteEntity(itemEnt);
            itemEnt.Order.ScheduleUpdateTotal();
            session.SaveChanges();
        }
        public BookOrderItem AddOrderItem(BookOrderItem item)
        {
            var session = OpenSession();
            var bk      = session.GetEntity <IBook>(item.Book.Id);

            OpContext.ThrowIfNull(bk, ClientFaultCodes.ObjectNotFound, "BookId", "Book not found.");
            var cart    = GetOpenOrder(session, LockType.ForUpdate, create: true);
            var itemEnt = cart.Add(bk, item.Quantity);

            cart.ScheduleUpdateTotal();
            session.SaveChanges();
            return(itemEnt.ToModel());
        }
Beispiel #31
0
	public OpContext op() {
		OpContext _localctx = new OpContext(Context, State);
		EnterRule(_localctx, 4, RULE_op);
		try {
			State = 74;
			ErrorHandler.Sync(this);
			switch ( Interpreter.AdaptivePredict(TokenStream,3,Context) ) {
			case 1:
				EnterOuterAlt(_localctx, 1);
				{
				State = 64; monad();
				}
				break;
			case 2:
				EnterOuterAlt(_localctx, 2);
				{
				State = 65; data();
				}
				break;
			case 3:
				EnterOuterAlt(_localctx, 3);
				{
				State = 66; biad();
				State = 67; arg();
				}
				break;
			case 4:
				EnterOuterAlt(_localctx, 4);
				{
				State = 69; triad();
				State = 70; arg();
				State = 71; Match(SEPARATOR);
				State = 72; arg();
				}
				break;
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}