public override void Init()
    {
        base.Init();
        this.Create(Config.VIEW_LOGINCARD, false);

        userModel = ModelManager.inst.userModel;
        chatModel = ModelManager.inst.chatModel;
        //
        this.GetChild("n17").asTextField.text = Tools.GetMessageById("25501");
        //
        listData = new List <object[]> ();
        Dictionary <string, object> data = (Dictionary <string, object>)userModel.records ["guild_support_logs"];

        this.GetChild("n7").text = Tools.GetMessageById("25502");
        this.GetChild("n9").text = Tools.GetMessageById("25503");

        card = this.GetChild("n8").asCom as ComCard;
        list = this.GetChild("n12").asList;
//		bar = this.GetChild ("n4").asCom as ComProgressBar;
//		bar.skin = ComProgressBar.BAR7;

        int count = 0;
        Dictionary <string, object> users = (Dictionary <string, object>)data ["data"];

        object[] obj;
        foreach (string n in users.Keys)
        {
            obj = new object[3];
            object[] ob = (object[])users [n];
            obj [0] = n;
            obj [1] = ob [0];
            obj [2] = ob [1];
            listData.Add(obj);
            count += Convert.ToInt32(obj [2]);
        }

        int max = chatModel.GetCardRequestCount(data ["cid"].ToString(), userModel.effort_lv);

//		bar.value = count;
//		bar.max = max;
        this.GetChild("n19").asTextField.text = count + "/" + max;
        CardVo vo = DataManager.inst.GetCardVo(data ["cid"].ToString());

        card.SetData(vo.id, 1, 1);
        card.SetText(Tools.GetMessageById(vo.name));

        this.GetChild("n11").text = vo.exp + "";       // + "/" + vo.maxExp;
        this.GetChild("n18").text = "/" + vo.maxExp;

        list.itemRenderer = Item_Render;
        list.SetVirtual();
        list.numItems = listData.Count;
    }
        public ActionResult Edit(ModelUser modelUser)
        {
            String baoloi = "";

            if (ModelState.IsValid)
            {
                try
                {
                    var file = Request.Files["img"];
                    if (!file.FileName.Equals(""))
                    {
                        modelUser.Update_By       = (int?)Session["UserIdAdmin"];
                        modelUser.Update_At       = DateTime.Now;
                        db.Entry(modelUser).State = EntityState.Modified;
                        db.SaveChanges();
                        Session["FullNameAdmin"] = modelUser.FullName;
                        int id = modelUser.Id;
                        Session["UserIdAdmin"] = id;
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        string[] FileExtentsions = new string[] { ".jpg", ".gif", ".png" };
                        if (!FileExtentsions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                        {
                            baoloi += "Kiểu Tập Tin " + string.Join(", ", FileExtentsions) + " Không Cho Phép!";
                        }
                        else
                        {
                            string strName  = Mystring.str_slug(modelUser.FullName);
                            String fileName = strName + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                            modelUser.Img = fileName;
                            String Strpath = Path.Combine(Server.MapPath("~/Public/Image/User"), fileName);
                            file.SaveAs(Strpath);
                            modelUser.Update_By       = (int?)Session["UserIdAdmin"];
                            modelUser.Update_At       = DateTime.Now;
                            db.Entry(modelUser).State = EntityState.Modified;
                            db.SaveChanges();
                            Session["FullNameAdmin"] = modelUser.FullName;
                            Session["UserIdAdmin"]   = modelUser.Id;
                            Session["ImgAdmin"]      = modelUser.Img;
                            return(RedirectToAction("Index"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    baoloi += "Không Thành Công";
                }
            }
            ViewBag.Error = baoloi;
            return(View(modelUser));
        }
Beispiel #3
0
        public ActionResult DeleteConfirm(ModelUser model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Delete", "Admin"));
            }
            List <ModelUserRole> UR = _userRoleStore.GetUserRolesByUser(model.Username).ToList();

            HelpingClass.FEach(UR, x => _userRoleStore.DeleteUserRole(x));
            _userStore.DeleteUser(model);
            return(RedirectToAction("Delete", "Admin"));;
        }
Beispiel #4
0
        public void ReEstablishResilientOpenRequest(ModelUser user)
        {
            reconnectClient = new Smb2FunctionalClient(testConfig.Timeout, testConfig, this.Site);

            AccountCredential account = testConfig.AccountCredential;

            if (user == ModelUser.DefaultUser)
            {
                account = testConfig.AccountCredential;
            }
            else if (user == ModelUser.DiffUser)
            {
                account = testConfig.NonAdminAccountCredential;
            }

            // Connect to Share
            ConnectToShare(
                Site,
                testConfig,
                reconnectClient,
                new DialectRevision[] { dialect },
                clientGuid,
                account,
                out dialect,
                out treeId);


            // Reconnect to the Open
            Smb2CreateContextResponse[] createContextResponse;

            testConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_RECONNECT);

            uint status = reconnectClient.Create(
                treeId,
                fileName,
                CreateOptions_Values.NONE,
                out fileId,
                out createContextResponse,
                createContexts: new Smb2CreateContextRequest[]
            {
                new Smb2CreateDurableHandleReconnect()
                {
                    Data = fileId
                }
            },
                checker: (header, response) =>
            {
                // do nothing, skip the exception
            }
                );

            ReEstablishResilientOpenResponse((ModelSmb2Status)status);
        }
 private string GetManager(ModelUser user)
 {
     try
     {
         return(user?.Login);
     }
     catch (Exception ex)
     {
         App.SendException(ex);
         return(null);
     }
 }
        public IActionResult Index()
        {
            tblKullanicilar tblKullanicilar = _ItblKullanicilarService.GetById(StaticValues.LoginId);
            ModelUser       model           = new ModelUser();

            model.name            = tblKullanicilar.Isim;
            model.surname         = tblKullanicilar.Soyisim;
            model.isSuccessfull   = null;
            model.yonetmenliklist = _ItblYonetmenlikService.GetAll();
            model.kanunlist       = ITblKanunService.GetAll();
            return(View(model));
        }
Beispiel #7
0
    //支援次数今天用完
    public bool IsSendGiveCard()
    {
        ModelUser userModel = ModelManager.inst.userModel;
        int       use       = Convert.ToInt32(Tools.Analysis(userModel.records, "guild_support.used_coin"));
        int       count     = Convert.ToInt32(Tools.Analysis(DataManager.inst.guild, "support.support_times[" + (userModel.effort_lv - 1) + "]"));

        if (use >= count)
        {
            return(false);
        }
        return(true);
    }
        public ActionResult DangKy2(ModelUser kh)
        {
            //var check = db.KhachHangs.SingleOrDefault(c => c.taiKhoan == kh.username);
            try
            {
                if (ModelState.IsValid)
                {
                    KhachHang khach = new KhachHang();
                    khach.tenKH = kh.tenKH;
                    khach.DiaChi = kh.diaChi;
                    khach.email = kh.email;
                    khach.sodt = kh.sdt;

                    khach.taiKhoan = kh.username;
                    khach.matKhau = kh.password;
                    db.KhachHangs.Add(khach);
                    db.SaveChanges();
                    return RedirectToAction("DangNhap", "NguoiDung");
                }
                return View();
                
            }
            catch (Exception ex)
            {

                ViewBag.thongBao = "Tài khoản bị trùng";
                return View();
            }

            //if (check == null && kh.password == kh.confirmPassword)
            //{
            //    KhachHang khach = new KhachHang();
            //    khach.tenKH = kh.tenKH;
            //    khach.DiaChi = kh.diaChi;
            //    khach.email = kh.email;
            //    khach.SDT = kh.sdt;

            //    khach.taiKhoan = kh.username;
            //    khach.matKhau = kh.password;
            //    db.KhachHangs.Add(khach);
            //    db.SaveChanges();
            //    return RedirectToAction("DangNhap", "NguoiDung");
            //}

            //else
            //{

            //    return View();
            //}


        }
    private void InitData()
    {
        userModel     = ModelManager.inst.userModel;
        shareModel    = ModelManager.inst.shareModel;
        sumClick      = (int)((Dictionary <string, object>)userModel.records["share_data"])["sum_n"];      //被点击的总数
        sumShare      = (int)((Dictionary <string, object>)userModel.records["share_data"])["sum_num"];    //分享出去的总次数
        todaySumClick = userModel.ipList;                                                                  //今日被点击的数
        todaySumShare = (int)((Dictionary <string, object>)userModel.records["share_data"])["succ_times"]; //分享出去的次数
        weekClike     = (int)((Dictionary <string, object>)userModel.records["share_data"])["week_n"];
        timeNewClick  = (DateTime)((Dictionary <string, object>)userModel.records["share_data"])["t"];
        timeNewShare  = (DateTime)((Dictionary <string, object>)userModel.records["share_data"])["succ_time"];
        qrType        = "**%%_%%**";
        Dictionary <string, object> dd = (Dictionary <string, object>)DataManager.inst.systemSimple["weixin_gift"];
        string shareM = dd["key"].ToString();

        string md5Result   = userModel.uid + shareM + string.Format("{0:s}", ModelManager.inst.gameModel.time).Split('T')[0];
        string byte2String = Tools.MD5(md5Result);

        Debug.Log(byte2String);
        shareUrl   = DataManager.inst.systemSimple["share_url"].ToString() + userModel.uid + "&code=" + byte2String;
        shareUrl_  = DataManager.inst.systemSimple["share_url_"].ToString() + userModel.uid + "&code=" + byte2String;
        baseUrl    = DataManager.inst.systemSimple["share_base_url"].ToString();
        share      = (Dictionary <string, object>)DataManager.inst.systemSimple["share"];
        isUid      = userModel.records["invite_uid"] + "";
        qrCode_str = LocalStore.GetLocal(LocalStore.LOCAL_QRCODE + userModel.uid);

        Dictionary <string, object> inviteList = (Dictionary <string, object>)share["invite"];
        List <object> arr1 = Tools.ConvertDicToList(inviteList, "name");

        Tools.Sort(arr1, new string[] { "name:int:0" });
        data = new List <object>();
        foreach (object v in arr1)
        {
            string name  = ((Dictionary <string, object>)v)["name"].ToString();
            string value = ((Dictionary <string, object>)v)[name].ToString();
            data.Add(name);
            data.Add(value);
        }
        yaoQingText = Tools.GetMessageById("19441", new string[] {
            data[0] + "",
            data[1] + "",
            data[2] + "",
            data[3] + "",
            data[4] + "",
            data[5] + "",
        });
        clickNum     = (int)(((object[])share["share2"])[0]);
        clickGetCoin = (int)(((object[])share["share2"])[1]);
        WeekClickNum = (int)(((object[])share["share2"])[2]);
        shareNum     = (int)(((object[])share["share1"])[0]);
        shareGetCoin = (int)(((object[])share["share1"])[1]);
    }
Beispiel #10
0
        private void Authorize_Click(object sender, RoutedEventArgs e)
        {
            string    login      = TB_Login.Text;
            string    password   = Hesher.MD5Hash(TB_Password.Password);
            bool      userExist  = false;
            ModelUser findedUser = null;

            foreach (ModelUser user in App.Repository.Users)
            {
                if (login == user.Login)
                {
                    userExist  = true;
                    findedUser = user;
                }
            }

            if (!userExist)
            {
                ShowValidMessageLogin();
                return;
            }

            if (password == findedUser.Password)
            {
                if (_close)
                {
                    Application.Current.Shutdown();
                }
                else
                {
                    App.IsAuthorized = true;
                    var entry = App.Frame.RemoveBackEntry();

                    while (entry != null)
                    {
                        entry = App.Frame.RemoveBackEntry();
                    }

                    App.Frame.Navigate(new PageFunction <string>()
                    {
                        RemoveFromJournal = true
                    });
                    App.AuthorizedUser = findedUser;
                    App.Frame.Navigate(new StartUpPage());
                }
            }
            else
            {
                ShowValidMessagePassword();
                return;
            }
        }
Beispiel #11
0
        public List <ModelUser> GetStudentUsers()
        {
            var                  model         = new ModelUser();
            StoreUserRole        userRoleStore = new StoreUserRole(_ctx);
            List <ModelUser>     final         = new List <ModelUser>();
            List <ModelUserRole> studentURs    = userRoleStore.ReadUserRoles().Where(x => x.RoleName == "student").ToList();

            foreach (ModelUserRole item in studentURs)
            {
                final.Add(GetUser(item.Username));
            }
            return(final);
        }
        private bool AuthToken(string username, string token)
        {
            ModelUser userSystem = new ModelUser();

            if (userSystem.isTokenExist(username, token))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #13
0
        /// <summary> Конструктор </summary>
        public ViewUser()
        {
            InitializeComponent();

            _viewModelUser = new ViewModelUser();

            _modelUser = _viewModelUser.CurrentModelUser;

            DataContext = _viewModelUser;

            // не перересовывается панель с статусом пользователя по этоум приходится руками сворачивать панель баланса
            StackPanelBalance.Visibility = _modelUser.HasBalance ? Visibility.Visible : Visibility.Collapsed;
        }
Beispiel #14
0
        public IActionResult Index(ModelUser model)
        {
            string Url = Request.GetDisplayUrl();

            string[]  sub    = Url.Split("/");
            int       length = sub.Length;
            int       id     = Int32.Parse(sub[length - 1].Substring(0, 1));
            TblDuyuru temp   = _ITblDuyuruService.GetById(id);

            if (temp.aktif == 1)
            {
                temp.aktif = 0;
            }
            else
            {
                temp.aktif = 1;
            }
            _ITblDuyuruService.Update(temp);

            tblKullanicilar tblKullanicilar = _IKullanicilarService.GetById(StaticValues.LoginId);
            ModelUser       user            = new ModelUser();

            user.name    = tblKullanicilar.Isim;
            user.surname = tblKullanicilar.Soyisim;

            DuyurularDtoResponse db     = new DuyurularDtoResponse(_ItblResimDuyuruService, _ItblPdfDuyuruService, _ITblDuyuruService, _ItblResimService, _ItblPdfService);
            ModelDuyurular       model1 = new ModelDuyurular();

            model1.listDuyuru = new List <DuyurularDto>();
            string Url1 = Request.GetDisplayUrl();

            string[]  sub1        = Url1.Split("/");
            int       length1     = sub.Length;
            int       id1         = Int32.Parse(sub1[length1 - 1].Substring(0, 1));
            ModelUser modelDuyuru = new ModelUser();

            modelDuyuru.duyuru = new DuyurularDto();
            foreach (var VARIABLE in db.DuyuruList())
            {
                if (id1 == VARIABLE.id)
                {
                    modelDuyuru.duyuru = VARIABLE;
                }
            }

            modelDuyuru.name    = tblKullanicilar.Isim;
            modelDuyuru.surname = tblKullanicilar.Soyisim;

            modelDuyuru.duyuru.array = modelDuyuru.duyuru.aciklama.Split("<br>");
            return(View(modelDuyuru));
        }
        public IActionResult Index(String Nom, String User, String pass, int edad, String direcion)
        {
            ModelUser user       = new ModelUser();
            var       validacion = user.Registro(Nom, User, pass, edad, direcion);

            if (validacion == true)
            {
                return(View());
            }
            else
            {
                return(View());
            }
        }
Beispiel #16
0
 public override void Init()
 {
     base.Init();
     Create(Config.VIEW_GAMESET);
     userModel            = ModelManager.inst.userModel;
     roleModel            = ModelManager.inst.roleModel;
     this.isAttention     = (bool)userModel.records ["follow_sign"];
     this.isInvite        = (bool)userModel.records ["invite_sign"]; //+		["follow_sign"]	false	System.Collections.DictionaryEntry
     this.isVoice         = (bool)userModel.records["chat_voice_sign"];
     this.isDreamAttetion = (bool)userModel.records["request_sign"]; //求关注
     //this.isDreamAttetion = true;
     FindObject();
     InitData();
 }
Beispiel #17
0
 private void InitDate()
 {
     roleModel = ModelManager.inst.roleModel;
     userModel = ModelManager.inst.userModel;
     rankMax   = (int)DataManager.inst.systemSimple["season_ranking"];
     if (roleModel.otherInfo["uid"].ToString().Equals(userModel.uid) && ModelRole.fight4 != null && ModelRole.fight4.Count != 0)
     {
         SetData(ModelRole.fight4);
     }
     else
     {
         GetData();
     }
 }
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ModelUser modelUser = db.Users.Find(id);

            if (modelUser == null)
            {
                return(HttpNotFound());
            }
            return(View(modelUser));
        }
Beispiel #19
0
 public void setUser(ModelUser user)
 {
     this.Dispatcher.Invoke(() => {
         nameTxtBlock.setText(user.full_name);
         if (user.phone_number != null)
         {
             phoneNumberTxtBlock.setText(user.phone_number);
         }
         if (user.profile_picture != null)
         {
             picture.ImageSource = new BitmapImage(new Uri(ApiConstant.BASE_URL + user.profile_picture));
         }
     });
 }
Beispiel #20
0
    public int GetChatRedCount()
    {
        ModelUser userModel = ModelManager.inst.userModel;

        if (redCount == -1)
        {
            redCount  = 0;
            redCount += userModel.Get_NoticeState(ModelUser.RED_REDBAGNUM);
            redCount += userModel.Get_NoticeState(ModelUser.RED_SUPPORTNUM);
            redCount += userModel.Get_NoticeState(ModelUser.RED_GUILDAPPLYNUM);
            redCount += userModel.Get_NoticeState(ModelUser.RED_GUILDJOIN);
            redCount += userModel.Get_NoticeState(ModelUser.RED_GUILDEXIT);
        }
        return(redCount);
    }
        public static ModelPhoto AddPhoto(ModelPlace place, ModelUser user, string url, MainContext db)
        {
            if (!user.Equals(place.Author))
            {
                throw new UnauthorizedAccessException();
            }
            var photo = new ModelPhoto {
                Place = place, Url = url
            };

            db.Photos.Add(photo);
            place.Photos.Add(photo);
            db.SaveChanges();
            return(photo);
        }
 public IActionResult Index()
 {
     try
     {
         tblKullanicilar tblKullanicilar = _ItblKullanicilarService.GetById(StaticValues.LoginId);
         ModelUser       user            = new ModelUser();
         user.name    = tblKullanicilar.Isim;
         user.surname = tblKullanicilar.Soyisim;
         return(View(user));
     }
     catch (Exception e)
     {
         return(Redirect("Giris"));
     }
 }
Beispiel #23
0
 public void Register()
 {
     gameModel  = new ModelGame();
     alertModel = new ModelAlert();
     userModel  = new ModelUser();
     roleModel  = new ModelRole();
     guildModel = new ModelGuild();
     chatModel  = new ModelChat();
     cardModel  = new ModelCard();
     mailModel  = new ModelMail();
     fightModel = new ModelFight();
     rankModel  = new ModelRank();
     guideModel = new ModelGuide();
     shareModel = new ModelShare();
 }
Beispiel #24
0
 private void InitDate()
 {
     userModel = ModelManager.inst.userModel;
     roleModel = ModelManager.inst.roleModel;
     rankModel = ModelManager.inst.rankModel;
     Tools.setRankData();
     if (roleModel.otherInfo["uid"].ToString().Equals(userModel.uid) && ModelRole.fight1 != null)
     {
         SetData(ModelRole.fight1);
     }
     else
     {
         GetData();
     }
 }
Beispiel #25
0
        public IActionResult Index(String User, String pass)
        {
            ModelUser user       = new ModelUser();
            var       validacion = user.Login(User, pass);

            if (validacion == true)
            {
                return(RedirectToAction("Index", "Blogs"));
            }
            else
            {
                ViewBag.mess = "La contraseña o el usuario es incorrecta ";
                return(View());
            }
        }
        public ViewResult AccountSetting()
        {
            var userImg = _dbcontext.UsersImg.FirstOrDefault(u => u.UId.Equals(User.Identity.Name));

            if (userImg != null)
            {
                ViewBag.img = Infrastructure.ImageConverter.ConvertToString(userImg.UImg);
            }
            var       dbUser    = _dbcontext.Users.FirstOrDefault(u => u.UId.Equals(User.Identity.Name));
            ModelUser user      = new ModelUser(dbUser.UId, dbUser.UEmail, dbUser.UFirstName, dbUser.ULastName, dbUser.UBirthDay);
            var       dbuserImg = _dbcontext.UsersImg.FirstOrDefault(u => u.UId.Equals(User.Identity.Name));

            user.img = Infrastructure.ImageConverter.ConvertToString(dbuserImg.UImg);
            return(View(user));
        }
Beispiel #27
0
        public IActionResult Index()
        {
            if (StaticValues.LoginId == null)
            {
                StaticValues.LoginId = null;
                return(Redirect("Giris"));
            }

            tblKullanicilar tblKullanicilar = _ItblKullanicilarService.GetById(StaticValues.LoginId);
            ModelUser       user            = new ModelUser();

            user.name    = tblKullanicilar.Isim;
            user.surname = tblKullanicilar.Soyisim;
            return(View(user));
        }
Beispiel #28
0
        private void SelectModelUser(FieldValueModel fieldValueWhereModel)
        {
            ModelUser modeluser = bllUser.GetModel(fieldValueWhereModel);

            if (CheckData.IsObjectNull(modeluser))
            {
                Print.WriteLine("没有查到 id = {0} 的数据", fieldValueWhereModel.Value);
            }
            else
            {
                Print.WriteLine("id: " + modeluser.id);
                Print.WriteLine("RealName: " + modeluser.RealName);
                Print.WriteLine("Sex: " + modeluser.Sex.GetName());
            }
        }
        /// <summary>
        /// Renvoi l'état de la demande en cours sous la forme d'un objet State.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public State GetState(string username, string token)
        {
            State state = new State();

            if (AuthToken(username, token))
            {
                ModelUser userSystem = new ModelUser();

                switch (userSystem.getProgressUser(username))
                {
                case 0:
                    state.amount  = 0;
                    state.comment = "Ready to bruteforce";
                    break;

                case 10:
                    int amount = 10;

                    int res = userSystem.getPourcent(username);

                    amount += res;

                    state.amount  = amount;
                    state.comment = amount + "% progress";
                    break;

                case 100:
                    state.amount  = 100;
                    state.comment = "100% Finished";
                    break;

                default:

                    break;
                }

                state.resultExist = userSystem.isResultExist(username);


                return(state);
            }
            else
            {
                state.amount  = 0;
                state.comment = "Invalid token";
                return(state);
            }
        }
        public void ConvertJsonArrStringToListTest2()
        {
            string           user1        = @"{
  ""id"": 0,
  ""uuid"": ""5AAB1A5B-48C4-4698-9830-1A401F286D00"",
  ""username"": ""naruto"",
  ""password"": ""sasuke""
}";
            string           user2        = @"{
  ""id"": 1,
  ""uuid"": ""5AAB1A5B-48C4-4698-9830-1A401F286D01"",
  ""username"": ""goku"",
  ""password"": ""kakaroto""
}";
            string           user3        = @"{
  ""id"": 2,
  ""uuid"": ""5AAB1A5B-48C4-4698-9830-1A401F286D02"",
  ""username"": ""seiya"",
  ""password"": ""sahori""
}";
            string           jsonString   = $"[{user1},{ user2},{user3}]";
            List <ModelUser> actualResult = ConvertStringToList <ModelUser> .Convert(jsonString);

            ModelUser userOne = new ModelUser();

            userOne.id       = 0;
            userOne.uuid     = "5AAB1A5B-48C4-4698-9830-1A401F286D00";
            userOne.username = "******";
            userOne.password = "******";
            ModelUser userTwo = new ModelUser();

            userTwo.id       = 1;
            userTwo.uuid     = "5AAB1A5B-48C4-4698-9830-1A401F286D01";
            userTwo.username = "******";
            userTwo.password = "******";
            ModelUser userThree = new ModelUser();

            userThree.id       = 2;
            userThree.uuid     = "5AAB1A5B-48C4-4698-9830-1A401F286D02";
            userThree.username = "******";
            userThree.password = "******";
            List <ModelUser> expectedResult = new List <ModelUser>()
            {
                userOne, userTwo, userThree
            };

            CollectionAssert.AreEqual(expectedResult, actualResult);
        }
        internal static ModelUser GetUserImp(string userName, string SessionToken)
        {
            if (String.IsNullOrEmpty(userName))
            {
                throw new InvalidOperationException("One of the requested fields is empty.");
            }

            ModelSession session = CheckSessionImp(SessionToken);

            if (userName.ToLowerInvariant() == "everyone")
                throw new UnauthorizedAccessException("Access Denied");

            if (CheckUserRightsImp(session.User.Name, "ManageUsers"))
            {
                ModelUser mu = new ModelUser(userName);

                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist.");

                return mu;
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
        internal static ModelUser GetCurrentUserImp(string SessionToken)
        {
            ModelSession session = CheckSessionImp(SessionToken);

            if (session.User.Name.ToLowerInvariant() == "everyone")
                throw new UnauthorizedAccessException("Access Denied");

            ModelUser mu = new ModelUser(session.User.Name);

            // Reset sensitive data
            mu.PasswordHash = null;
            mu.SecretAnswer = null;

            // mu.Email = null;
            // mu.SecretQuestion = null;

            return mu;
        }
        public Services.Packages.Security.Security.ModelUserAccessControlListCollection GetModelUserACLs(ModelUser _ModelUser, string SessionToken)
        {
            _ModelUser.Reload();

            //*
            if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            /*
            if (!Services.Packages.Security.Security.Security.ModelUserAccessControlListSecureService.CheckAccessImp(_ModelUser.ModelUserACLs, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ModelUser.ModelUserACLs;
        }
 public ModelReEstablishResilientOpenRequest(ModelUser user)
     : base(0)
 {
     User = user;
 }
        public bool Exists(ModelUser _ModelUser, string SessionToken)
        {
            if (!ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");

            return _ModelUser.Exists;
        }
        internal static void UpdateUserImp(string userName, string password, string email, string secretQuestion,
            string secretAnswer, bool enabled, string SessionToken)
        {
            if (String.IsNullOrEmpty(userName) ||
                String.IsNullOrEmpty(password) ||
                String.IsNullOrEmpty(email) ||
                String.IsNullOrEmpty(secretQuestion) ||
                String.IsNullOrEmpty(secretAnswer))
            {
                throw new InvalidOperationException("One of the requested fields is empty.");
            }

            if (userName.ToLowerInvariant() == "everyone")
                throw new InvalidOperationException("Anonymous user update is not allowed.");

            ModelSession session = CheckSessionImp(SessionToken);

            if (CheckUserRightsImp(session.User.Name, "ManageUsers"))
            {
                ModelUser mu = new ModelUser(userName);

                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist.");

                mu.PasswordHash = Platform.Runtime.Security.Hash.ComputeHash(password, "SHA512", null);
                mu.Email = email;
                mu.SecretQuestion = secretQuestion;
                mu.SecretAnswer = secretAnswer;
                mu.Enabled = enabled;
                mu.Update();

                return;
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
        internal static void SetUserByObjectImp(ModelUser userObject, string SessionToken)
        {
            // This function actually does nothing
            // You have another function of setting user data; and password cannot be set this way (direct hash)

            ModelSession session = CheckSessionImp(SessionToken);

            if (userObject.Name.ToLowerInvariant() == "everyone")
                throw new UnauthorizedAccessException("Access Denied");

            if ( (session.User.Name == userObject.Name) ||
                CheckUserRightsImp(session.User.Name, "ManageUsers"))
            {
                ModelUser mu = new ModelUser(userObject.Name);

                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist.");

                // userObject.Update();

                return;
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
        public void CreateObject(ModelUser _ModelUser, string SessionToken)
        {
            ModelSession session = ModelUserSecureService.CheckSessionImp(SessionToken);

            if (!ModelUserSecureService.CheckUserRightsImp(session.User.Name, "Create " + typeof(ModelUser).FullName))
                throw new UnauthorizedAccessException("Access Denied");

            _ModelUser.Owner = session.User;
            _ModelUser.Create();
        }
        public Services.Packages.Log.ApplicationExceptionCollection GetApplicationExceptionOwning(ModelUser _ModelUser, string SessionToken)
        {
            _ModelUser.Reload();

            //*
            if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            /*
            if (!Services.Packages.Log.Security.ApplicationExceptionSecureService.CheckAccessImp(_ModelUser.ApplicationExceptionOwning, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ModelUser.ApplicationExceptionOwning;
        }
        public void CreateObjectFromOwner(ModelUser _ModelUser, Services.Packages.Security.ModelUser _Owner, string SessionToken)
        {
            ModelSession session = ModelUserSecureService.CheckSessionImp(SessionToken);

            //if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_Owner, SessionToken, "Create ModelUserOwning"))
            //	throw new UnauthorizedAccessException("Access Denied");

            _ModelUser.Reload();

            if (!_ModelUser.Exists && !Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_Owner, SessionToken, "Create ModelUserOwning"))
                throw new UnauthorizedAccessException("Access Denied");
            else if (_ModelUser.Exists && !ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Update"))
                throw new UnauthorizedAccessException("Access Denied");

            _ModelUser.Owner = session.User;
            _ModelUser.Owner = _Owner;
            _ModelUser.Create();
        }
        public void Delete(System.String __Name, string SessionToken)
        {
            ModelUser _ModelUser = new ModelUser(__Name);

            if (!ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Delete"))
                throw new UnauthorizedAccessException("Access Denied");

            ModelUser.DeleteModelUser(__Name);
        }
        public void SessionSetupRequest(
            ModelConnectionId connectionId,
            ModelSessionId sessionId,
            ModelSessionId previousSessionId,
            ModelSigned signed,
            ModelFlags flags,
            ModelUser user,
            ModelAllowReauthentication ReAuthentication)
        {
            ulong adapterSessionId;
            ulong adapterPreviousSessionId;
            Packet_Header_Flags_Values headerFlags;
            SESSION_SETUP_Request_Flags sessionSetupFlags;
            AccountCredential credential;

            #region sessionId
            if (sessionTable.ContainsKey(sessionId))
            {
                adapterSessionId = sessionTable[sessionId];

                // For sessionId is 0 which indicates session creation
                // assign a new one
                if (sessionId == ModelSessionId.ZeroSessionId)
                {
                    if (!sessionTable.ContainsKey(ModelSessionId.MainSessionId))
                    {
                        sessionId = ModelSessionId.MainSessionId;
                    }
                    else if (!sessionTable.ContainsKey(ModelSessionId.AlternativeSessionId))
                    {
                        sessionId = ModelSessionId.AlternativeSessionId;
                    }
                }
            }
            else
            {
                Random r = new Random();
                adapterSessionId = (ulong)r.Next(1, int.MaxValue);
            }

            Site.Log.Add(
                LogEntryKind.Debug,
                "ModelSessionId: {0}, AdapterSessionId: 0x{1:x8}",
                sessionId, adapterSessionId);

            #endregion

            #region previousSessionId
            if (sessionTable.ContainsKey(previousSessionId))
            {
                adapterPreviousSessionId = sessionTable[previousSessionId];
            }
            else
            {
                Random r = new Random();
                adapterPreviousSessionId = (ulong)r.Next(1, int.MaxValue);
            }

            Site.Log.Add(
                LogEntryKind.Debug,
                "ModelSessionId: {0}, adapterPreviousSessionId: 0x{1:x8}",
                sessionId, adapterPreviousSessionId);

            #endregion

            #region isSigned

            headerFlags = (signed == ModelSigned.SignFlagSet) ? Packet_Header_Flags_Values.FLAGS_SIGNED : Packet_Header_Flags_Values.NONE;

            #endregion

            #region flags

            switch (flags)
            {
                case ModelFlags.Binding:
                    {
                        sessionSetupFlags = SESSION_SETUP_Request_Flags.SESSION_FLAG_BINDING;
                        break;
                    }
                case ModelFlags.NotBinding:
                    {
                        sessionSetupFlags = SESSION_SETUP_Request_Flags.NONE;
                        break;
                    }
                default:
                    throw new ArgumentException("flags");
            }

            #endregion

            #region user

            switch (user)
            {
                case ModelUser.DefaultUser:
                    {
                        credential = testConfig.AccountCredential;
                        break;
                    }
                case ModelUser.DiffUser:
                    {
                        credential = testConfig.NonAdminAccountCredential;
                        break;
                    }
                default:
                    throw new ArgumentException("user");
            }

            #endregion

            #region MultipleChannel
            // Multiple Channel only takes affect when Connection.Dialect belongs to the SMB 3.x dialect family
            bool isMultipleChannelSupported = sessionMgmtConfig.IsMultiChannelCapable && ModelUtility.IsSmb3xFamily(connectionList[connectionId].Dialect);
            #endregion

            PrintCurrentSessionTable("Before SessionSetup Request");

            #region Send Request

            uint status;
            SESSION_SETUP_Response? sessionSetupResponse = null;
            string serverName = testConfig.SutComputerName;
            SecurityPackageType securityPackageType = testConfig.DefaultSecurityPackage;
            bool useServerGssToken = testConfig.UseServerGssToken;

            // Use desired explored sessionId
            ulong oldSessionId = connectionList[connectionId].SessionId;
            connectionList[connectionId].SessionId = adapterSessionId;

            // alternative connection and never session setup
            if (connectionId == ModelConnectionId.AlternativeConnection
                && sessionId == ModelSessionId.MainSessionId
                && connectionList[connectionId].SessionKey == null
                && connectionList.ContainsKey(ModelConnectionId.MainConnection))
            {
                connectionList[connectionId].GenerateCryptoKeys(testConfig.SendSignedRequest, false, connectionList[ModelConnectionId.MainConnection], true);
            }

            status = connectionList[connectionId].SessionSetup(
                headerFlags,
                sessionSetupFlags,
                adapterPreviousSessionId,
                securityPackageType,
                serverName,
                credential,
                useServerGssToken,
                isMultipleChannelSupported,
                (header, response) =>
                {
                    sessionSetupResponse = response;
                });

            if (status != Smb2Status.STATUS_SUCCESS
                && status != Smb2Status.STATUS_MORE_PROCESSING_REQUIRED)
            {
                // Restore original sessionId if request failed
                connectionList[connectionId].SessionId = oldSessionId;
            }

            #endregion

            // Insert session to session table
            if (!sessionTable.ContainsKey(sessionId)
                && (status == Smb2Status.STATUS_SUCCESS
                || status == Smb2Status.STATUS_MORE_PROCESSING_REQUIRED))
            {
                sessionTable.Add(sessionId, connectionList[connectionId].SessionId);
            }

            PrintCurrentSessionTable("After SessionSetup Request");

            SessionSetupResponse((ModelSmb2Status)status, connectionId, sessionMgmtConfig);
        }
        internal static void SetOwnerImp(Services.Packages.Log.ApplicationException _object, string userName, string SessionToken)
        {
            if (CheckAccessImp(_object, SessionToken, "ChangeAccess"))
            {
                ModelUser mu = new ModelUser(userName);
                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist in this context.");

                _object.Owner = mu;
                _object.Update();
                return;
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
 public void SetUserByObject(ModelUser userObject, string SessionToken)
 {
     this.Invoke("SetUserByObject", new object[] {userObject, SessionToken});
     return;
 }
        internal static void SetupImp()
        {
            ModelUser mu = new ModelUser("Everyone");

            if (!mu.Exists)
            {
                mu.PasswordHash = null;
                mu.Enabled = false;
                mu.Create();

                ModelUserRights ur = new ModelUserRights("owner", "Everyone");
                ur.Create();
            }

            Securable s = new Securable(typeof(ApplicationExceptionSecureService).FullName);
            if (!s.Exists)
            {
                // Default configuration - the safe way.
                s.TimeSessionIsIssued = 20;
                s.AllowAnonymousAccess = true;
                s.Enabled = true;
                s.GenerationPasswordLength = 6;
                s.AllowedIPFailures = 10;
                s.IPsMustBePreregistered = false;
                s.IPFailureTimeDenying = 60;
                s.DisableIPFiltering = false;
                s.SessionsPerIPAllowed = 2;
                s.Create();
            }
        }
        public Services.Packages.CustomerUserEntryCollection GetCustomerUserEntryOwning(ModelUser _ModelUser, string SessionToken)
        {
            _ModelUser.Reload();

            //*
            if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            /*
            if (!Services.Packages.Security.CustomerUserEntrySecureService.CheckAccessImp(_ModelUser.CustomerUserEntryOwning, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ModelUser.CustomerUserEntryOwning;
        }
        internal static void UpdateUserImp(string userName, string oldPassword, string email, string secretQuestion,
            string secretAnswer, string SessionToken)
        {
            if (String.IsNullOrEmpty(userName) ||
                String.IsNullOrEmpty(oldPassword) ||
                String.IsNullOrEmpty(email) ||
                String.IsNullOrEmpty(secretQuestion) ||
                String.IsNullOrEmpty(secretAnswer))
            {
                throw new InvalidOperationException("One of the requested fields is empty.");
            }

            ModelSession session = CheckSessionImp(SessionToken);

            if ( (session.User.Name == userName) ||
                CheckUserRightsImp(session.User.Name, "ManageUsers"))
            {
                ModelUser mu = new ModelUser(userName);

                string oldPasswordHash = Platform.Runtime.Security.Hash.ComputeHash(oldPassword, "SHA512", null);

                if (mu.PasswordHash != oldPasswordHash)
                    throw new InvalidOperationException("Old password is invalid.");

                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist.");

                mu.Email = email;
                mu.SecretQuestion = secretQuestion;
                mu.SecretAnswer = secretAnswer;
                mu.Update();

                return;
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
        public void DeleteObject(ModelUser _ModelUser, string SessionToken)
        {
            if (!ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Delete"))
                throw new UnauthorizedAccessException("Access Denied");

            _ModelUser.Delete();
        }
 public void SetUserByObject(ModelUser userObject, string SessionToken)
 {
     ApplicationExceptionSecureService.SetUserByObjectImp(userObject, SessionToken);
 }
 public void SetACLs(ModelUser _ModelUser, Services.Packages.Security.Security.ModelUserAccessControlListCollection _ACLs, string SessionToken)
 {
     this.Invoke("GetACLs", new object[] {_ModelUser,SessionToken});
     return;
 }
 public void SetUserByObject(ModelUser userObject, string SessionToken)
 {
     ApiKeySecureService.SetUserByObjectImp(userObject, SessionToken);
 }
        public static void ReEstablishResilientOpenRequest(ModelUser user)
        {
            Condition.IsTrue(Request == null);

            /// restrict parameter combination
            Condition.IfThen(Open == null, user == ModelUser.DefaultUser);

            Request = new ModelReEstablishResilientOpenRequest(user);
        }
 public Services.Packages.Security.Security.ModelUserAccessControlListCollection GetACLs(ModelUser _ModelUser, string SessionToken)
 {
     object[] results = this.Invoke("GetACLs", new object[] {_ModelUser,SessionToken});
     return ((Services.Packages.Security.Security.ModelUserAccessControlListCollection)(results[0]));
 }
 public void SetUserByObject(ModelUser userObject, string SessionToken)
 {
     CustomerUserEntrySecureService.SetUserByObjectImp(userObject, SessionToken);
 }
        internal static void ChangePasswordImp(string userName, string oldPassword, string newPassword, string SessionToken)
        {
            if (String.IsNullOrEmpty(userName) ||
                String.IsNullOrEmpty(oldPassword) ||
                String.IsNullOrEmpty(newPassword))
            {
                throw new InvalidOperationException("One of the requested fields is empty.");
            }

            if (userName.ToLowerInvariant() == "everyone")
                throw new InvalidOperationException("Anonymous user cannot have a password.");

            ModelSession session = CheckSessionImp(SessionToken);

            if ( (session.User.Name == userName) ||
                CheckUserRightsImp(session.User.Name, "ManageUsers"))
            {
                ModelUser mu = new ModelUser(userName);

                string oldPasswordHash = Platform.Runtime.Security.Hash.ComputeHash(oldPassword, "SHA512", null);

                if (mu.PasswordHash != oldPasswordHash)
                    throw new InvalidOperationException("Old password is invalid.");

                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist.");

                mu.PasswordHash = Platform.Runtime.Security.Hash.ComputeHash(newPassword, "SHA512", null);
                mu.Update();

                return;
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
        internal static string CreateRandomPasswordImp(string userName, string answer, string SessionToken)
        {
            // This must change - only anonymous can request new account
            // Must be sent in the email address <- We do not know the delivery of password here :-(

            if (String.IsNullOrEmpty(userName) ||
                String.IsNullOrEmpty(answer))
            {
                throw new InvalidOperationException("One of the requested fields is empty.");
            }

            if (userName.ToLowerInvariant() == "everyone")
                throw new InvalidOperationException("Anonymous user cannot have a password.");

            ModelSession session = CheckSessionImp(SessionToken);

            if (CheckUserRightsImp(session.User.Name, "ManageUsers")) // this should be removed - must be only everyone
            {
                ModelUser mu = new ModelUser(userName);

                if (!mu.Exists)
                    throw new InvalidOperationException("User does not exist.");

                if (mu.SecretAnswer.ToLowerInvariant() == answer.ToLowerInvariant())
                {
                    string password = GeneratePasswordImp();

                    mu.PasswordHash = Platform.Runtime.Security.Hash.ComputeHash(password, "SHA512", null);
                    mu.Update();

                    return password;
                }
            }

            throw new UnauthorizedAccessException("Access Denied");
        }
 public void SetRights(ModelUser _ModelUser, Services.Packages.Security.ModelUserRightsCollection _Rights, string SessionToken)
 {
     this.Invoke("GetRights", new object[] {_ModelUser,SessionToken});
     return;
 }
        internal static void CreateSessionImp(ref ModelSession ms, string userName, string password)
        {
            if (userName.ToLowerInvariant() == "everyone")
                throw new InvalidOperationException("Wrong API call for anonymous access.");

            Securable s = new Securable(typeof(ApplicationExceptionSecureService).FullName);

            ModelUser mu = new ModelUser(userName);
            if (!mu.Exists)
            {
                if (System.Web.HttpContext.Current != null)
                {
                    IPRegistered ipr = new IPRegistered(System.Web.HttpContext.Current.Request.UserHostAddress);
                    RegisterIPFailureImp(s, ipr);
                }

                throw new UnauthorizedAccessException("Access Denied");
            }

            if (!Platform.Runtime.Security.Hash.VerifyHash(password, "SHA512", mu.PasswordHash))
            {
                if (System.Web.HttpContext.Current != null)
                {
                    IPRegistered ipr = new IPRegistered(System.Web.HttpContext.Current.Request.UserHostAddress);
                    RegisterIPFailureImp(s, ipr);
                }

                throw new UnauthorizedAccessException("Access Denied");
            }

            if (!mu.Enabled && !ApplicationExceptionSecureService.CheckUserRightsImp(userName, "CannotBeDisabled"))
            {
                if (System.Web.HttpContext.Current != null)
                {
                    IPRegistered ipr = new IPRegistered(System.Web.HttpContext.Current.Request.UserHostAddress);
                    RegisterIPFailureImp(s, ipr);
                }

                throw new UnauthorizedAccessException("Access Denied"); // LoginDisabledException
            }

            ms.User = mu;
            ms.TimeIssued = DateTime.Now;
            ms.TimeIssuedFor = s.TimeSessionIsIssued;
            ms.Create();
        }
 public ModelSessionSetupRequest(
     ModelConnectionId connectionId,
     ModelSessionId sessionId,
     ModelSessionId previousSessionId,
     bool isSigned,
     ModelFlags flags,
     ModelUser user
     )
     : base(0)
 {
     this.connectionId = connectionId;
     this.sessionId = sessionId;
     this.previousSessionId = previousSessionId;
     this.isSigned = isSigned;
     this.flags = flags;
     this.user = user;
 }
        public Services.Packages.Security.ModelUser GetOwner(ModelUser _ModelUser, string SessionToken)
        {
            _ModelUser.Reload();

            //*
            if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_ModelUser, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            //*
            if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_ModelUser.Owner, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ModelUser.Owner;
        }