예제 #1
0
        public ActionResult Login(Login_Data LD)
        {
            if (ModelState.IsValid)
            {

                Service1Client client = new Service1Client();
                LoginData auth = new LoginData();
                auth.Email = LD.Email;
                auth.Password = LD.Password;
                if (client.AuthenticateUser(auth))
                {
                    Session["Email"] = LD.Email;
                    return index();
                }
                else
                {
                    string error_message = "Wrong Email or Password";
                    ViewBag.LoginError = error_message;
                    return View();
                }

            }
            else
            {
                return View();
            }
        }
예제 #2
0
        private async void LogIn()
        {
            var email = this.LogUsername.Text;
            var password = this.LogPassword.Password;

            var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("username", email),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("confirmPassword", password),
                    new KeyValuePair<string, string>("grant_type", "password")
                });

            var response = await this._httpClient.PostAsync(Endpoint.Log, content);
            var loginDataPlus = await response.Content.ReadAsAsync<LoginData>();
            this._loginData = loginDataPlus;

            if (response.IsSuccessStatusCode)
            {
                var placement = this.GetPlacement();
                ModesWindow roomWindow = new ModesWindow(_loginData, placement);
                roomWindow.Show();
                this.Close();
            }
            else
            {
                MessageBox.Show(await response.Content.ReadAsStringAsync());
                this.ButtonLog.IsEnabled = true;
                this.RegisterButton.IsEnabled = true;
                this.LogUsername.IsEnabled = true;
                this.LogPassword.IsEnabled = true;
            }
        }
예제 #3
0
        private static LoginData ParseData(string data)
        {
            string strRegex = @"\{.*\}";
            RegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
            Regex myRegex = new Regex(strRegex, myRegexOptions);

            var loginData=new LoginData();
            foreach (Match myMatch in myRegex.Matches(data))
            {
                if (myMatch.Success)
                {
                    var singles=myMatch.ToString().Substring(1, myMatch.Length - 2).Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
                    foreach (var single in singles)
                    {
                        var keyValuePair=single.Replace("\"","").Split(new char[] {':'}, StringSplitOptions.None);
                        switch (keyValuePair[0])
                        {
                            case "name":
                                loginData.Username = keyValuePair[1];
                                break;
                            case "password":
                                loginData.PasswordHash = keyValuePair[1];
                                break;
                            case "world_id":
                                loginData.WorldId = keyValuePair[1];
                                break;
                        }
                    }
                }
            }
            return loginData;
        }
예제 #4
0
        public static void InsertLogin(Guid OrganizationId, int DepartmentId, LoginData ld)
        {
            if (string.IsNullOrEmpty(ld.email)) return;
            ld.email=ld.email.ToLower();
            lib.bwa.bigWebDesk.LinqBll.Context.MutiBaseDataContext dc = new lib.bwa.bigWebDesk.LinqBll.Context.MutiBaseDataContext(OrganizationId, DepartmentId);
            var l = (from ll in dc.Tbl_Logins where ll.Email.ToLower() == ld.email select ll).FirstOrNull();
            if (l == null)
            {
                l = new Context.Tbl_Logins();
                FillLogin(ld, l);
                dc.Tbl_Logins.InsertOnSubmit(l);
                dc.SubmitChanges();
            }
            else
            {
                FillLogin(ld, l);
            }
            var j = (from jj in dc.Tbl_LoginCompanyJunc where jj.Company_id==DepartmentId && jj.Login_id==l.Id select jj).FirstOrNull();
            if (j == null)
            {
                j = new Context.Tbl_LoginCompanyJunc();
                j.Company_id = DepartmentId;
                j.Login_id = l.Id;
                FillJunk(ld, j);
                dc.Tbl_LoginCompanyJunc.InsertOnSubmit(j);
            }
            else
            {
                FillJunk(ld, j);
            }

            dc.SubmitChanges();
        }
        public async Task Login(string username, string password)
        {
            using (var httpClient = new HttpClient())
            {
                this.CurrentResponse = null;

                var bodyData = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("Username", username),
                    new KeyValuePair<string, string>("Password", password),
                    new KeyValuePair<string, string>("grant_type", "password")
                });

                var response = await httpClient.PostAsync(loginEndPoint, bodyData);

                if (response.IsSuccessStatusCode)
                {
                    string data = await response.Content.ReadAsStringAsync();

                    this.loginData = JsonConvert.DeserializeObject<LoginData>(data);
                    this.IsLogged = true;
                }

                this.CurrentResponse = response;
            }
        }
        public static LoginData Read()
        {
            LoginData result = null;

            string path = Path.Combine(FileLocations.TrakHound, SERVER_CREDENTIALS_FILENAME);
            if (File.Exists(path))
            {
                try
                {
                    var xml = new XmlDocument();
                    xml.Load(path);

                    string username = XML_Functions.GetInnerText(xml, "Username");
                    string token = XML_Functions.GetInnerText(xml, "Token");

                    if (username != null && token != null)
                    {
                        result = new LoginData();
                        result.Username = username;
                        result.Token = token;
                    }
                }
                catch (Exception ex) { Logger.Log("Exception :: " + ex.Message); }
            }

            return result;
        }
예제 #7
0
        public MainWindow()
        {
            InitializeComponent();

            /*System.Diagnostics.Trace.Listeners.Add(
                new System.Diagnostics.ConsoleTraceListener());*/

            this.commentClient.CommentReceived += (sender, e) =>
                Console.Write(".");
            this.commentClient.CommentReceived +=
                commentClient_CommentReceived;

            this.commentClient.ConnectedRoom += (sender, e) =>
                Log.Info("Connected to {0}.", e.RoomIndex);
            this.commentClient.DisconnectedRoom += (sender, e) =>
                Log.Info("Disconnected from {0}.", e.RoomIndex);

            var loginData = new LoginData()
            {
                LoginMethod = LoginMethod.WithBrowser,
                BrowserType = BrowserType.GoogleChrome,
            };
            this.nicoClient.LoginAsync(loginData);

            DataContext = this;

            this.timer = new Timer(TimeCallback, null, 1000, 1000);
        }
예제 #8
0
 protected override ResourceResponse OnRequest(ResourceRequest request)
 {
     // try to recover login data
     if (request.Count>0 && request.Method == "POST" && request.Url.AbsoluteUri.ToLower().EndsWith(LoginUrl))
     {
         _lastLoginData = ParseData(Uri.UnescapeDataString(request[0].Bytes));
     }
     return base.OnRequest(request);
 }
예제 #9
0
        public RoomWindow(LoginData loginData, string placement)
        {
            InitializeComponent();
            this.loginData = loginData;
            this._placement = placement;

            UpdateRooms();
            HubConnectAsync();
        }
예제 #10
0
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

        //Response.Write("<script>alert('3');</script>");
        bool LoginResult;
        LoginData seesionData = new LoginData();
        LoginResult = seesionData.CheckByUserID(TextBox1.Text, TextBox2.Text);
        //Session["UserID"] = TextBox1.Text;
        //Response.Write("<script>alert('1');</script>");
        if (LoginResult)
        {
            //Response.Write("<script>alert('2');</script>");
            Response.Redirect("kilnB.aspx");
            Response.Flush();
            Response.End();
        }
        if (LoginResult==false)
        {
            //Response.Redirect("kilnB.aspx");
            Response.Write("<script>alert('谨防盗链,谢谢合作!');</script>");
            //Response.Write(Url);
            Response.Write("<script language='javascript'>window.close();</script>");
            Response.Redirect("LoginTest.aspx");
            Response.Flush();
            Response.End();
        }
        //Session["Role"] = TextBox2.Text;
        //Data.CheckByUserID(TextBox1.Text);

        //if (seesionData.Login_Region.Capacity > 0)
        //{
        //    for (int i = 0; i < seesionData.Login_Region.Count; i++)
        //    {
        //        Session["Region"] = Session["Region"] + seesionData.Login_Region[i].ToString().Trim() + ":";
        //    }
        //}
        //else
        //{
        //    Response.Redirect("LoginTest3.aspx");
        //}

        //if (seesionData.Attribute.Capacity > 0)
        //{
        //    for (int i = 0; i < seesionData.Attribute.Count; i++)
        //    {
        //        Session["Attribute"] = Session["Attribute"] + seesionData.Attribute[i].ToString().Trim() + ":";
        //    }
        //}
        //else
        //{
        //    Response.Redirect("LoginTest3.aspx");
        //}


        //Response.Redirect("OutLine_Anhui.aspx");
    }
예제 #11
0
        /// <summary>
        /// Adds a user to the users table if the requested username doesn't exist.
        /// </summary>
        /// <param name="sentUser">The user to register in the database.</param>
        /// <returns>UserAddResult giving feedback on the process.</returns>
        public UserAddResult addUser(LoginData sentUser)
        {
            //GlobalEnumerations.UserValidationResult result;
            UserAuthenticationResult preCheck;
            preCheck = validateUser(sentUser);

            //If validateUser returns 1, user is not in database
            if (preCheck == UserAuthenticationResult.InvalidUser)
            {
                using (SqlConnection connection = new SqlConnection(sqlStrBldr.ConnectionString))
                {
                    SqlCommand command = new SqlCommand("addMusicUser", connection);
                    command.CommandType = CommandType.StoredProcedure;

                    SqlParameter userName = new SqlParameter("@uname", SqlDbType.VarChar);
                    userName.Direction = ParameterDirection.Input;
                    userName.Value = sentUser.username;
                    userName.Size = 50;
                    command.Parameters.Add(userName);

                    SqlParameter password = new SqlParameter("@passw", SqlDbType.VarChar);
                    password.Direction = ParameterDirection.Input;
                    password.Value = sentUser.password;
                    password.Size = 80;
                    command.Parameters.Add(password);

                    command.Connection.Open();
                    command.ExecuteNonQuery();
                }

                // Check user again  to make sure things went well.
                // This is a hack because the database doesn't give you feedback on addMusicUser...
                UserAddResult result = UserAddResult.UnknownResult;
                UserAuthenticationResult postCheck;
                postCheck = validateUser(sentUser);
                switch (postCheck)
                {
                    case UserAuthenticationResult.UnknownResult:
                        break;
                    case UserAuthenticationResult.Success:
                        result = UserAddResult.Success;
                        break;
                    case UserAuthenticationResult.InvalidUser:
                        break;
                    case UserAuthenticationResult.InvalidPassword:
                        break;
                    default:
                        break;
                }
                return result;
            }
            else
            {
                return UserAddResult.AlreadyExists;
            }
        }
