protected void RestoreSession() { MyEntityContext ctx = Application.Context; string GUID = ""; // Я не хочу перезапускать сервак.... try { GUID = this.Request.Cookies[IN_SESSION_COOKIE_NAME]; } catch (KeyNotFoundException) { GUID = ""; } try { CurrentSession = activeSessions[GUID]; } catch (System.Collections.Generic.KeyNotFoundException) { CurrentSession = new SessionModel(); CurrentSession.GUID = ImportFromAtlcomru.GetGUID(); } bool a = CurrentSession.Valid; }
private IAgent createAnonymousAgent() { MyEntityContext ctx = Application.Context; if (GUID == null) { GUID = ImportFromAtlcomru.GetGUID(); } else { // Try load from database IAgent agent = ctx.Agents.Where(x => x.GUID == GUID).FirstOrDefault(); if (agent != null) { Agent = agent; } } IAgent anonym = ctx.Agents.Create(); anonym.GUID = GUID; anonym.Role = RoleEnum.Unknown; this.Agent = anonym; ctx.Add(this.Agent); ctx.SaveChanges(); return(this.Agent); }
public void Logout() { Session = new SessionModel(); Session["valid"] = false; Session.GUID = ImportFromAtlcomru.GetGUID(); Session["message"] = info("Вы вышли из системы и мы про вас забыли.", "Успехов"); // Плохо то, что у нас будут копиться анонимные сессии. }
protected Nancy.Response InSession(Nancy.Response response = null) { if (response == null) { throw new RenderException("null response object"); } if (String.IsNullOrEmpty(CurrentSession.GUID)) { CurrentSession.GUID = ImportFromAtlcomru.GetGUID(); CurrentSession["valid"] = "false"; } activeSessions[CurrentSession.GUID] = CurrentSession; return(response.WithCookie(IN_SESSION_COOKIE_NAME, CurrentSession.GUID)); }
private void importMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog() { InitialDirectory = ".", Filter = "All files (*.*)|*.*|Yandex Zipped XML files (*.xml.zip)|*.xml.zip|Yandex XML files (*.xml)|*.xml", Title = "Select Yandex XML file or an archive containing it for import" }; if (openFileDialog.ShowDialog() == DialogResult.OK) { Console.WriteLine(String.Format("Open File: '{0}'", openFileDialog.FileName)); ImportFromAtlcomru import = new ImportFromAtlcomru() { // FileName = openFileDialog.FileName InputStream = openFileDialog.OpenFile() }; import.Import(); } }
protected void RestoreSession() { string value = ""; try { value = this.Request.Cookies[IN_SESSION_COOKIE_NAME]; } catch (KeyNotFoundException) { value = ""; } CurrentSession = new SessionModel(); CurrentSession["valid"] = false; if (String.IsNullOrEmpty(value)) { // Сессия не устанвлена, т.е. пользователь не зарегистрирован CurrentSession.GUID = ImportFromAtlcomru.GetGUID(); // Сделать сессии идентификатор. return; } try { CurrentSession = activeSessions[value]; // По идее там будет где-то пользователь. object ouser = null; CurrentSession["valid"] = CurrentSession.TryGetValue("user", out ouser); // Сессия валидна, если оттуда можно вытащить пользователя. CurrentSession["valid"] = ouser != null; CurrentSession["GUID"] = value; return; } catch (System.Collections.Generic.KeyNotFoundException) { // Беспонтовая сессия, нам оно не надо // Возвращяем невалидную сессию по умолчанию CurrentSession.GUID = ImportFromAtlcomru.GetGUID(); // Пусть будет беспонтовая анонимная новая сессия. } }
public bool Process() { MyEntityContext ctx = Application.Context; string nick = request.Form.user; string phone = request.Form.phone; Console.WriteLine("---> FORM:" + nick); IAgent user = ctx.Agents.Where(x => x.NickName == nick).FirstOrDefault(); string register = request.Form["register"]; MessageModel success = null; if (register != null && user != null) { return(UserBad("Пользователь уже зарегистрирован")); } else if (register == null && user == null) { return(UserBad("Пользователь не найден")); } else if (register != null && user == null) { // FIXME: Проверки правильности данных не сделаны. string password = request.Form.password; string repeat = request.Form.repeat; if (password != repeat) { return(UserBad("Пароли не совпадают")); } user = ctx.Agents.Create(); user.Name = request.Form.firstname + " " + request.Form.surname + " " + request.Form.lastname; user.PasswordHash = BCryptHelper.HashPassword(password, SALT); user.Phone = request.Form.phone; user.GUID = ImportFromAtlcomru.GetGUID(); if (request.Form.realtor == "checked") { user.Role = RoleEnum.Agent; } else { user.Role = RoleEnum.Buyer; } user.NickName = nick; user.Email = request.Form.email; ctx.Add(user); ctx.SaveChanges(); success = info("Теперь вы зарегистрированы в системе. Можно начинать бояться.", msg: "Успешная регистрация"); } else // register == null && user != null { string password = request.Form.password; if (!BCryptHelper.CheckPassword(password, user.PasswordHash)) { return(UserBad("Неправильный пароль")); } success = info("Ну вот вы и вошли в систему.", msg: "Успешная идентикация"); } // К этому моменту пользователь или аутентифицирован // или создан. // Установить сессию. // Сессии бывают двух типов // 1. На время одного сеанса // 2. Между сеансами. // Мы будем делать 2 из 1. // Т.е. в сессии типа 1 собирать (обновлять) данные // зарегистрированного пользователя. Session = new SessionModel(); //Создание новой сессии Session["valid"] = true; Session["user"] = user; // Объект пользователя в сессии Session.GUID = user.GUID; // Идентификатор сессии пользователя. Session["message"] = success; Console.WriteLine("Linux rulez!"); // TODO: Еще надо сделать выход из сессии при разлогигивании. Но пока у нас нет такой команды. return(true); }