Exemplo n.º 1
0
        public bool IsSessionIntrudingOnOtherSessionsTimeframe(SessionModel newSession, IEnumerable<SessionModel> currentSessions)
        {
            bool isInConflict = true;

            if (!currentSessions.Any())
            {
                return false;
            }

            foreach (var session in currentSessions)
            {
                //Checks for exact match
                if (session.FromTime == newSession.FromTime && session.ToTime == newSession.ToTime)
                {
                    return isInConflict;
                }

                //Checks that newSessions FromTime is not inbetween the current sessions timeframe.
                isInConflict = IsTimeBetween(newSession.FromTime, session.FromTime, session.ToTime);

                if (isInConflict)
                {
                    return isInConflict;
                }

                //Checks that newSessions toTime is not inbetween the current sessions timeframe.
                isInConflict = IsTimeBetween(newSession.ToTime, session.FromTime, session.ToTime);

                if (isInConflict)
                {
                    return isInConflict;
                }
            }
            return isInConflict;
        }
        public IActionResult Post([FromBody] LoginModel login)
        {
            try
            {
                var session = sessionService.Login(login.UserName, login.Password);
                var ret     = new SessionModel();
                var user    = userService.GetUserByUserName(login.UserName);

                ret.Name     = user.Name;
                ret.Lastname = user.LastName;
                ret.UserId   = user.Id;
                ret.Username = user.UserName;
                ret.Token    = session.Token;

                if (user is Administrator)
                {
                    ret.IsAdmin = true;
                }
                else
                {
                    ret.IsAdmin = false;
                    employeeService.PutEmployeeStatus(ret.UserId, Status.CONNECTED);
                }

                var response = new ResponseModelWithData <SessionModel>()
                {
                    Data         = ret,
                    IsResponseOK = true
                };

                return(Ok(response));
            }
            catch (HandledException he)
            {
                var response = new ResponseModelWithData <SessionModel>()
                {
                    IsResponseOK = false,
                    ErrorMessage = he.Message
                };

                return(Ok(response));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Exemplo n.º 3
0
        public FirstCaseModel GetFirstCase(bool onlyNew, string computerName, SessionModel model)
        {
            var request = new RestRequest("/api/Capture/Case/First", Method.POST);

            request.AddQueryParameter("computerName", computerName);
            request.AddQueryParameter("onlyNew", onlyNew.ToString());
            request.AddJsonBody(model);

            var response = RestClient.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw CreateException(response);
            }

            return(JsonConvert.DeserializeObject <FirstCaseModel>(response.Content));
        }
Exemplo n.º 4
0
        public ActionResult CloseSession([FromBody] SessionModel model)
        {
            int userRole = GetAuthorizedUserRole();

            if (userRole != 1)
            {
                return(Unauthorized());
            }

            var currentSessionId = _sessionService.GetCurrentSession();

            _sessionService.CloseSession(currentSessionId);

            _sessionService.AddWinnersByThisSession(currentSessionId);

            return(Ok("Current session closed!"));
        }
Exemplo n.º 5
0
        public RetornoModel <SessionModel> GetSessao(bool completo = false)
        {
            if (completo)
            {
                using (var ado = new MasterADOBase())
                {
                    var bo = new CompraBOModel(SessionModel.GetSiteId(), ado);
                    CarregarCompra(bo, true);
                }
            }
            RetornoModel <SessionModel> retorno = new RetornoModel <SessionModel>();

            retorno.Sucesso  = true;
            retorno.Mensagem = "OK";
            retorno.Retorno  = SessionModel;
            return(ParseRetorno(retorno));
        }
 private void Upload()
 {
     while (true)
     {
         int    uploadInterval = ConfigurationManager.AppSettings["Upload_Interval"].ToInt();
         string gameName       = ConfigurationManager.AppSettings["ServerGameName"].ToString();
         int    minute         = DateTime.Now.Minute;
         bool   flag           = minute % uploadInterval == 0 && DateTime.Now.Second == 0;
         if (flag)
         {
             SessionModel session = CenterDataFactory.KeyTable();
             PoliceDataFactory.Entrance(session.Id, gameName);
             PoliceDataFactory.InspectTicket(session.Id, gameName);
             PoliceDataFactory.Ticket(session.Id, gameName);
         }
     }
 }
Exemplo n.º 7
0
        public async Task <IActionResult> Delete(SessionModel model)
        {
            try
            {
                await _appSession.DeleteAsync(model);

                TempData["Success"] = true;
                TempData["Message"] = "Sessão deletada com sucesso";
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                ViewBag.Success = false;
                ViewBag.Message = e.Message;
                return(View(model));
            }
        }
Exemplo n.º 8
0
        public IActionResult Active()
        {
            var          date    = DateTime.Now;
            SessionModel session = _userService.IsItSessionActive();

            if (session == null)
            {
                return(BadRequest("Closed for betting at the moment"));
            }

            if (session.StartDate <= date && date <= session.EndDate)
            {
                return(Ok("Open for betting"));
            }

            return(BadRequest("Closed for betting at the moment"));
        }
Exemplo n.º 9
0
        public APIResponseModel <string> Post([FromBody] SessionModel model)
        {
            //_sessionBusinessLogic.Insert(model);
            //return Ok();


            if (model.LocationId <= 0)
            {
                return(new APIResponseModel <string>(
                           "Cannot insert empty session.", StatusCodes.Status406NotAcceptable.ToString(), StatusCodes.Status406NotAcceptable, ""));
            }

            _sessionBusinessLogic.Insert(model);

            return(new APIResponseModel <string>(
                       "Session inserted successfully", StatusCodes.Status200OK.ToString(), StatusCodes.Status200OK, ""));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Get events created by the logged in user from the database and update the List for created events.
        /// </summary>
        public void UpdateCreatedEvents()
        {
            // Update created events list.
            this._createdEventsList.Clear();

            // Refresh the session first!
            SessionModel.GetInstance().Refresh();

            ICollection <DBLayer.Event> ownedEvents = SessionModel.GetInstance().LoggedInUser.OwnedEvents;

            foreach (DBLayer.Event e in ownedEvents)
            {
                this._createdEventsList.Add(new EventModel(e));
            }

            this.NotifyPropertyChanged("CreatedEventsList");
        }
        public void LoadSessions()
        {
            var startDate = DateTime.Today.AddDays(-365);
            var today     = DateTime.Now.Date;

            for (var currentDay = startDate; currentDay.Date <= today.Date; currentDay = currentDay.AddDays(1))
            {
                var session = new SessionModel()
                {
                    Created     = currentDay,
                    Title       = currentDay.ToString("D"),
                    Description = $"Activities for {currentDay:D}"
                };

                Sessions.Add(session);
            }
        }
Exemplo n.º 12
0
        public JsonResult GetAreas(String idDepto)
        {
            model = (SessionModel)this.Session["SessionData"];

            DeptoHelper dh    = new DeptoHelper();
            var         Areas = dh.GetArea(int.Parse(idDepto), Convert.ToInt32(model.ProfileID));

            if (Areas == null)
            {
                logger.Info("Areas no disponibles para crear nuevo usuario." + Environment.NewLine + DateTime.Now);
                return(Json(new { success = false, data = Areas, msgError = "Areas No Disponibles para este Depto." }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new { success = true, data = Areas }, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 13
0
        private IActionResult Session(string id, string id2)
        {
            var session = _db.Sessions.FindById(id);

            if (session == null || session.IdVerification != id2)
            {
                return(NotFound());
            }

            var vm = new SessionModel
            {
                SessionId           = id,
                SessionVarification = id2
            };

            return(View("Session", vm));
        }
Exemplo n.º 14
0
 public ActionResult Instruction(SessionModel model)
 {
     if (model != null)
     {
         context = new ApplicationDbContext();
         var test          = context.Tests.Where(x => x.IsActive == true && x.Id == model.TestId).SingleOrDefault();
         var questionCount = context.TestXQuestions.ToList(); /*.Where(x => x.IsActive == true && x.TestId == model.TestId).FirstOrDefault();*/
         if (test != null)
         {
             ViewBag.TestName        = test.Name;
             ViewBag.TestDescription = test.Description;
             ViewBag.QuestionCount   = questionCount.Count();
             ViewBag.TestDuration    = test.DurationInMinute;
         }
     }
     return(View(model));
 }
Exemplo n.º 15
0
        private Message GetMessageFromModel(SessionModel model, bool hasFile = false)
        {
            var utcNow = DateTime.UtcNow;

            return(new Message
            {
                Id = _db.NewGuid(),
                SessionId = model.SessionId,
                SessionIdVerification = model.SessionVerification,
                SocketConnectionId = model.SocketConnectionId,
                EncryptionPublicKeyAlias = model.EncryptionPublicKeyAlias,
                DateSent = utcNow,
                DateSentEpoch = utcNow.ToEpoch(),
                Text = model.ComposerText,
                HasFile = hasFile
            });
        }
Exemplo n.º 16
0
        public IActionResult Success()
        {
            //Order order = HttpContext.Session.GetOrder("order");
            //int orderId = this.OrderService.InsertOrder(order, GetCustomerId());
            //if (orderId != 0)
            //{
            SessionModel session = HttpContext.Session.GetSession("session");

            session.Products = new List <ProductInSessionModel>();
            //HttpContext.Session.SetSession("order", null);
            HttpContext.Session.SetSession("session", session);
            return(View());
            //}

            //else
            //    return View("Error");
        }
        public async Task <bool> OpenDashboard()
        {
            SessionModel session = await CreateSession();

            if (session != null)
            {
                Process.Start(new ProcessStartInfo(session.url)
                {
                    UseShellExecute = true
                });
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 18
0
    /// <summary>
    ///
    /// </summary>
    private void InitSession()
    {
        GameObject[] sliceables = GameObject.FindGameObjectsWithTag("Sliceable");

        foreach (GameObject obj in sliceables)
        {
            if (obj.activeSelf)
            {
                SessionModel model = obj.GetComponent <SessionModel>();

                if (model)
                {
                    LoadModel(model, null);
                }
            }
        }
    }
Exemplo n.º 19
0
        public ActionResult Login(UserModel user)
        {
            if (user != null)
            {
                try
                {
                    UserModel     userModel = DB.UserDAO.ReadUser(user.Login, user.Password);
                    EmployeeModel employee  = DB.EmployeesDAO.ReadEmployeeByUserId(userModel.IdUser, "en");

                    if (userModel != null)
                    {
                        string t     = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
                        string token = t.Replace("+", "xj3FFv").Replace("/", "3d66aS").Replace("=", "66Tsdo4").Replace(" ", "88rDrf");

                        SessionModel session = new SessionModel();
                        session.IdUser         = (long)userModel.IdUser;
                        session.Token          = token;
                        session.ExpirationDate = DateTime.Now.AddHours(6);
                        DB.SessionsDAO.InsertSession(session);
                        session.Login = userModel.Login;
                        if (employee != null)
                        {
                            session.UserType = DB.DictionaryDAO.ReadDictionaryById(DictionaryTypesEnum.Positions, employee.IdPosition, "en").label;
                        }
                        else
                        {
                            session.UserType = "Patient";
                        }

                        return(Json(session));
                    }
                    else
                    {
                        return(new HttpStatusCodeResult(404));
                    }
                }
                catch (Exception ex)
                {
                    return(new HttpStatusCodeResult(400));
                }
            }
            else
            {
                return(new HttpStatusCodeResult(400));
            }
        }
Exemplo n.º 20
0
        private void RegisterSession(int userId)
        {
            DateTime currentDateTime = DateTime.Now;

            SessionModel session = new SessionModel
            {
                SessionId = Guid.NewGuid().ToString(),
                UserId    = userId,
                Created   = currentDateTime,
                Expired   = currentDateTime.AddMinutes(15)
            };

            db.Sessions.Add(session);
            db.SaveChanges();

            contextAccessor.HttpContext.Response.Cookies.Append("SessionId", session.SessionId);
        }
Exemplo n.º 21
0
        public ActionResult Instruction(SessionModel model)
        {
            if (model != null)
            {
                var test = _context.Tests.Include(u => u.TestQuestions)
                           .Where(x => x.IsActive == true && x.TestID == model.TestID).FirstOrDefault();
                if (test != null)
                {
                    ViewBag.TestName        = test.Name;
                    ViewBag.TestDescription = test.Description;
                    ViewBag.QuestionCount   = test.TestQuestions.Count;
                    ViewBag.TestDuration    = test.DurationInMinute;
                }
            }

            return(View(model));
        }
Exemplo n.º 22
0
        public void LoadUsersResult(object sender, LoadUsersCompletedEventArgs e)
        {
            ONyR_client.model.vo.UserVO[] loadedUsers = Convert(e.Result);
            SessionModel sessionModel = ModelLocator.getInstance().SessionModel;

            foreach (ONyR_client.model.vo.UserVO user in loadedUsers)
            {
                if (sessionModel.UserId == user.ID)
                {
                    sessionModel.SetCurrentUser(user);
                    break;
                }
            }
            ModelLocator.getInstance().SessionModel.NotifyOneOperationDone();

            ModelLocator.getInstance().UserModel.AddUsers(loadedUsers);
        }
Exemplo n.º 23
0
        public async Task <CreateSessionResponse> CreateSessionAsync(CreateSessionRequest createSessionRequest, CancellationToken cancellationToken)
        {
            var session = new SessionModel
            {
                SessionId    = ObjectId.GenerateNewId().ToString(),
                SessionCode  = GetRandomCode(SessionCodeLength),
                Expires      = DateTime.UtcNow.AddDays(ExpiryTimeInDays),
                HostCode     = GetRandomCode(HostCodeLength),
                PointChoices = createSessionRequest.PointChoices
            };

            await _sessionRepo.InsertSessionAsync(session, cancellationToken);

            var user = new UserModel
            {
                SessionId = session.SessionId,
                UserId    = ObjectId.GenerateNewId().ToString(),
                AuthCode  = GetRandomCode(AuthCodeLength),
                Nickname  = createSessionRequest.Nickname,
                IsHost    = true
            };

            await _userRepo.InsertUserAsync(user, cancellationToken);

            var i = 0;

            foreach (var story in createSessionRequest.Stories)
            {
                story.SessionId  = session.SessionId;
                story.StoryIndex = i++;
            }

            await _storyRepo.InsertStoriesAsync(createSessionRequest.Stories, cancellationToken);

            ScheduleDeleteSession(session.SessionId);

            return(new CreateSessionResponse
            {
                SessionId = session.SessionId,
                SessionCode = session.SessionCode,
                HostCode = session.HostCode,
                PointChoices = session.PointChoices,
                UserId = user.UserId,
                AuthCode = user.AuthCode
            });
        }
        public async Task OnGetAsyncSuccessfull()
        {
            var testSession   = GetTestSessionResponse();
            var apiClientStub = new Mock <IApiClient>();

            apiClientStub.Setup(a => a.GetSessionAsync(It.IsAny <int>()))
            .ReturnsAsync(testSession);
            apiClientStub.Setup(a => a.GetSessionsAsync(It.IsAny <int>()))
            .ReturnsAsync(GetTestAllSessionsAsync());
            apiClientStub.Setup(a => a.GetSessionsByAttendeeAsync(It.IsAny <string>(), It.IsAny <int>()))
            .ReturnsAsync(GetTestAllSessionsAsync());

            var displayName = "User name";
            var identity    = new GenericIdentity(displayName);
            var principle   = new ClaimsPrincipal(identity);
            // use default context with user
            var httpContext = new DefaultHttpContext()
            {
                User = principle
            };
            //need these as well for the page context
            var modelState            = new ModelStateDictionary();
            var actionContext         = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
            var modelMetadataProvider = new EmptyModelMetadataProvider();
            var viewData = new ViewDataDictionary(modelMetadataProvider, modelState);
            // need page context for the page model
            var pageContext = new PageContext(actionContext)
            {
                ViewData = viewData
            };
            //create model with necessary dependencies
            var model = new SessionModel(apiClientStub.Object)
            {
                PageContext = pageContext
            };
            await model.OnGetAsync(testSession.ID);

            Assert.Equal(testSession.ID, model.Session.ID);
            Assert.Equal(testSession.Title, model.Session.Title);
            Assert.Equal(testSession.Abstract, model.Session.Abstract);

            Assert.True(model.IsInPersonalAgenda);

            Assert.Equal(1, model.DayOffset);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 操作权限认证
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public static bool Authentication(string token, string sid)
        {
            //测试时使用
            return(true);

            if (userhash.ContainsKey(token))
            {
                SessionModel sm = (SessionModel)userhash[token];
                if ((DateTime.Now - sm.lastoper).TotalSeconds < Timeout)
                {
                    int       rid = 0;
                    DataRow[] drs = rightsid.Select("SIDs like '%" + sid + "%'");
                    foreach (DataRow dr in drs)
                    {
                        rid = int.Parse(dr["A_ID"].ToString());
                        if (sm.aids.Contains(rid))
                        {
                            sm.lastoper    = DateTime.Now;
                            sm.lastopersid = rid.ToString();
                            lock (userhash.SyncRoot)
                            {
                                userhash[token] = sm;
                            }
                            return(true);
                        }
                    }
                    return(false);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                if (GSRunFlag && GetGlobalSessionToLocal(token))
                {
                    return(Authentication(token, sid));
                }
                else
                {
                    return(false);
                }
            }
        }
Exemplo n.º 26
0
        private async void SaveCommandExecuteAsync()
        {
            if (String.IsNullOrEmpty(Name) || String.IsNullOrEmpty(SelectedActivity.Name))
            {
                await Application.Current.MainPage.DisplayAlert("Atención", "Debe rellenar todos lo campos", "Aceptar");
            }
            else
            {
                SessionModel newSession = new SessionModel();
                if (modify)
                {
                    newSession.ID = session.ID;
                }
                newSession.Name         = Name;
                newSession.Description  = Description;
                newSession.ActivityName = SelectedActivity.Name;
                if (!modify)
                {
                    newSession.CreateDate = DateTime.Now;
                }
                else
                {
                    newSession.CreateDate = session.CreateDate;
                }
                newSession.ModifyDate = DateTime.Now;
                newSession.UserID     = user.ID;

                App.Database.SaveSession(newSession);

                if (modify)
                {
                    await Application.Current.MainPage.DisplayAlert("Información", "La sesión se ha modificado correctamente", "Aceptar");
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Información", "La sesión se ha creado correctamente", "Aceptar");
                }

                await Navigation.PopAsync();

                Name             = null;
                Description      = "";
                SelectedActivity = null;
            }
        }
Exemplo n.º 27
0
        public void Favorites_Clicked(object sender, EventArgs e)
        {
            try
            {
                Image        imageSender   = (Image)sender;
                SessionModel sendercontext = (SessionModel)imageSender.BindingContext;
                var          id            = sendercontext.Id;
                if (App.Favoritesessions != null)
                {
                    var session = App.Favoritesessions.FirstOrDefault(f => f.Id == id);
                    if (session != null)
                    {
                        if (session.isFavorite)
                        {
                            var sessionItem = (from item in App.Favoritesessions
                                               where item.Id == session.Id
                                               select item).FirstOrDefault();

                            if (sessionItem != null)
                            {
                                session.isFavorite = false;
                                App.Favoritesessions.Remove((SessionModel)sessionItem);
                                App.SaveFavorites();
                            }
                        }
                        //else
                        //{
                        //    // check if it is already there before adding
                        //    var sess = App.Favoritesessions.FirstOrDefault(f => f.Id == id);
                        //    if (sess == null)
                        //    {
                        //        session.isFavorite = true;
                        //        App.Favoritesessions.Add((SessionModel)session);
                        //        App.SaveFavorites();
                        //    }
                        //}
                        lvSession2.ItemsSource = App.Favoritesessions;
                    }
                }
            }
            catch (Exception ex)
            {
                string h = ex.Message;
            }
        }
Exemplo n.º 28
0
        public ActionResult Index(User user)
        {
            if (ModelState.IsValid)
            {
                using (UserDataModel db = new UserDataModel())
                {
                    var obj   = db.User.Where(a => a.username.Equals(user.username)).FirstOrDefault();
                    var pass1 = obj.password;
                    var pass2 = user.password;

                    var validatePass = Crypto.VerifyHashedPassword(pass1, pass2);
                    if (obj != null && validatePass)
                    {
                        var profile = db.Profile.Where(p => p.idUser.Equals(obj.idUser)).FirstOrDefault();

                        /*Session["UserID"] = obj.idUser.ToString();
                         * Session["UserName"] = obj.username.ToString();
                         * Session["ProfileID"] = profile.idProfile.ToString();
                         * Session["rolName"] = profile.rolName.ToString();*/

                        SessionModel sm = new SessionModel()
                        {
                            UserID     = obj.idUser.ToString(),
                            UserName   = obj.username.ToString(),
                            ProfileID  = profile.idProfile.ToString(),
                            RolName    = profile.rolName.ToString(),
                            UserActive = true
                        };

                        Session["SessionData"] = sm;

                        //Write in Log
                        LogManager.Configuration.Variables["userid"]   = sm.UserID;
                        LogManager.Configuration.Variables["username"] = sm.UserName;
                        logger.Info("Initialize Session VTIntranet with username: "******"Index", "Home"));
                    }
                }
            }

            logger.Error("Attempted to login but credentials are incorrect " + Environment.NewLine + DateTime.Now);
            return(View(user));
        }
Exemplo n.º 29
0
        public SessionModel GetCurrentUser(string sessionid)
        {
            if (string.IsNullOrEmpty(sessionid))
            {
                throw new ArgumentNullException("用户SessionId为空", innerException: null);
            }
            SessionModel sessionModel = null;

            try
            {
                sessionModel = CacheResolver.GetCache(sessionid) as SessionModel;
            }
            catch (NullReferenceException)
            {
                throw new UserException("用户信息已经失效,请重新登陆");
            }
            return(sessionModel);
        }
Exemplo n.º 30
0
        // GET:
        public IActionResult CustomerProfile()
        {
            //CustomerModel customer = HttpContext.Session.GetCustomer("customer");
            SessionModel session = HttpContext.Session.GetSession("session");

            //if (customer.Name != null)
            if (session != null)
            {
                //var temp = this.CustomerService.GetById(customer.Id);
                var temp = this.CustomerService.GetById(session.CustomerId);
                var customerProfileViewModel = Mapper.Map <Customer, CustomerProfileViewModel>(temp);
                return(View(customerProfileViewModel));
            }
            else
            {
                return(View());
            }
        }
Exemplo n.º 31
0
        public ActionResult Index()
        {
            var _ctx = new MyQuizNewEntities();

            ViewBag.Test = _ctx.Test.Where(x => x.IsActive == true).Select(x => new { x.Id, x.Name }).ToList();

            SessionModel _model = null;

            if (Session["SessionModel"] == null)
            {
                _model = new SessionModel();
            }
            else
            {
                _model = (SessionModel)Session["SessionModel"];
            }
            return(View(_model));
        }
Exemplo n.º 32
0
        public void CreateAnActivity()
        {
            var session = new SessionModel
                {
                    FromTime = new TimeSpan(12, 00, 00),
                    ToTime = new TimeSpan(14, 00, 00),
                    VolunteersNeeded = 1
                };

            var sessions = new List<SessionModel>
                 {
                     session
                 };

            var createActivityModel = new CreateActivityModel
                {
                    Information = "Henrik testar",
                    Name = "Henrik",
                    Date = DateTime.Now.AddDays(1),
                    Sessions = sessions
                };
            var activityController = new ActivityController(SecurityService, _activityRepository.Object, _teamRepository.Object, EmailServices.Object,null);
            var id = activityController.Create(createActivityModel) as ActionResult;
        }
Exemplo n.º 33
0
        private Response Login()
        {
            var username = (string)Data.UserName;
            var password = (string)Data.Password;
            var users = _users.Query().Where(u => u.StoredUserName == username.ToLower()).ToList();
            Response response;

            if (users.Count == 0)
            {
                response = Response.Error(Res.User.Login.IncorrectLogin);
            }
            else if (users.Count > 1) //More than one user with the same name?!
            {
                //Log this weird occurance and deny
                _logger.Log(new LogMessageModel("More than one user found with the username '" + username + "'."));
                response = Response.Error(Res.User.Login.IncorrectLogin);
            }
            else
            {
                var user = users.First();
                var hashedPW = (password + user.Id).GetSha1Hash(); //Using user's id as the salt

                if (user.AccountLocked)
                {
                    //Too many attempts.
                    user.LastLogin = DateTime.Now;
                    _logger.Log(new LogMessageModel("Too many login attempts for username '" + username + "' under the IP address: " + Request.UserHostAddress));
                    response = Response.Error(Res.User.Login.TooManyAttempts);
                }
                else if (user.Password != hashedPW)
                {
                    var tries = user.LoginAttempts + 1;

                    user.LastLogin = DateTime.Now;
                    user.LoginAttempts = tries;

                    if (tries >= MaxLoginRetries)
                    {
                        user.AccountLocked = true;
                        _logger.Log(new LogMessageModel("Too many login attempts for username '" + username + "' under the IP address: " + Request.UserHostAddress));
                    }

                    response = Response.Error(Res.User.Login.IncorrectLogin);
                }
                else
                {
                    //Success!
                    var session = new SessionModel(!Request.Form.RememberMe.HasValue);

                    _sessions.Store(session);

                    if (Context.Items.ContainsKey(SecureAPIModule.SessionItemKey))
                        Context.Items[SecureAPIModule.SessionItemKey] = session;
                    else
                        Context.Items.Add(SecureAPIModule.SessionItemKey, session);

                    user.LastLogin = DateTime.Now;
                    user.LoginAttempts = 0;

                    response = Response.AsRedirect("~/");
                    response.StatusCode = HttpStatusCode.OK;
                }

                _users.Update(user);
            }

            return response;
        }
Exemplo n.º 34
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            this.FadeToTransparent (grdLoginInfo.Name);
            this.FadeToOpaque(lblStatus.Name);

            Settings.Set("SavePassword", chkSave.IsChecked == true);
            Settings.Set("AutoLogin", chkAutoLogin.IsChecked == true);
            if ((bool)chkSave.IsChecked) Settings.SetSecure("Password", txtPassword.Password.ToSecureString(), SessionModel.KEY);
            Settings.Set("UserName", txtUserName.Text);
            Settings.Save();

            this.Try (() => windowsTaskbar.SetProgressState(TaskbarProgressBarState.Indeterminate));

            model = new SessionModel(txtUserName.Text, txtPassword.Password);

            model.OnLoginFailure += () =>
            {
                this.Invoke(() =>
                    {
                        this.FadeToTransparent(lblStatus.Name);
                        this.FadeToOpaque(grdLoginInfo.Name);
                        windowsTaskbar.SetProgressState(TaskbarProgressBarState.NoProgress);
                        gpLoginBox.Header = "Invalid Username or Password";
                    });
            };
            model.OnLoginSuccess += () =>
            {
                this.Invoke(() =>
                {
                    Settings.Set("LoginCount", Settings.Get("LoginCount", 1) + 1);
                    int loginCount = Settings.Get("LoginCount", 0);
                    Debug.WriteLine("Login Count: " + loginCount);

                    if (loginCount > 5)
                    {
                        if (!Settings.Get("donate14", false))
                        {
                            Debug.WriteLine("Welcome Open");
                            Welcome w = new Welcome();
                            w.Show();
                        }
                    }

                    Title = "GVNotifier";
                    LoggedInPage.Visibility = System.Windows.Visibility.Visible;
                    LoginPage.Visibility = System.Windows.Visibility.Hidden;
                    this.FadeToTransparent(LoginPage.Name);
                    this.FadeToOpaque(LoggedInPage.Name);
                    txtSearch.Focus();

                    lsvContacts.ItemsSource = model.Contacts;
                    ConfigureListView();
                    SyncContactsJumpList();

                    this.Try(() => windowsTaskbar.SetProgressState(TaskbarProgressBarState.Normal));

                    SelectedView = lsvContacts;
                    DavuxLib2.Platform.DwmApi.DwmExtendFrameIntoClientArea(this, new Thickness(0, gLoginTop.ActualHeight * this.GetDPI(), 0, 1 + (bottomPanel.ActualHeight * this.GetDPI())));

                    model.account.Ready += () => this.Invoke(() => FitColumn(lsvVM, lsvNameColVM));
                });
            };
            model.OnLoginMessage += (s) =>
            {
                this.Invoke(() => lblStatus.Text = s);
            };

            model.account.ContactsManager.ContactsLoadingUpdate += (v, max) =>
            {
                if (windowsTaskbar != null)
                {
                    this.Try(() => windowsTaskbar.SetProgressState(TaskbarProgressBarState.Normal));
                    this.Invoke(() => TaskbarManager.Instance.SetProgressValue(v, max));
                }
            };

            model.Login();

            model.OnMessage += new Action<GoogleVoice.Message,GoogleVoice.Contact>(model_OnMessage);
            model.OnContactsUpdated += () =>
            {
                this.Invoke(() =>
                {
                    if (windowsTaskbar != null)
                    {
                        this.Try(() => windowsTaskbar.SetProgressState(TaskbarProgressBarState.NoProgress));
                    }
                        Debug.WriteLine("Reloading Contacts View");
                    ResizeGridViewColumn(lsvNameCol);
                    SyncContactsJumpList();
                });
            };

            lblStatus.Text = "Waiting...";
            lblStatus.Visibility = System.Windows.Visibility.Visible;
            gpLoginBox.Header = "";

            // TODO still not right for loading a window above
            model.OnJumpListContact += (c) =>
            {
                this.Invoke(() =>
                {
                    var mw = WindowForContact(c);
                    mw.Show();
                    this.InvokeDelay(100, () =>
                    {
                        mw.Activate();
                        mw.Focus();
                    });
                });
            };
        }