예제 #12
0
        public GameWindow(LoginData loginData, string placement, GameMode gameMode, OnlineGame gameData = null)
        {
            InitializeComponent();
            this._placement = placement;
            this.gameMode = gameMode;
            this.loginData = loginData;
            if (gameMode == GameMode.Online)
            {
                this.gameData = gameData;

                this.LabelFirstPlayer.Content = gameData.FirstPlayerName;
                this.LabelSecondPlayer.Content = gameData.SecondPlayerName;
                this.LabelGameState.Content = gameData.GameState;
                this.LabelGameName.Content = gameData.Name;

                HubConnectAsync();
            }
            else if (gameMode == GameMode.Multiplayer)
            {
                this.LabelFirstPlayer.Content = this.loginData.UserName;
                this.LabelGameName.Content = "Multiplayer";
                this.LabelSecondPlayer.Content = "Other guy";
                this.gameData = new MultiPlayerGame()
                {
                    FirstPlayerName = this.loginData.UserName,
                    SecondPlayerName = "Other guy",
                    EnumGameState = GameState.FirstPlayer,
                    Field = new String('0', 9),
                    Name = "Multiplayer"
                };
            }
            else if (gameMode == GameMode.Singleplayer)
            {
                this.LabelFirstPlayer.Content = this.loginData.UserName;
                this.LabelGameName.Content = "Singleplayer";
                this.LabelSecondPlayer.Content = "Bot";
                this.gameData = new SinglePlayerGame()
                {
                    FirstPlayerName = this.loginData.UserName,
                    EnumGameState = GameState.FirstPlayer,
                    Field = new String('0', 9),
                    Name = "Singleplayer"
                };
            }
        }
예제 #13
0
    public void sendLoginData(LoginData loginData, MethodReferenceWithResponse responseHandler)
    {
        Response response = (Response)gameObject.AddComponent<Response>();

        Debug.Log("Sending login request to Kii Cloud");

        try {
            user = KiiUser.LogIn(loginData.username, loginData.password);
            response.error = false;
            response.message = "";
            Debug.Log("User log-in successful");
        }
        catch(Exception e){
            response.error = true;
            response.message = e.Message;
            Debug.Log(e.Message);
        }

        // Calling response handler
        responseHandler(response);
    }
예제 #14
0
 public void sendLoginData(LoginData loginData, MethodReferenceWithResponse responseHandler)
 {
     Response response = (Response)gameObject.AddComponent<Response>();
     bool inHandler = true;
     Debug.Log("Attempting login...");
     KiiUser.LogIn(loginData.username, loginData.password, (KiiUser user, Exception e) => {
         if (e != null) {
             response.error = true;
             response.message = "Login failed: " + e.ToString();
             inHandler = false;
             Debug.Log("Login failed: " + e.ToString());
         } else {
             response.error = false;
             response.message = "";
             inHandler = false;
             Debug.Log("Login successful");
         }
     });
     // Calling response handler
     while(inHandler) {}
     responseHandler(response);
 }
        public bool LogIn(LoginData loginData)
        {
            if (string.IsNullOrEmpty(loginData.DownloadSource))
            {
                return(false);
            }

            SelectedDownloadSource = DownloadSources.First(s => s.Name == loginData.DownloadSource);
            var downloaderType = Type.GetType(SelectedDownloadSource.FullyQualifiedHandlerName);

            if (downloaderType == null)
            {
                throw new NotImplementedException($"Download manager of type \"{SelectedDownloadSource.FullyQualifiedHandlerName}\" could not be found.");
            }

            _mapDownloader = (DownloadManager)Activator.CreateInstance(downloaderType, DownloadDirectory, SelectedDownloadSource.DownloadThreads, SelectedDownloadSource.DownloadsPerMinute, SelectedDownloadSource.DownloadsPerHour);
            _mapDownloader.ProgressUpdated += MapDownloaderOnProgressUpdated;
            if (SelectedDownloadSource.RequiresLogin)
            {
                return(IsLoggedIn = loginData.IsValid() && _mapDownloader.Login(loginData));
            }

            return(IsLoggedIn = true);
        }
예제 #16
0
        // POST api/values
        public object Post(LoginData loginData)
        {
            // TODO: key應該移至config
            var secret = "wellwindJtwDemo";

            // TODO: 真實世界檢查帳號密碼
            if (loginData.Username == "wellwind" && loginData.Password == "1234")
            {
                var payload = new JwtAuthObject()
                {
                    Id = "wellwind"
                };

                return(new
                {
                    Result = true,
                    token = Jose.JWT.Encode(payload, Encoding.UTF8.GetBytes(secret), JwsAlgorithm.HS256)
                });
            }
            else
            {
                throw new UnauthorizedAccessException("帳號密碼錯誤");
            }
        }
예제 #17
0
        public ActionResult Login(LoginData loginData)
        {
            if (ModelState.IsValid)
            {
                User user = _userManager.Get(loginData.UserName);
                if (user != null && user.IsPasswordOk(loginData.Password))
                {
                    _sessionManager.AddUserToSession(user);

                    if (!string.IsNullOrEmpty(loginData.ReturnPage))
                    {
                        return(Redirect(loginData.ReturnPage));
                    }
                    else
                    {
                        return(Redirect("/Welcome.html"));
                    }
                }

                ViewData["Message"] = Resources.AppMessages.bad_user_or_password;
                return(View("Login"));
            }
            return(View(loginData));
        }
예제 #18
0
        public void DownvotePost()
        {
            // Arrange
            LoginData loginData = CreatePost();

            PostController postController = new PostController();
            var            getPostResult  = postController.Get(loginData.sessionkey, 1).Result;
            var            createdPost    = ((getPostResult as OkObjectResult).Value as ComplexAnswer).data as Post;

            VoteController voteController = new VoteController();

            // Act
            var actionResult = voteController.Post(loginData.sessionkey, Mocks.downvote).Result;

            // Assert
            var actual = ((actionResult as OkObjectResult).Value as ComplexAnswer).data as Post;

            Assert.Equal(Mocks.createPosts[0].title, actual.title);
            Assert.Equal(Mocks.createPosts[0].description, actual.description);
            Assert.Equal(Mocks.createPosts[0].path, actual.path);
            Assert.Equal(0, actual.upvotes);
            Assert.Equal(1, actual.downvotes);
            Assert.Equal(-1, actual.yourvote);
        }
예제 #19
0
        /*public IActionResult About()
         * {
         *  ViewData["Message"] = "Your application description page.";
         *
         *  return View();
         * }*/

        public async Task <ActionResult> About()
        {
            //Simulate test user data and login timestamp
            var userId           = "12345";
            var currentLoginTime = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss");

            //Save non identifying data to Firebase
            var currentUserLogin = new LoginData()
            {
                TimestampUtc = currentLoginTime
            };
            var firebaseClient = new FirebaseClient("https://netkapifirebase.firebaseio.com");
            var result         = await firebaseClient
                                 .Child("Users/" + userId + "/Logins")
                                 .PostAsync(currentUserLogin);

            //Retrieve data from Firebase
            var dbLogins = await firebaseClient
                           .Child("Users")
                           .Child(userId)
                           .Child("Logins")
                           .OnceAsync <LoginData>();

            var timestampList = new List <DateTime>();

            //Convert JSON data to original datatype
            foreach (var login in dbLogins)
            {
                timestampList.Add(Convert.ToDateTime(login.Object.TimestampUtc).ToLocalTime());
            }

            //Pass data to the view
            ViewBag.CurrentUser = userId;
            ViewBag.Logins      = timestampList.OrderByDescending(x => x);
            return(View());
        }
예제 #20
0
        public static async Task <User> ValidateRegisterAsync(Tourist tourist, LoginData loginData)
        {
            var firstName  = tourist.FirstName.ToLower();
            var secondName = tourist.SecondName.ToLower();
            var db         = ContextHelper.GetContext();
            var t          = await db.Tourists.FirstOrDefaultAsync(x => x.FirstName.ToLower().Equals(firstName) && x.SecondName.ToLower().Equals(secondName));

            if (t != null)
            {
                throw new Exception("Tourist with such data is already in the database!");
            }
            else
            {
                UserRole userRole = db.UserRoles.FirstOrDefault(x => x.Name.Equals("User"));
                User     u        = new User()
                {
                    LoginData = loginData, UserRole = userRole
                };
                tourist.User = u;
                db.Tourists.Add(tourist);
                db.SaveChanges();
                return(u);
            }
        }
