コード例 #1
0
        public void ReturnTestEmp1GivenValueOf1()
        {
            EmployeeAPIDAO result = _employeeUtil.GetEmployee(1);

            Assert.Equal("Test", result.FirstName);
            Assert.Equal("User", result.LastName);
            Assert.Equal("Test position 2", result.PositionName);
            Assert.Equal("HR", result.DepartmentName);
            Assert.True(result.Id.Equals(1));
        }
コード例 #2
0
        public async Task <IActionResult> OnPostAsync(string returnURL = "/index")
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var values = new Dictionary <string, string>
            {
                { "username", Username },
                { "password", Password }
            };

            HttpClient client = new HttpClient();

            var content = new StringContent("{\"username\":\"" + Username + "\",\"password\": \"" + Password + "\"}",
                                            Encoding.UTF8,
                                            "application/json");

            var response = await client.PostAsync("https://api-gateway-343.herokuapp.com/auth/login", content);

            var responseString = await response.Content.ReadAsStringAsync();

            try {
                Response resp = JsonConvert.DeserializeObject <Response>(responseString);


                if (!resp.Status)
                {
                    Error = "Username or Password is incorrect. Please try again";
                    return(Page());
                }
                else
                {
                    var jwt = resp.Token;

                    string[] parts     = jwt.Split(".".ToCharArray());
                    var      header    = parts[0];
                    var      payload   = parts[1];
                    var      signature = parts[2];//Base64UrlEncoded signature from the token

                    byte[] bytesToSign = Encoding.UTF8.GetBytes(string.Join(".", header, payload));

                    byte[] secret = Encoding.UTF8.GetBytes("secretkey");

                    var alg  = new HMACSHA256(secret);
                    var hash = alg.ComputeHash(bytesToSign);

                    var computedSignature = Base64UrlEncode(hash);

                    if (signature != computedSignature)
                    {
                        Error = "Something went wrong. Please try again.";
                        return(Page());
                    }

                    var handler = new JwtSecurityTokenHandler();

                    var token = handler.ReadToken(jwt) as JwtSecurityToken;

                    var userID = token.Claims.First(claim => claim.Type == "id").Value;

                    var userType = token.Claims.First(claim => claim.Type == "accountType").Value;

                    if (userType != "employee")
                    {
                        Error = "Username or Password is incorrect. Please try again";
                        return(Page());
                    }

                    EmployeeUtil empUtil = new EmployeeUtil(_context);

                    EmployeeAPIDAO userEmployee = empUtil.GetEmployeeByUserId(Convert.ToInt32(userID));

                    var userRole = userEmployee.RoleName;


                    // var role = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;

                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, Username),
                        new Claim(ClaimTypes.Name, jwt),
                        new Claim(ClaimTypes.Role, userRole),
                        new Claim(ClaimTypes.PrimarySid, Convert.ToString(userEmployee.Id))
                    };

                    var             userIdentity = new ClaimsIdentity(claims, "login");
                    ClaimsPrincipal principal    = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    return(Redirect(returnURL));
                }
            } catch (JsonReaderException) {
                Error = "Username or Password is incorrect. Please try again";
                return(Page());
            }
        }
コード例 #3
0
        public IActionResult GetEmployees([FromQuery] string region,
                                          [FromQuery] string position,
                                          [FromQuery] string department,
                                          [FromQuery] string id,
                                          [FromQuery] string userId,
                                          [FromQuery] string limit,
                                          [FromQuery] string pageNum)
        {
            var EmployeeUtilities = new EmployeeUtil(_context);

            if (!String.IsNullOrEmpty(id))
            {
                EmployeeAPIDAO e = EmployeeUtilities.GetEmployee(Int32.Parse(id));

                if (e == null)
                {
                    return(BadRequest(new
                    {
                        error = "Invalid EmployeeId Provided"
                    }));
                }

                return(Ok(e));
            }

            if (!String.IsNullOrEmpty(userId))
            {
                EmployeeAPIDAO e = EmployeeUtilities.GetEmployeeByUserId(Int32.Parse(userId));

                if (e == null)
                {
                    return(BadRequest(new
                    {
                        error = "Invalid userId Provided"
                    }));
                }

                return(Ok(e));
            }

            int itemLimit;

            if (String.IsNullOrEmpty(limit))
            {
                itemLimit = 25;
            }
            else
            {
                itemLimit = Int32.Parse(limit);
            }

            int page;

            if (String.IsNullOrEmpty(pageNum))
            {
                page = 1;
            }
            else
            {
                page = Int32.Parse(pageNum);
            }


            List <EmployeeAPIDAO> emps = EmployeeUtilities
                                         .GetEmployees(region, position, department, ((page - 1) * itemLimit), itemLimit);

            if (emps.Count() < itemLimit)
            {
                return(Ok(new
                {
                    data = emps
                }));
            }

            var nextString = "";

            if (!String.IsNullOrEmpty(region))
            {
                nextString += "&region=" + region;
            }
            if (!String.IsNullOrEmpty(department))
            {
                nextString += "&department=" + department;
            }
            if (!String.IsNullOrEmpty(position))
            {
                nextString += "&position=" + position;
            }


            return(Ok(new
            {
                data = emps,
                page = new {
                    nextPage = "?pageNum=" + (page + 1) + "&limit=" + itemLimit + nextString
                }
            }));
        }