예제 #21
0
        public LoginResult Login(LoginData model)
        {
            var result       = new LoginResult();
            var signinResult = _signinManager.PasswordSignInAsync(model.Email, model.Password, false, false).Result;

            if (signinResult.Succeeded)
            {
                var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);

                result.Token   = GenerateJwtToken(model.Email, appUser);
                result.Success = true;
                AppUser user = GetUserData(appUser.Id);
                result.User = new UserModel
                {
                    Email     = user.Email,
                    Campaigns = _mapper.Map <ICollection <Campaign>, List <CampaignModel> >(user.Campaigns)
                };
            }
            else if (!signinResult.IsLockedOut && !signinResult.RequiresTwoFactor && !signinResult.IsNotAllowed)
            {
                result.Errors = new[]
                {
                    new ApiError
                    {
                        Field     = _errors["InvalidPassword"].Field,
                        ErrorCode = _errors["InvalidPassword"].ErrorCode
                    }
                };
            }
            else
            {
                throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
            }

            return(result);
        }
        public async Task <IActionResult> AddOrEditLoginData(LoginDataViewModel loginDataView, string Id)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("Views/Forms/AddOrEditLoginData.cshtml", loginDataView));
            }
            var loginData = new LoginData
            {
                Id          = 0,
                Name        = loginDataView.Name,
                Login       = loginDataView.Login,
                Email       = loginDataView.Email,
                Website     = loginDataView.Website,
                Compromised = PwnedPasswords.IsPasswordPwnedAsync(loginDataView.Password,
                                                                  new CancellationToken(), null).Result == -1 ? 0 : 1,
                Password = _encryptionService.Encrypt(AuthUserId,
                                                      loginDataView.Password)
            };

            loginData.UserId = Int32.Parse(AuthUserId);
            if (!Id.Equals("0"))
            {
                loginData.Id = Int32.Parse(dataProtectionHelper.Decrypt(Id, _config["QueryStringsEncryptions"]));
            }
            if (loginData.Id == 0)
            {
                await _apiService.CreateUpdateData <LoginData>(loginData);
            }
            else
            {
                await _apiService.CreateUpdateData <LoginData>(loginData, loginData.Id);
            }
            ClearCache();
            OnDataEdit(loginData);
            return(RedirectToAction("List"));
        }
예제 #23
0
    // Use this for initialization
    void Start()
    {
        Screen.orientation = ScreenOrientation.PortraitUpsideDown;
        temp   = LoginInfo.Instance().mylogindata;
        playGO = playerScroecPanelGO.transform.Find("forbackbutton").GetComponent <Button>();
        playGO.onClick.AddListener(playGO.GetComponent <showWindow>().OnClick);

        liSpGO = liScroecPanelGO.transform.Find("forbackbutton").GetComponent <Button>();
        liSpGO.onClick.AddListener(liSpGO.GetComponent <showWindow>().OnClick);

        chPDGO = changepasswordGO.transform.Find("forbackbutton").GetComponent <Button>();
        chPDGO.onClick.AddListener(chPDGO.GetComponent <showWindow>().OnClick);

        loadtologin = bettpenal.transform.Find("Image").Find("quitButton").GetComponent <Button>();
        closebet    = bettpenal.transform.Find("Image").Find("closeButton").GetComponent <Button>();

        closebet.onClick.AddListener(closebet.GetComponent <showWindow>().OnClick);
        loadtologin.onClick.AddListener(torlogin);

        room1to1.transform.GetComponent <Button>().onClick.AddListener(toroom);
        room1to10.transform.GetComponent <Button>().onClick.AddListener(toroom2);
        setmoneyandname();

        gamelistinfo = new List <userinfo>();
        Pagecout     = 0;
        for (int i = 0; i < 27; i++)
        {
            userinfo temp = new userinfo();
            temp.username = "******" + i;
            temp.time     = "2017/1/1/" + i;
            temp.winbet   = "win:" + i;
            gamelistinfo.Add(temp);
        }

        //StartCoroutine(hallalive());
    }
        public IHttpActionResult LoginOrganization(LoginData logindata)
        {
            // Does the Organization data exist?
            List <BepOrganization> orglist;

            if (logindata.Phone != null)
            {
                orglist = context.BepOrganizations.Where(x => (x.Phone == logindata.Phone && x.Password == logindata.Password)).ToList();
            }
            else
            {
                orglist = context.BepOrganizations.Where(x => (x.Email == logindata.Email && x.Password == logindata.Password)).ToList();
            }
            int count = orglist.Count;

            if (count == 1)
            {
                return(Ok(Mapper.Map <BepOrganizationDTO>(orglist[0])));
            }
            else
            {
                return(BadRequest("Invalid login credentials!"));
            }
        }
예제 #25
0
    //로그인
    public LoginData GetValue(string id)
    {
        var       tb   = loginTb.GetTable();
        LoginData data = null;

        LoginIdx = 0;

        if (tb == null)
        {
            Debug.LogError("TableMngLoginDataError");
            return(null);
        }

        foreach (var val in tb)
        {
            if (val.Value.strName == id)
            {
                data = val.Value;
            }
            ++LoginIdx;
        }

        return(data);
    }
예제 #26
0
        public async Task <ApiResult <LoginResponse> > SaveAsync(Login login)
        {
            ApiResult <LoginResponse> response = null;
            var request = new LoginRequest(login);

            if (login.Id == null)
            {
                response = await _loginApiRepository.PostAsync(request);
            }
            else
            {
                response = await _loginApiRepository.PutAsync(login.Id, request);
            }

            if (response.Succeeded)
            {
                var data = new LoginData(response.Result, _authService.UserId);
                if (login.Id == null)
                {
                    await _loginRepository.InsertAsync(data);

                    login.Id = data.Id;
                }
                else
                {
                    await _loginRepository.UpdateAsync(data);
                }
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.Forbidden ||
                     response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                MessagingCenter.Send(Application.Current, "Logout", (string)null);
            }

            return(response);
        }
예제 #27
0
        public LoginResult PostLogin([FromBody] LoginData data)
        {
            LoginResult retVal = new LoginResult()
            {
                Success = false
            };

            using (EmployeesManagerEntities db = new EmployeesManagerEntities())
            {
                User user = db.User.FirstOrDefault(u => u.login == data.UserLogin);
                if (user != null)
                {
                    string hashFromTypedPassword = MD5Helper.Hash(data.UserPassword + user.passwordSalt);
                    if (user.passwordHash.ToLower() == hashFromTypedPassword.ToLower())
                    {
                        //TODO: implementar login
                        retVal.Success  = true;
                        retVal.UserName = user.login;
                        retVal.UserId   = user.id;
                    }
                }
            }
            return(retVal);
        }
예제 #28
0
        // GET: Login

        public ActionResult Index()
        {
#if DEBUG
            LoginData.CreateCookie("VP");
#endif

            var user = LoginData.GetUser();

            if (string.IsNullOrEmpty(user.Login))
            {
                return(RedirectToAction("Logar", "Login"));
            }

            AutoLogin(user);
            //return RedirectToAction("Index", "Home");

            //if (User.Identity.IsAuthenticated)
            //{
            Session["USERMODEL"] = user;
            return(RedirectToAction("Index", "Home"));
            //}

            //return View(new LoginModel());
        }
예제 #29
0
        public void Login(string user, string pass, pnCallback cb = null)
        {
            // Logging in is a two step process:
            // First, we must register with the server and get a server challenge
            // Then, we actually login.
            // We will make it easy on the programmer and silently register the client :)
            if (fSrvChg.HasValue || !user.Contains('@'))
                ILogin(user, pass, cb);
            else {
                // Unfortunately, RegisterRequests have no TransID, so we can't save our
                // params using the normal way... So, we must use this ugly HACK.
                fEvilTemporaryHack = new LoginData(user, pass, cb);

                // Back to the regularly scheduled programming
                pnCli2Auth_ClientRegisterRequest req = new pnCli2Auth_ClientRegisterRequest();
                req.fBuildID = fConnHdr.fBuildID;
                lock (fStream) req.Send(fStream);
            }
        }
예제 #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            LoginData login = LoginUser.LogedUser(this);

            if (login == null)
            {
                Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "login2/", false);
            }
            else
            {
                html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"" + Session["ApplicationVirtualPath"] + "login2/changepassword/\"><div class=\"login_form\">";

                if (Request.HttpMethod == "POST")
                {
                    try
                    {
                        String password  = Tools.Tool.TrataInjection(Request["password"]);
                        String password2 = Request["password2"];
                        if ((password == null) || (password == ""))
                        {
                            error = MessageResource.GetMessage("type_password");
                        }
                        else if ((password2 == null) || (password2 == ""))
                        {
                            error = MessageResource.GetMessage("type_password_confirm");
                        }
                        else if (password != password2)
                        {
                            error = MessageResource.GetMessage("password_not_equal");
                        }
                        else
                        {
                            Int64 enterpriseId = 0;
                            if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null))
                            {
                                enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id;
                            }

                            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            {
                                UserPasswordStrength       usrCheck = new UserPasswordStrength(db.Connection, login.Id);
                                UserPasswordStrengthResult check    = usrCheck.CheckPassword(password);
                                if (check.HasError)
                                {
                                    if (check.NameError)
                                    {
                                        error = MessageResource.GetMessage("password_name_part");
                                    }
                                    else
                                    {
                                        String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("uppercase") + ":  " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("symbols") + ":  " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail"));

                                        error = MessageResource.GetMessage("password_complexity") + ": <br />" + txt;
                                    }
                                }
                                else
                                {
                                    DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id);
                                    if ((c != null) && (c.Rows.Count > 0))
                                    {
                                        //Verifica a senha atual
                                        using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId))
                                            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(c.Rows[0]["password"].ToString())))
                                            {
                                                using (SqlConnection conn1 = IAMDatabase.GetWebConnection())
                                                    using (EnterpriseKeyConfig sk1 = new EnterpriseKeyConfig(conn1, enterpriseId))
                                                        using (CryptApi cApi1 = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password)))
                                                        {
                                                            DbParameterCollection pPar = new DbParameterCollection();
                                                            String b64 = Convert.ToBase64String(cApi1.ToBytes());
                                                            pPar.Add("@password", typeof(String), b64.Length).Value = b64;

                                                            db.ExecuteNonQuery("update entity set password = @password, change_password = getdate() , recovery_code = null, must_change_password = 0 where id = " + login.Id, CommandType.Text, pPar);
                                                        }

                                                db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, login.Id, 0, "Password changed through logged user", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");

                                                //Cria o pacote com os dados atualizados deste usuário
                                                //Este processo visa agiliar a aplicação das informações pelos plugins
                                                db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + login.Id + ")", CommandType.Text, null);

                                                //Mata a sessão
                                                //Session.Abandon();

                                                Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "login2/passwordchanged/", false);
                                            }
                                    }
                                    else
                                    {
                                        error = MessageResource.GetMessage("internal_error");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.Tool.notifyException(ex);
                        error = MessageResource.GetMessage("internal_error") + ": " + ex.Message;
                    }
                }

                html += "    <ul>";
                html += "        <li>";
                html += "            <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("password_expired_text") + "</p>";
                html += "        </li>";
                html += "    <li>";
                html += "        <span class=\"inputWrap\">";
                html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"cas.passwordStrength('#password');\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                html += "        </span>";
                html += "    </li>";
                html += "    <li>";
                html += "        <span class=\"inputWrap\">";
                html += "			<input type=\"password\" id=\"password2\" tabindex=\"1\" name=\"password2\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password_confirm") + "\" onfocus=\"$('#password2').addClass('focus');\" onblur=\"$('#password2').removeClass('focus');\" />";
                html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password2').focus();\"></span>";
                html += "        </span>";
                html += "    </li>";
                html += "    <li>";
                html += "        <div id=\"passwordStrength\"><span>" + MessageResource.GetMessage("password_strength") + ": " + MessageResource.GetMessage("unknow") + "</span><div class=\"bar\"></div></div>";
                html += "    </li>";

                if (error != "")
                {
                    html += "        <li><div class=\"error-box\">" + error + "</div>";
                }

                html += "        <li>";
                html += "           <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "logout/\">" + MessageResource.GetMessage("cancel") + "</a> </span>";
                html += "           <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>";
                html += "        </li>";
                html += "    </ul>";


                html += "</div></form>";

                holderContent.Controls.Add(new LiteralControl(html));
            }
        }
예제 #31
0
        public async Task startPostingAsync(bool latest, bool popular, int delay)
        {
            int randomNum    = getRandomNum(latest, popular);
            var mainInstance = Main.getInstance();
            var status       = mainInstance.getStatusLabel();
            var comboBox     = mainInstance.getPwdComboBox();

            while (true)
            {
                status.Text = "기사 정보를 수집 중입니다.";
                List <LoginInfo> loginInfos = LoginData.getInstance().getData();

                Article targetArticle;

                var maxIndex = comboBox.Items.Count;
                comboBox.SelectedIndex = 0;
                foreach (var item in loginInfos.Select((value, i) => new { i, value }))
                {
                    if (_cancel)
                    {
                        status.Text = "중지";
                        _cancel     = false;
                        return;
                    }
                    while (true)
                    {
                        try
                        {
                            await TwitterProfileScraper.getUserProfile(item.value);

                            break;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                            continue;
                        }
                    }
                    try
                    {
                        while (true)
                        {
                            targetArticle = await _scraper[randomNum].getArticleInfoAsync();
                            var title = targetArticle.getTitle();

                            var filter =
                                from data in _articleHistory
                                where data.Equals(title)
                                select data;

                            if (!filter.Any())
                            {
                                _articleHistory.Add(title);
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    if (_cancel)
                    {
                        status.Text = "중지";
                        _cancel     = false;
                        return;
                    }
                    var index     = item.i;
                    var loginInfo = item.value;

                    status.Text = "트위터에 기사를 포스팅 중입니다.";
                    try
                    {
                        await TwitterPoster.twitterAsync(loginInfo, targetArticle);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                        if (index + 1 >= maxIndex)
                        {
                            await Task.Delay(delay * 1000);

                            break;
                        }
                        continue;
                    }

                    status.Text = "다음 계정 대기 중";
                    if (index + 1 >= maxIndex)
                    {
                        await Task.Delay(delay * 1000);

                        break;
                    }
                    comboBox.SelectedIndex = index + 1;
                    await Task.Delay(delay * 1000);
                }
            }
        }
예제 #32
0
	public async Task<IActionResult> Login(LoginData loginData, string returnUrl)
	{
		await SignIn(loginData);
		return Redirect(returnUrl);
	}
예제 #33
0
        public ActionResult Login(CatUsuario usuario)
        {
            LoginData objData        = new LoginData();
            string    empleado       = usuario.NoEmpleado.ToString();
            string    actionName     = "";
            string    nameController = "";

            if (ModelState.IsValid == false)
            {
                if (empleado != "0" && usuario.Contrasena != null)
                {
                    objData.IsValid(empleado, usuario.Contrasena, usuario);
                    usuario.Nombres   = objUsr.Obtener_Nombre_Usuario(empleado);
                    Session["nombre"] = usuario.Nombres;
                    int noEmpleado = objUsr.Obtener_Datos_Usuarios(empleado);
                    Session["id_Empleado"] = noEmpleado;
                    Session["idCargo"]     = usuario.Cargo;
                    int cargo = Convert.ToInt32(Session["idCargo"]);
                    if (cargo == 0)
                    {
                        Session["idCargo"]     = 0;
                        actionName             = "Login";
                        nameController         = "Login";
                        TempData["loginError"] = "The session has expired, access the system again.";
                    }
                    usuario.CatRoles   = objCaRoles.ConsultarListaRoles(usuario.Cargo);
                    Session["rolUser"] = usuario.CatRoles.Rol;
                    string pass     = objUsr.Obtener_Contraseña_Usuario(empleado);
                    string sucursal = objUsr.Obtener_Sucursal_Usuario(empleado);
                    Session["sucursal"] = sucursal;

                    if (noEmpleado != 0 && pass.CompareTo(usuario.Contrasena) == 0)
                    {
                        if (usuario.Cargo == 1)
                        {
                            actionName     = "Index";
                            nameController = "Pedidos";
                        }
                        else if (usuario.Cargo == 4)
                        {
                            actionName     = "Index";
                            nameController = "Almacen";
                        }
                        else if (usuario.Cargo == 5)
                        {
                            actionName     = "Index";
                            nameController = "PrintShop";
                        }
                        else if (usuario.Cargo == 6)
                        {
                            actionName     = "Index";
                            nameController = "Shipping";
                        }
                        else if (usuario.Cargo == 7)
                        {
                            actionName     = "Index";
                            nameController = "Staging";
                        }
                        else if (usuario.Cargo == 8)
                        {
                            actionName     = "Index";
                            nameController = "PNL";
                        }
                        else if (usuario.Cargo == 9)
                        {
                            actionName     = "Index";
                            nameController = "Packing";
                        }
                        else if (usuario.Cargo == 12)
                        {
                            actionName     = "Index";
                            nameController = "Arte";
                        }
                        else if (usuario.Cargo == 15)
                        {
                            actionName     = "Index";
                            nameController = "customerService";
                        }
                        else if (usuario.Cargo == 10)
                        {
                            actionName     = "Index";
                            nameController = "Trims";
                        }
                        else if (usuario.Cargo == 20)
                        {
                            actionName     = "Index";
                            nameController = "Pedidos";
                        }
                        else if (usuario.Cargo == 0)
                        {
                            actionName     = "Login";
                            nameController = "Login";
                        }
                    }
                    else
                    {
                        actionName             = "Login";
                        nameController         = "Login";
                        TempData["loginError"] = "The employee number or password is incorrect.";
                    }
                }
                else
                {
                    actionName             = "Login";
                    nameController         = "Login";
                    TempData["loginError"] = "Please enter your employee number and password.";
                }
                return(RedirectToAction(actionName, nameController));
            }


            if (ModelState.IsValid)
            {
                if (objData.IsValid(empleado, usuario.Contrasena, usuario))
                {
                    //FormsAuthentication.SetAuthCookie(usuario.Nombres, usuario.Contrasena);
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Login incorrecto!");
                }
            }
            return(View(usuario));
        }
예제 #34
0
        public ActionResult Loginagency(FingerprintsModel.Login User, bool?chkRememberMe)
        {
            try
            {
                string IPAddress  = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                bool   isCoreTeam = false;

                if (string.IsNullOrEmpty(IPAddress))
                {
                    IPAddress = Request.ServerVariables["REMOTE_ADDR"];
                }

                if (string.IsNullOrWhiteSpace(User.Emailid) || string.IsNullOrWhiteSpace(User.Password))
                {
                    ViewBag.message = "Please enter email and password.";
                    return(View());
                }
                string result = string.Empty;

                FingerprintsModel.Login UserInfo = LoginData.LoginUser(out result, User.Emailid.Trim(), User.Password.Trim(), IPAddress);
                if (!result.ToLower().Contains("success"))
                {
                    User.UserName   = string.Empty;
                    User.Password   = string.Empty;
                    ViewBag.message = result;
                    return(View());
                }
                else
                {
                    if (chkRememberMe != null && Convert.ToBoolean(chkRememberMe))
                    {
                        HttpCookie Emailid = new HttpCookie("Emailid", UserInfo.Emailid);
                        Emailid.Expires = DateTime.Now.AddYears(1);
                        HttpCookie Password = new HttpCookie("Password", User.Password);
                        Password.Expires = DateTime.Now.AddYears(1);
                        Response.Cookies.Add(Emailid);
                        Response.Cookies.Add(Password);
                    }
                    else
                    {
                        HttpCookie Emailid = new HttpCookie("Emailid");
                        Emailid.Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(Emailid);
                        HttpCookie Password = new HttpCookie("Password");
                        Password.Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(Password);
                    }
                    Session["UserID"]                     = UserInfo.UserId;
                    Session["RoleName"]                   = UserInfo.RoleName.Replace(" ", string.Empty);
                    Session["EmailID"]                    = UserInfo.Emailid;
                    Session["FullName"]                   = UserInfo.UserName;
                    Session["AgencyName"]                 = UserInfo.AgencyName;
                    Session["Roleid"]                     = UserInfo.roleId;
                    Session["MenuEnable"]                 = UserInfo.MenuEnable;
                    Session["IsCoreTeam"]                 = false;
                    Session["IsDemographic"]              = false;
                    Session["isAcceptance"]               = false;
                    Session["IsShowPIR"]                  = UserInfo.IsShowPIR;
                    Session["IsShowSectionB"]             = UserInfo.IsShowSectionB;
                    Session["IsShowScreening"]            = UserInfo.IsShowScreening;
                    Session["IsInAcceptanceProcess"]      = UserInfo.IsInAcceptanceProcess;
                    Session["AllowCaseNoteTeacher"]       = UserInfo.AllowCaseNoteTeacher;
                    Session["AvailableDailyHealthChecks"] = UserInfo.AvailableDailyHealthChecks;
                    Session["HasSignatureCode"]           = (UserInfo.StaffSignature.StaffSignatureID > 0);
                    Session["StaffSignature"]             = UserInfo.StaffSignature.Signature;



                    if (UserInfo.AgencyId != null)
                    {
                        Session["AgencyID"] = UserInfo.AgencyId;
                        isCoreTeam          = new LoginData().IsDevelopmentTeam(UserInfo.UserId, UserInfo.AgencyId, UserInfo.roleId);
                        List <Tuple <string, string, int, bool> > AccessList = new List <Tuple <string, string, int, bool> >();
                        bool isAcceptanceProcess = false;
                        AccessList = new LoginData().GetAccessPageByUserId(ref isAcceptanceProcess, UserInfo.UserId, UserInfo.AgencyId, UserInfo.roleId);

                        Session["AccessList"]            = AccessList;
                        UserInfo.IsInAcceptanceProcess   = isAcceptanceProcess;
                        Session["IsInAcceptanceProcess"] = UserInfo.IsInAcceptanceProcess;

                        if (isCoreTeam)
                        {
                            Session["IsCoreTeam"] = true;
                        }

                        if (UserInfo.RoleList != null)
                        {
                            Session["RoleList"] = UserInfo.RoleList;
                        }
                    }



                    if (!string.IsNullOrEmpty(UserInfo.AccessStart))
                    {
                        Session["AccessStart"] = UserInfo.AccessStart;
                    }
                    if (!string.IsNullOrEmpty(UserInfo.AccessStop))
                    {
                        Session["AccessStop"] = UserInfo.AccessStop;
                    }
                }

                StaffDetails staff = StaffDetails.GetInstance();

                AppUserState appUserState = new AppUserState()
                {
                    Email    = staff.EmailID,
                    Name     = staff.FullName,
                    UserId   = staff.UserId.ToString(),
                    RoleId   = staff.RoleId.ToString(),
                    AgencyId = staff.AgencyId.ToString()
                };
                string uniqueId = Guid.NewGuid().ToString();
                IdentitySignin(appUserState, uniqueId, Convert.ToBoolean(chkRememberMe == null?false:chkRememberMe));

                string newLocation = string.Empty;
                if (Session["Roleid"].ToString().Contains("f87b4a71-f0a8-43c3-aea7-267e5e37a59d"))
                {
                    newLocation = "~/Home/SuperAdminDashboard";
                }

                else if (Session["Roleid"].ToString().Contains("a65bb7c2-e320-42a2-aed4-409a321c08a5") && Session["MenuEnable"] != null && Convert.ToBoolean(Session["MenuEnable"]))
                {
                    newLocation = "~/Home/AgencyAdminDashboard";
                }

                else if (Session["Roleid"].ToString().Contains("a65bb7c2-e320-42a2-aed4-409a321c08a5") && Session["MenuEnable"] != null && !Convert.ToBoolean(Session["MenuEnable"]))
                {
                    newLocation = "~/Agency/AgencyProfile/" + UserInfo.AgencyId;
                }

                else if (Session["Roleid"].ToString().Contains("2d9822cd-85a3-4269-9609-9aabb914d792"))
                {
                    newLocation = "~/Home/AgencyHRDashboard";
                }

                else if (Session["Roleid"].ToString().Contains("94cdf8a2-8d81-4b80-a2c6-cdbdc5894b6d"))
                {
                    newLocation = "~/Home/AgencystaffDashboard";
                }

                else if (Session["Roleid"].ToString() == "a31b1716-b042-46b7-acc0-95794e378b26")
                {
                    // newLocation = "~/Home/ApplicationApprovalDashboard";
                    newLocation = "~/Roster/Roster";
                }

                else if (Session["Roleid"].ToString() == "e4c80fc2-8b64-447a-99b4-95d1510b01e9")
                {
                    newLocation = "~/Home/AgencystaffDashboard";
                }

                else if (Session["Roleid"].ToString() == "82b862e6-1a0f-46d2-aad4-34f89f72369a")
                {
                    newLocation = "~/Teacher/Roster";
                }

                else if (Session["Roleid"].ToString() == "b4d86d72-0b86-41b2-adc4-5ccce7e9775b")
                {
                    newLocation = "~/Home/Dashboard";
                }

                //else if (Session["Roleid"].ToString() == "2ADFE9C6-0768-4A35-9088-E0E6EA91F709")
                else if (Session["Roleid"].ToString() == "2adfe9c6-0768-4a35-9088-e0e6ea91f709")
                {
                    newLocation = "~/Teacher/Roster";
                }

                else if (Session["Roleid"].ToString() == "9ad1750e-2522-4717-a71b-5916a38730ed")
                {
                    // newLocation = "~/Home/HealthManager";
                    newLocation = "~/HealthManager/Dashboard";
                }

                else if (Session["Roleid"].ToString() == "7c2422ba-7bd4-4278-99af-b694dcab7367")
                {
                    newLocation = "~/Home/Dashboard";
                }

                else if (Session["Roleid"].ToString() == "047c02fe-b8f1-4a9b-b01f-539d6a238d80")
                {
                    newLocation = "~/Home/AgencyDisabilityManagerDashboard";
                }

                else if (Session["Roleid"].ToString() == "699168ac-ad2d-48ac-b9de-9855d5dc9af8")
                {
                    newLocation = "~/MentalHealth/MentalHealthDashboard";
                }

                else if (Session["Roleid"].ToString() == "9c34ec8e-2359-4704-be89-d9f4b7706e82")
                {
                    newLocation = "~/Home/DisabilityStaffDashboard";
                }

                else if (staff.RoleId.ToString().ToLowerInvariant() == EnumHelper.GetEnumDescription(RoleEnum.SocialServiceManager).ToLowerInvariant())
                {
                    newLocation = "~/Home/Dashboard";
                }

                else if (Session["Roleid"].ToString().Contains("5ac211b2-7d4a-4e54-bd61-5c39d67a1106"))
                {
                    newLocation = "~/Parent/ParentInfo";
                }

                else if (Session["Roleid"].ToString().ToUpper().Contains("944D3851-75CC-41E9-B600-3FA904CF951F"))
                {
                    newLocation = "~/Billing/FamilyOverride";
                }

                else if (Session["Roleid"].ToString().ToUpper().Contains("B65759BA-4813-4906-9A69-E180156E42FC"))
                {
                    newLocation = "~/ERSEA/CenterAnalysis";
                }

                else if (Session["Roleid"].ToString() == "6ed25f82-57cb-4c04-ac8f-a97c44bdb5ba")
                {
                    newLocation = "~/Transportation/Dashboard";
                }

                else if (Session["Roleid"].ToString() == "825f6940-9973-42d2-b821-5b6c7c937bfe")
                {
                    newLocation = "~/Home/AgencyFacilitiesManagerDashboard";
                }

                else if (Session["Roleid"].ToString() == "cb540cea-154c-482e-82a6-c1e0a189f611")
                {
                    newLocation = "~/Home/FacilityWorkerDashboard";
                }

                else if (Session["Roleid"].ToString() == "4b77aab6-eed1-4ac3-b498-f3e80cf129c0")
                {
                    newLocation = "~/EducationManager/EducationManagerDashboard";
                }
                else
                {
                    newLocation = "~/Home/Dashboard";
                }
                return(Redirect(newLocation));
            }
            catch (Exception Ex)
            {
                clsError.WriteException(Ex);
                ViewBag.message = "Error Occurred. Please try again.";
                return(View());
            }
        }
        private void CheckSetting(string settingKey, string settingValue)
        {
            string    url       = "";
            LoginData loginData = null;

            switch (settingKey)
            {
            case "Base path":                // Settings.LocalBasePath
            case "Production path":          // Settings.LocalProductionPath
            case "FFmpeg path":              // Settings.LocalFfmpegExePath
            case "Audio path":               //Settings.LocalAudioPath
            case "Fusion plugin path":       //Settings.LocalFusionPluginPath
            case "Deadline executable path": //Settings.LocalDeadlineExePath
                if (IOHelper.IsDirectory(settingValue))
                {
                    if (!Directory.Exists(settingValue))
                    {
                        ErrorString += string.Format("- Directory '{0}' does not exist.\r\n", settingValue);
                    }
                }
                else
                {
                    if (!File.Exists(settingValue))
                    {
                        ErrorString += string.Format("- File '{0}' does not exist.\r\n", settingValue);
                    }
                }
                break;

            case "Server url":   //Settings.ServerUrl
            case "Services url": //Settings.ServicesUrl
            case "Film url":     // Settings.ServerUrl
                url = settingValue;
                break;

            case "SALTED string":     //Settings.SALTED
                if (settingValue.Length == 0)
                {
                    ErrorString += "No SALTED pass defined.\r\n";
                }
                break;

            case "Email server settings":     //"Settings.EmailServerLogin"
                break;

            case "Ghostscript installation":
                RegistryKey gsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\GPL Ghostscript", false);
                if (gsKey == null)
                {
                    ErrorString += "Ghostscript not installed (required to process PDFs)";
                }
                break;
            }

            if (url.Length > 0)
            {
                if (!IsUrlReachable(url))
                {
                    ErrorString += string.Format("- URL '{0}' is not reachable.\r\n", url);
                }
            }
            else if (loginData != null)
            {
                string ftpLoginResult = IsSFtpServerAvailable(loginData);
                if (ftpLoginResult.Length > 0)
                {
                    ErrorString += ftpLoginResult;
                }
            }
        }
예제 #36
0
        /// <summary>
        /// 非同期的にログインを行います。
        /// </summary>
        public void LoginAsync(LoginData loginData)
        {
            if (loginData == null)
            {
                return;
            }

            using (new LazyModelLock(this, SyncRoot))
            {
                try
                {
                    if (LoginState == LoginState.Logining)
                    {
                        return;
                    }

                    LoginState = LoginState.Logining;

                    // ログインの非同期処理を開始します。
                    ThreadPool.QueueUserWorkItem(
                        LoginAsync,
                        loginData);
                }
                catch (Exception)
                {
                    LoginState =
                        (IsLogin ? LoginState.Logined : LoginState.Waiting);
                }
            }
        }
예제 #37
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public NicoClient()
 {
     LoginState = LoginState.Waiting;
     LoginData = new LoginData();
 }
예제 #38
0
        /// <summary>
        /// ニコニコへログイン済みのクッキーを設定します。
        /// </summary>
        /// <param name="cookieContainer">
        /// クッキーデータを指定します。
        /// </param>
        /// <param name="loginData">
        /// 指定のクッキーが指定のデータから取得したことが分かっている場合は
        /// 指定してください。nullでもかまいません。
        /// </param>
        public bool Login(CookieContainer cookieContainer,
                          LoginData loginData = null)
        {
            if (cookieContainer == null)
            {
                return false;
            }

            // アカウント情報を取得します。
            // 取得できなければ、このクッキーはログインされていません。
            var accountInfo = CookieValidator.Validate(
                cookieContainer);
            if (accountInfo == null)
            {
                return false;
            }

            // ロックせずに設定します。
            CookieContainer = cookieContainer;
            AccountInfo = accountInfo;
            LoginData = loginData;

            NotifyLoginSucceeded();
            return true;
        }
예제 #39
0
        /// <summary>
        /// ニコニコへログインします。
        /// </summary>
        public bool Login(LoginData loginData)
        {
            if (loginData == null)
            {
                return false;
            }

            // 得られたクッキーでログインを試みます。
            var cc = Loginer.LoginFromData(loginData, false);
            if (cc == null)
            {
                return false;
            }

            return Login(cc, loginData);
        } 
예제 #40
0
    public void Login(GamePlatform platform, string user, string password, string publicServerKey, string token, LoginResultRef result, LoginData resultLoginData_)
    {
        loginResult = result;
        resultLoginData = resultLoginData_;
        result.value = LoginResult.Connecting;

        LoginUser = user;
        LoginPassword = password;
        LoginToken = token;
        LoginPublicServerKey = publicServerKey;
        shouldLogin = true;
    }
예제 #41
0
        /// <summary>
        /// Validates the passed username and password against the database.
        /// </summary>
        /// <param name="sentUser">The user to validate</param>
        /// <returns>Result of authentication request indicating success or failure mode.</returns>
        public UserAuthenticationResult validateUser(LoginData sentUser)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(sqlStrBldr.ConnectionString))
                {
                    SqlCommand command = new SqlCommand("checkMusicUser", connection);
                    command.CommandType = CommandType.StoredProcedure;

                    SqlParameter userName = new SqlParameter("@uname", SqlDbType.VarChar);
                    userName.Direction = ParameterDirection.Input;
                    userName.Value = sentUser.username;
                    userName.Size = 50;
                    command.Parameters.Add(userName);

                    SqlParameter password = new SqlParameter("@passw", SqlDbType.VarChar);
                    password.Direction = ParameterDirection.Input;
                    password.Value = sentUser.password;
                    password.Size = 80;
                    command.Parameters.Add(password);

                    SqlParameter returnValue = new SqlParameter("@retval", SqlDbType.Int);
                    returnValue.Direction = ParameterDirection.Output;
                    command.Parameters.Add(returnValue);

                    command.Connection.Open();
                    command.ExecuteNonQuery();

                    return (UserAuthenticationResult)(int)command.Parameters["@retval"].Value;
                }
            }
            catch
            {
                return UserAuthenticationResult.UnknownResult;
            }
        }
예제 #42
0
파일: Program.cs 프로젝트: ssickles/archive
        static void Main(string[] args)
        {
            IList<AuthenticationTemplateData> templates = (from atd in (IEnumerable<AuthenticationTemplateData>)RepositoryFactory.AuthenticationTemplateRepository.GetAllAuthenticationTemplates()
                                                           where atd.AuthenticationUnitCode != "P1"
                                                           select atd).ToList();

            Random rndGroup = new Random();
            Random rndTemplate = new Random();
            Guid adminId = Guid.Empty;

            for (int i = 0; i < 100000; i++)
            {
                Console.WriteLine("Adding Identity " + i);
                IdentityData identity = new IdentityData()
                {
                    CountryCode = "US",
                    FirstName = "Scott" + i,
                    LastName = "Sickles" + i,
                    FullName = "Scott" + i + " Sickles" + i,
                    IdentityCode = i % 10 == 0 ? "E" : "C",
                    SourceId = i.ToString(),
                    GroupId = rndGroup.Next(26) + 1
                };
                identity.Uid = RepositoryFactory.IdentityRepository.Add(identity);
                Audit.AuditEvent(Audit.EventTypes.AddIdentity, string.Format("Identity {0} has been added.", identity.Uid), Guid.Empty);

                LoginData login1 = new LoginData()
                {
                    IdentityId = identity.Uid,
                    ApplicationCode = "T24",
                    LoginName = "AUTHOR",
                    Password = "******",
                    RoleCode = "T24USER",
                    T24Id = i.ToString()
                };
                login1.Id = RepositoryFactory.LoginRepository.Add(login1);
                Audit.AuditEvent(Audit.EventTypes.AddLogin, string.Format("Login {0} has been added for Identity {1}.", login1.Id, identity.Uid), Guid.Empty);

                LoginData login2 = new LoginData()
                {
                    IdentityId = identity.Uid,
                    ApplicationCode = "LA",
                    LoginName = "system",
                    Password = "******",
                    RoleCode = "LAUSER",
                    T24Id = i.ToString()
                };
                login2.Id = RepositoryFactory.LoginRepository.Add(login2);
                Audit.AuditEvent(Audit.EventTypes.AddLogin, string.Format("Login {0} has been added for Identity {1}.", login2.Id, identity.Uid), Guid.Empty);

                EnrollmentData enroll1 = new EnrollmentData()
                {
                    IdentityId = identity.Uid,
                    AdministratorId = adminId,
                    AuthenticationTypeCode = "FP"
                };
                enroll1.Uid = RepositoryFactory.EnrollmentRepository.Add(enroll1);
                Audit.AuditEvent(Audit.EventTypes.AddEnrollment, string.Format("Enrollment {0} has been added for Identity {1}.", enroll1.Uid, identity.Uid), Guid.Empty);
                //now add the templates to go along with the enrollment
                List<int> temps1 = new List<int>();
                for (int j = 0; j < 10; j++)
                {
                    int tempIndex;
                    do
                    {
                        tempIndex = rndTemplate.Next(templates.Count - 1);
                    } while (temps1.Contains(tempIndex));
                    temps1.Add(tempIndex);
                    AuthenticationTemplateData temp = new AuthenticationTemplateData()
                    {
                        AuthenticationUnitCode = templates[tempIndex].AuthenticationUnitCode,
                        EnrollmentId = enroll1.Uid,
                        Score = templates[tempIndex].Score,
                        Template = templates[tempIndex].Template
                    };
                    temp.Uid = RepositoryFactory.AuthenticationTemplateRepository.Add(temp);
                    Audit.AuditEvent(Audit.EventTypes.AddAuthenticationTemplate, string.Format("Authentication Template {0} has been added for Enrollment {1}.", temp.Uid, enroll1.Uid), Guid.Empty);
                }

                if (i % 5 == 0)
                {
                    EnrollmentData enroll2 = new EnrollmentData()
                    {
                        IdentityId = identity.Uid,
                        AdministratorId = adminId,
                        AuthenticationTypeCode = "FP"
                    };
                    enroll2.Uid = RepositoryFactory.EnrollmentRepository.Add(enroll2);
                    Audit.AuditEvent(Audit.EventTypes.AddEnrollment, string.Format("Enrollment {0} has been added for Identity {1}.", enroll2.Uid, identity.Uid), Guid.Empty);
                    //now add the templates to go along with the enrollment
                    List<int> temps2 = new List<int>();
                    for (int j = 0; j < 10; j++)
                    {
                        int tempIndex;
                        do
                        {
                            tempIndex = rndTemplate.Next(templates.Count - 1);
                        } while (temps2.Contains(tempIndex));
                        temps2.Add(tempIndex);
                        AuthenticationTemplateData temp = new AuthenticationTemplateData()
                        {
                            AuthenticationUnitCode = templates[tempIndex].AuthenticationUnitCode,
                            EnrollmentId = enroll2.Uid,
                            Score = templates[tempIndex].Score,
                            Template = templates[tempIndex].Template
                        };
                        temp.Uid = RepositoryFactory.AuthenticationTemplateRepository.Add(temp);
                        Audit.AuditEvent(Audit.EventTypes.AddAuthenticationTemplate, string.Format("Authentication Template {0} has been added for Enrollment {1}.", temp.Uid, enroll2.Uid), Guid.Empty);
                    }
                }

                //every fifth identity added becomes the enrollment officer for the next 5
                if (i % 5 == 0) adminId = identity.Uid;
            }
        }
예제 #43
0
        private void IClientRegistered()
        {
            pnAuth2Cli_ClientRegisterReply reply = new pnAuth2Cli_ClientRegisterReply();
            reply.Read(fStream);

            // This always happens as a result of a login request
            // This is such an implementation detail that there's really no need to expose it
            fSrvChg = reply.fChallenge;
            ILogin(fEvilTemporaryHack.fUser, fEvilTemporaryHack.fPass, fEvilTemporaryHack.fCallback);
            fEvilTemporaryHack = null; // Take out the trash...
        }
        private int CreateNews(LoginData loginData)
        {
            var news = new AddNewsBindingModel
            {
                Title = "News title",
                Content = "some news content",
                PublishDate = DateTime.Now
            };

            var newsContent = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("title", news.Title),
                new KeyValuePair<string, string>("content", news.Content),
                new KeyValuePair<string, string>("publishDate", news.PublishDate.ToString())
            });

            // Act
            this.httpClient.DefaultRequestHeaders.Add(
                   "Authorization", "Bearer " + loginData.Access_Token);
            var httpResponse = this.httpClient.PostAsync("api/news", newsContent).Result;
            this.httpClient.DefaultRequestHeaders.Remove("Authorization");

            if (!httpResponse.IsSuccessStatusCode)
            {
                // Nothing to return, throw a proper exception + message
                throw new HttpRequestException(
                    httpResponse.Content.ReadAsStringAsync().Result);
            }

            var dbNews = httpResponse.Content.ReadAsAsync<News>().Result;

            return dbNews.Id;
        }
예제 #45
0
        public HttpResponseMessage Post(LoginDTO dto)
        {
            try
            {
                using (AspodesDB _context = new AspodesDB())
                {
                    string pwd = HashHelper.IntoMd5(dto.Password);
                    //User user = _context.Users.FirstOrDefault(u => u.UserId == dto.Username && u.Password == pwd && u.Person.Status != "D");

                    //20170114 为演示方便,更改登录验证为 EnglishName 登录(英文名默认为汉字转拼音)
                    string username = dto.Username.ToLower().Replace("@qq.com", "").ToUpper();
                    User   user     = _context.Users.FirstOrDefault(u => (u.Person.EnglishName == username || u.UserId == dto.Username) && u.Password == pwd && u.Person.Status != "D");

                    if (null == user)
                    {
                        return(ResponseWrapper.ExceptionResponse(new OtherException("用户名或密码错误!")));
                    }
                    var roles = (from r in _context.Roles
                                 join a in _context.Authorizes
                                 on r.RoleId equals a.RoleId
                                 join u in _context.Users
                                 on a.UserId equals u.UserId
                                 where u.UserId == user.UserId
                                 select r.Name).ToArray();

                    LoginData ld = new LoginData();
                    ld.UserId        = user.UserId;
                    ld.UserName      = user.Name;
                    ld.UserTimeStamp = HashHelper.GetTimestamp();
                    ld.Roles         = roles;

                    if (user.Person.PersonId.HasValue)
                    {
                        ld.PersonId = user.Person.PersonId.Value;
                    }
                    else
                    {
                        ld.PersonId = 0;
                    }

                    LoginLog log = new LoginLog();
                    log.LoginLogId     = Guid.NewGuid().ToString();
                    log.UserId         = user.UserId;
                    log.Roles          = string.Join(",", roles);;
                    log.LoginIP        = Helper.GetClientIpAddress(Request);
                    log.LoginTime      = DateTime.Now;
                    log.LastActiveTime = DateTime.Now;
                    log.IsLogout       = false;
                    log.LoginTimeStamp = HashHelper.GetTimestamp(DateTime.Now.AddMinutes(HashHelper.LoginDuration));
                    log.Token          = HashHelper.Encrypt(JsonConvert.SerializeObject(ld));
                    ld.Token           = log.Token;

                    _context.LoginLogs.Add(log);

                    _context.SaveChanges();

                    CurrentUser current = new CurrentUser
                    {
                        UserId   = user.UserId,
                        PersonId = user.PersonId.Value,
                        InstId   = user.Person.InstituteId.Value,
                        Name     = user.Name,
                        Roles    = roles
                    };
                    if (roles.Contains("院管理员"))
                    {
                        var projectTypes = from aa in _context.ApplicationAssignments where aa.UserId == user.UserId select aa.ProjectTypeId;
                        current.ProjectTypeIds = projectTypes.ToArray();
                    }

                    var cookie = new HttpCookie("user", UserHelper.SerializeUserInfo(current));
                    HttpContext.Current.Response.AppendCookie(cookie);

                    return(ResponseWrapper.SuccessResponse(ld));
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return(ResponseWrapper.ExceptionResponse(new OtherException("数据库连接错误")));
            }
            catch (Exception e)
            {
                var a = e.Message;
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
예제 #46
0
        private LoginData DoLogin(LoginVM model, string nrAcesso)
        {
            LoginData data = new LoginData
            {
                LoginMessage = LoginMessageId.Sucesso,
                ShowCaptcha = false
            };

            using (Context db = new Context())
            {
                using (var transaction = new RP.DataAccess.RPTransactionScope(db))
                {

                    // instancia bll do usuario
                    UsuarioBLL usuarioBLL = new UsuarioBLL(db, 0);

                    // consulta usuario pelo login
                    Usuario usuario = usuarioBLL.FindSingle(u => u.dsLogin.ToLower().Equals(model.Usuario.ToLower()));

                    //if (data.ShowCaptcha)
                    //    return data;

                    // se o usuario nao existir
                    if (usuario == null)
                    {
                        data.LoginMessage = LoginMessageId.UsuarioInvalido;
                    }
                    // se o usuario existir
                    else
                    {
                        data.ShowCaptcha = usuario.nrFalhalogin >= Convert.ToInt32(ConfigurationManager.AppSettings["Seguranca:tentativasParaExibirCaptcha"]);
                        // se a senha informada estiver incorreta
                        if (!(usuario.dsSenha == RP.Util.Class.Util.getHash(model.Senha)))
                        {
                            // registra a tentiva falha de acesso
                            AccessRegister(model.Usuario, false);

                            // seta status do login
                            data.LoginMessage = LoginMessageId.SenhaInvalida;

                            // instancia bll de Log
                            //RP.Log.Model.BLL LogBLL = new Log.Model.BLL();

                            // altera a quantidade de falhas
                            usuario.nrFalhalogin = (usuario.nrFalhalogin ?? 0) + 1;
                            data.ShowCaptcha = usuario.nrFalhalogin >= Convert.ToInt32(ConfigurationManager.AppSettings["Seguranca:tentativasParaExibirCaptcha"]);

                            // armazena tentativas falhas de acesso
                            data.TentativasFalhas = usuario.nrFalhalogin ?? 0;

                            // armazena as tentativas falhas de acesso
                            if (data.TentativasFalhas >= Convert.ToInt32(ConfigurationManager.AppSettings["Seguranca:tentativasParaBloquearUsuario"]))
                            {
                                // bloqueia o usuario no banco
                                usuario.flAtivo = "Não";
                                usuarioBLL.Update(usuario);

                                // seta status do login
                                data.LoginMessage = LoginMessageId.UsuarioInativo;
                            }
                            else
                            {
                                usuarioBLL.UpdateLoginCount(usuario);
                            }

                        }
                        // se a senha estiver correta
                        else
                        {
                            // se usuario não estiver ativo
                            if (!(usuario.flAtivo.ToLower().Equals("sim")))
                            {
                                data.LoginMessage = LoginMessageId.UsuarioInativo;
                            }
                            // se usuario nao tiver licencas disponiveis
                            else if (!Auth.Class.License.UseLicense(usuario.dsLogin, nrAcesso))
                            {
                                data.LoginMessage = LoginMessageId.SemLicenca;
                            }
                            // se a senha do usuario estiver expirada
                            else if ((usuario.dtValidade ?? DateTime.Now.Date.AddDays(-1)) < DateTime.Now.Date)
                            {
                                data.LoginMessage = LoginMessageId.SenhaExpirada;
                            }
                            else
                            {
                                usuario.nrFalhalogin = 0;
                                usuarioBLL.UpdateLoginCount(usuario);
                            }

                            // armazena usuario
                            data.Usuario = usuario;
                        }

                        usuarioBLL.SaveChanges();
                        transaction.Complete();
                    }
                }
            }

            return data;
        }
예제 #47
0
 public GameNetLoginModel()
 {
     Db = new CheckersDBDataContext();
     LoginData = new LoginData();
 } // GameNetLoginModel ctor
예제 #48
0
    internal void ConnectToGame(LoginData loginResultData, string username)
    {
        ConnectData connectData = new ConnectData();
        connectData.Ip = loginResultData.ServerAddress;
        connectData.Port = loginResultData.Port;
        connectData.Auth = loginResultData.AuthCode;
        connectData.Username = username;

        StartGame(false, null, connectData);
    }
 public DatabaseConfigurationViewModel()
 {
     CurrentLoginData = new LoginData(true);
 }
예제 #50
0
 internal void Login(string user, string password, string serverHash, string token, LoginResultRef loginResult, LoginData loginResultData)
 {
     if (user == "" || (password == "" && token == ""))
     {
         loginResult.value = LoginResult.Failed;
     }
     else
     {
         loginClient.Login(p, user, password, serverHash, token, loginResult, loginResultData);
     }
 }
 public CreateMenuCycleItemStepDef(LoginData loginData, MenuCycleRecord menuCycleLastId)
 {
     this.menuCycleLastId = menuCycleLastId;
 }
예제 #52
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
            {
                return(AuthenticateResult.Fail("Missing Authorization Header"));
            }

            EmployeeModel admin           = null;
            ClientModel   client          = null;
            LoginData     loginDataPerson = null;
            Person        person          = null;

            try
            {
                var authHeader      = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(':');
                var username        = credentials[0];
                var password        = credentials[1];
                admin           = _adminService.AuthenticateEmployee(username, password);
                client          = _clientService.AuthenticateClient(username, password);
                loginDataPerson = _context.LoginData.FirstOrDefault(x => x.Username == username);
                person          = _context.People.FirstOrDefault(x => x.LoginDataId == loginDataPerson.LoginDataId);
            }
            catch
            {
                return(AuthenticateResult.Fail("Invalid Authorization Header"));
            }

            if (admin == null && client == null)
            {
                return(AuthenticateResult.Fail("Invalid Username or Password"));
            }



            var claims = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, loginDataPerson.Username),
                new Claim(ClaimTypes.Name, person.FirstName),
            };


            if (admin != null)
            {
                var employeeRoles     = _context.EmployeeRoles.ToList();
                var employeeRolesList = _context.EmployeeEmployeeRoles.ToList();

                foreach (var x in employeeRolesList)
                {
                    if (admin.EmployeeId == x.EmployeeId)
                    {
                        foreach (var y in employeeRoles)
                        {
                            if (x.EmployeeRolesId == y.EmployeeRolesId)
                            {
                                claims.Add(new Claim(ClaimTypes.Role, y.Name));
                            }
                        }

                        break;
                    }
                }
            }

            if (client != null)
            {
                claims.Add(new Claim(ClaimTypes.Role, "Client"));
            }

            var identity  = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket    = new AuthenticationTicket(principal, Scheme.Name);

            return(AuthenticateResult.Success(ticket));
        }
예제 #53
0
        public BaseModel <object> DS_ThanhVien_Group(int id_group, [FromBody] QueryRequestParams p)
        {
            string    Token     = lc.GetHeader(Request);
            LoginData loginData = lc._GetInfoUser(Token);

            if (loginData == null)
            {
                return(JsonResultCommon.DangNhap());
            }
            try
            {
                using (DpsConnection cnn = new DpsConnection(_config.ConnectionString))
                {
                    Dictionary <string, string> _sortableFields = new Dictionary <string, string>
                    {
                        { "Username", "Username" },
                        //{ "DonViTinh", "DonViTinh" }
                    };
                    Panigator v_panigator = null;
                    IDictionary <string, string> v_dic_keyFilter = new Dictionary <string, string>
                    {
                        { "Username", "Username" },
                        //{ "DonViTinh", "DonViTinh"},
                    };

                    string        _select = "", _sqlQuery = "", v_str_paginate = "", _orderBy = "", _whereCondition = "";
                    SqlConditions _cond = new SqlConditions();

                    #region Filter, sort, paganitor
                    //filter request have to right and enough , same in code
                    if (p.Filter != null)
                    {
                        if (p.Filter.Count > 0)
                        {
                            var listKeySearch = p.Filter.Where(x => !v_dic_keyFilter.ContainsKey(x.Key)).Select(q => q.Key).ToList();
                            if (listKeySearch != null && listKeySearch.Count > 0)
                            {
                                return(JsonResultCommon.NotData());
                            }

                            foreach (string _filter in p.Filter.Keys)
                            {
                                if (!string.IsNullOrEmpty(p.Filter[_filter]))
                                {
                                    foreach (string vl in p.Filter.Values)
                                    {
                                        //_whereCondition += " AND " + v_dic_keyFilter[_filter] + " = @" + _filter;
                                        _whereCondition += " AND " + v_dic_keyFilter[_filter] + " LIKE'%";
                                        _whereCondition += vl;
                                        _whereCondition += "%'";
                                        _cond.Add(_filter, p.Filter[_filter]);
                                    }
                                }
                            }
                        }
                    }

                    //sort column in datatable
                    if (p.Sort != null)
                    {
                        if (!string.IsNullOrEmpty(p.Sort.ColumnName) && v_dic_keyFilter.ContainsKey(p.Sort.ColumnName))
                        {
                            _orderBy = v_dic_keyFilter[p.Sort.ColumnName] + " " + (p.Sort.Direction.ToLower().Equals("asc") ? "asc" : "desc");
                        }
                    }

                    int page_index = 0;
                    //set up panigator for datatable
                    if (p.Panigator != null)
                    {
                        //v_str_paginate = $@" OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;";
                        //// offset fetch là các tùy chọn của mệnh đề order by
                        //_cond.Add("PageSize", p.Panigator.PageSize);
                        //_cond.Add("PageNumber", p.Panigator.PageIndex);

                        page_index = p.Panigator.PageIndex;
                    }
                    #endregion

                    _sqlQuery = $@" select ID_GROUP, U.ID_USER, QUYEN_ADMIN
, CREATE_DATE, IDNV, UserName, AVATAR from TBL_GROUPMEMBER AS G, TBL_Account AS U
WHERE G.ID_USER = U.ID_USER and ID_GROUP=" + id_group + "" + _whereCondition + "";

                    DataTable _datatable = cnn.CreateDataTable(_sqlQuery, _cond);
                    int       _countRows = _datatable.Rows.Count;
                    if (cnn.LastError != null || _datatable == null)
                    {
                        return(JsonResultCommon.NotData());
                    }

                    if (_datatable.Rows.Count == 0)
                    {
                        return(JsonResultCommon.NotData());
                    }
                    else
                    {
                        if (page_index == 0)
                        {
                            p.Panigator.PageSize = _countRows;
                        }
                        v_panigator = new Panigator(p.Panigator.PageIndex, p.Panigator.PageSize, _datatable.Rows.Count);
                    }

                    var _data = from r in _datatable.AsEnumerable().Skip((p.Panigator.PageIndex - 1) * p.Panigator.PageSize).Take(p.Panigator.PageSize).ToList()
                                select new
                    {
                        Id_group    = r["ID_GROUP"],
                        id_user     = r["ID_USER"],
                        id_nv       = r["IDNV"],
                        Username    = r["UserName"],
                        quyen_group = r["QUYEN_ADMIN"],
                        create_date = r["CREATE_DATE"],
                        hinhanh     = r["AVATAR"],
                        Avatar      = LiteController.genLinkAvatar(_config.LinkAPI, r["AVATAR"]),
                    };

                    return(JsonResultCommon.ThanhCong(_data, v_panigator));
                }
            }
            catch (Exception ex)
            {
                return(JsonResultCommon.Exception(ex));
            }
        }
예제 #54
0
 public RestConnector()
 {
     currentLoginData = new LoginData();
 }
예제 #55
0
        /// <summary>
        /// ログイン用データからログインを試みます。
        /// </summary>
        public static CookieContainer LoginFromData(LoginData loginData,
                                                    bool validate)
        {
            try
            {
                if (loginData == null)
                {
                    return null;
                }

                // データに沿ったログイン方法でログインします。
                CookieContainer cc = null;
                switch (loginData.LoginMethod)
                {
                    case LoginMethod.Direct:
                        // 直接ログインします。
                        cc = DirectLogin(
                            loginData.Mail,
                            loginData.Password);
                        break;
                    case LoginMethod.WithBrowser:
                    case LoginMethod.AvailableCookie:
                        // ブラウザからログインします。
                        cc = LoginWithBrowser(
                            loginData.BrowserType,
                            validate);
                        break;
                }

                return cc;
            }
            catch (Exception)
            {
                // 例外は無視します。
            }

            return null;
        }
예제 #56
0
        public ActionResult Login()
        {
            LoginData data = new LoginData();

            return(View("Login", data));
        }
예제 #57
0
 public IActionResult UserLogin(LoginData data, string id)
 {
     return(Json(_projectCol.UserLogin(data, id)));
 }
예제 #58
0
 public bool UpdateCredentials(Profile profile, LoginData data) {
     return CredentialsCollection.AddOrUpdate(profile, data, (key, oldValue) => data).Equals(data);
 }
예제 #59
0
        public IHttpActionResult Login(LoginData loginData)
        {
            var result = JwtController.Instance.LoginUser(this.Request, loginData);

            return(this.ReplyWith(result));
        }
예제 #60
0
 private bool PerformLogin(LoginData credentials) {
     if (!failedLogin.Contains(credentials.User)) {
         if (credentials.IsManual) {
             GameModel model = ProfileManager.CurrentProfile.GameModel;
             if (ConfigurationManager.GetConfiguration(model).IsManualLoginSupported) {
                 Login(credentials.User, PassEncrypt.ConvertToUnsecureString(credentials.SecurePassword), true);
                 return true;
             }
         }
         if (credentials.IsCorrect) {
             LoginDialogData loginData = new LoginDialogData() {
                 Username = credentials.User,
                 Password = PassEncrypt.ConvertToUnsecureString(credentials.SecurePassword)
             };
             ShowLoggingInDialog(loginData);
             return true;
         }
     }
     return false;
 }