Beispiel #1
0
        public ApiCustomer ValidateToken(string token)
        {
            ApiCustomer user = null;

            token = token.Replace(Prefixe, "");
            JwtSecurityToken jwtSecurityToken = Handler.ReadJwtToken(token);
            DateTime         now = DateTime.Now;

            if (jwtSecurityToken.ValidFrom <= now && jwtSecurityToken.ValidTo >= now)
            {
                JwtPayload payload      = jwtSecurityToken.Payload;
                string     compareToken = Handler.WriteToken(new JwtSecurityToken(Header, payload));

                if (token == compareToken)
                {
                    payload.TryGetValue("Id", out object id);
                    payload.TryGetValue("LastName", out object lastName);
                    payload.TryGetValue("FirstName", out object firstName);
                    payload.TryGetValue("Email", out object email);

                    user = new ApiCustomer(int.Parse((string)id), (string)lastName, (string)firstName, (string)email);
                }
            }

            return(user);
        }
Beispiel #2
0
        public async Task <ActionResult <int> > AddCustomer([FromBody] ApiCustomer customer)
        {
            using (dal)
            {
                try
                {
                    Customer c = new Customer
                    {
                        Birthday    = customer.Birthday,
                        Firstname   = customer.Firstname,
                        Lastname    = customer.Lastname,
                        HouseNumber = customer.HouseNumber,
                        Street      = customer.Street,
                        Town        = customer.Town,
                        ZipCode     = customer.ZipCode
                    };

                    int id = await dal.AddCustomer(c);

                    return(Ok(id));
                }
                catch (ArgumentException ex)
                {
                    return(BadRequest(ex.Message));
                }
            }
        }
        public HttpResponseMessage Get()
        {
            try
            {
                List <Customer> entities = db.Customers.Where(x => x.CustomerIsActive == true).ToList();

                if (entities == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                       "No Customers Found."));
                }

                List <ApiCustomer> apiCustomers = new List <ApiCustomer>();

                foreach (var record in entities)
                {
                    ApiCustomer apiCustomer = new ApiCustomer();
                    PropertyCopier <Customer, ApiCustomer> .Copy(record, apiCustomer);

                    apiCustomers.Add(apiCustomer);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, apiCustomers));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                   "Error in the code"));
            }
        }
        public HttpResponseMessage Put(int id, [FromBody] ApiCustomer newCustomer)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var entity = db.Customers.FirstOrDefault(x => x.CustomerId == id);

                    if (entity == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                           "Customer with Id " + id.ToString() + " not found to update."));
                    }

                    PropertyCopier <ApiCustomer, Customer> .Copy(newCustomer, entity);

                    db.SaveChanges();

                    return(Request.CreateResponse(HttpStatusCode.OK,
                                                  "Customer with Id " + id.ToString() + " found and updated."));
                }
                catch (Exception e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                       "Error in the code"));
                }
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Beispiel #5
0
        public bool SearchCustomerByUserName(string userName, string password)
        {
            ApiCustomerController controller = new ApiCustomerController();
            ApiCustomer           customer   = controller.SearchCustomerByUserName(userName, password);

            if (customer != null)
            {
                ClaimsIdentity identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, customer.UserName),
                    new Claim(ClaimTypes.Sid, customer.ID.ToString())
                },
                                                             "ApplicationCookie");

                IOwinContext           ctx         = Request.GetOwinContext();
                IAuthenticationManager authManager = ctx.Authentication;

                AuthenticationProperties authenticationproperties = new
                                                                    AuthenticationProperties
                {
                    IsPersistent = false
                };

                authManager.SignIn(authenticationproperties, identity);

                return(true);
            }

            return(false);
        }
Beispiel #6
0
        public static ApiCustomer GetCustomer(int id)
        {
            var customer = db.Customers.Find(id);

            var customerApi = new ApiCustomer();

            PropertyCopier <Customer, ApiCustomer> .Copy(customer, customerApi, true);

            return(customerApi);
        }
Beispiel #7
0
 public ActionResult Edit(ApiCustomer customer)
 {
     if (client.UpdateCustomer(customer))
     {
         ViewBag.message = "Customer Changed";
     }
     else
     {
         ViewBag.message = "Customer not Changed, error";
     }
     return(RedirectToAction("Details", new { id = customer.CustomerId }));
 }
Beispiel #8
0
        public static void PostCustomer(ApiCustomer ac)
        {
            // Create a new EF Customer.
            Customer c = new Customer();

            // Copy the Simplified customer to the EF customer using the tool I provided.
            PropertyCopier <ApiCustomer, Customer> .Copy(ac, c, true);

            // Tell EF we want to add the customer.
            db.Customers.Add(c);

            //Save changes
            db.SaveChanges();
        }
Beispiel #9
0
        public static void PutCustomer(int id, ApiCustomer ac)
        {
            // Create a new car
            Customer c = db.Customers.Find(id);

            // Copy car
            if (ac.CustomerId == id)
            {
                PropertyCopier <ApiCustomer, Customer> .Copy(ac, c, true);

                db.Entry(c).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
        }
Beispiel #10
0
        public async Task <ActionResult <int> > UpdateCustomer(int customerId, [FromBody] ApiCustomer customer)
        {
            using (dal)
            {
                try
                {
                    Customer c = new Customer
                    {
                        Gender      = customer.Gender,
                        Birthday    = customer.Birthday,
                        Firstname   = customer.Firstname,
                        Lastname    = customer.Lastname,
                        HouseNumber = customer.HouseNumber,
                        Street      = customer.Street,
                        Town        = customer.Town,
                        ZipCode     = customer.ZipCode
                    };
                    int updatedCustomerId = await dal.UpdateCustomer(customerId, c);

                    if (updatedCustomerId <= 0)
                    {
                        return(BadRequest());
                    }
                    else
                    {
                        return(Ok(updatedCustomerId));
                    }
                }
                catch (CustomerNotExistingException)
                {
                    return(BadRequest());
                }
            }
            //var customerFromDb = context.Customers.ToList().Find(c => c.CustomerId == customerId);
            //if (customerFromDb == null)
            //{
            //    return BadRequest();
            //}
            //customerFromDb.Birthday = customer.Birthday;
            //customerFromDb.Firstname = customer.Firstname;
            //customerFromDb.Lastname = customer.Lastname;
            //customerFromDb.HouseNumber = customer.HouseNumber;
            //customerFromDb.Street = customer.Street;
            //customerFromDb.Town = customer.Town;
            //customerFromDb.ZipCode = customer.ZipCode;
            //context.Customers.Update(customerFromDb);
            //await context.SaveChangesAsync();
            //return Ok(customerFromDb);
        }
Beispiel #11
0
        // GET api/<controller>/5
        public HttpResponseMessage Get(int id)
        {
            var myDbCustomer = myDb.Customers.Find(id);

            if (myDbCustomer == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found"));
            }

            var myApiCustomer = new ApiCustomer();

            PropertyCopier <Customer, ApiCustomer> .Copy(myDbCustomer, myApiCustomer);

            return(Request.CreateResponse(HttpStatusCode.OK, myApiCustomer));
        }
Beispiel #12
0
        public HttpResponseMessage PostCustomer([FromBody] ApiCustomer ac)
        {
            try
            {
                DBAccess.PostCustomer(ac);
            }
            catch (Exception e)
            {
                // ERROR
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Cannot create record." + e.Message));
            }

            // All OK
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Beispiel #13
0
        public HttpResponseMessage PutCustomer(int id, [FromBody] ApiCustomer ac)
        {
            try
            {
                // Persist our change.
                DBAccess.PutCustomer(id, ac);
            }
            catch (Exception e)
            {
                // ERROR
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Cannot update record: " + e));
            }

            // All OK
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public bool UpdateCustomer(ApiCustomer customer)
        {
            client.BaseAddress = new Uri("http://localhost:81/");

            var putTask = client.PutAsJsonAsync <ApiCustomer>("api/Customer/" + customer.CustomerId, customer);

            putTask.Wait();
            var result = putTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public bool CreateCustomer(ApiCustomer customer)
        {
            client.BaseAddress = new Uri("http://localhost:81/");

            var postTask = client.PostAsJsonAsync("api/Customer", customer);

            postTask.Wait();
            var result = postTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #16
0
        public ActionResult Create(FormCollection form)
        {
            ApiCustomer customer = new ApiCustomer();

            customer.CustomerFirstName = form["CustomerFirstName"];
            customer.CustomerLastName  = form["CustomerLastName"];
            customer.CustomerPhoneId   = Int32.Parse(form["CustomerPhoneId"]);
            customer.CustomerAddress   = form["CustomerAddress"];
            customer.CustomerDOB       = DateTime.Parse(form["CustomerDOB"]);
            if (!client.CreateCustomer(customer))
            {
                return(View(customer));
            }
            else
            {
                return(RedirectToAction("Customers"));
            }
        }
        public IActionResult Login([FromBody] LoginForm form)
        {
            if (ModelState.IsValid)
            {
                Customer customer = _repository.Login(form.Email, form.Passwd);

                if (customer is null)
                {
                    return(NoContent());
                }

                ApiCustomer apiCustomer = new ApiCustomer(customer);
                apiCustomer.Token = _tokenService.GenerateToken(customer);

                return(Ok(apiCustomer));
            }

            return(BadRequest());
        }
        public ApiCustomer SearchCustomerByUserName(string userName, string password)
        {
            ICustomerManager customerManager = UnityResolver.Resolve <ICustomerManager>();
            Customer         customer        = customerManager.SearchCustomerByUserName(userName, password);
            ApiCustomer      cust            = null;

            if (customer != null)
            {
                cust = new ApiCustomer
                {
                    ID       = customer.ID,
                    Name     = customer.Name,
                    Password = customer.Password,
                    UserName = customer.UserName
                };
            }

            return(cust);
        }
Beispiel #19
0
        public async Task <IActionResult> PutCustomer(string id, ApiCustomer apiCustomer)
        {
            var currentUserId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            if (id != currentUserId)
            {
                return(Unauthorized());
            }

            if (id != apiCustomer.UserId)
            {
                return(BadRequest());
            }

            var customer = new Customer()
            {
                Age          = apiCustomer.Age,
                Weight       = apiCustomer.Weight,
                FavMeal      = apiCustomer.FavMeal,
                UserId       = apiCustomer.UserId,
                CustomerName = apiCustomer.CustomerName
            };

            _context.Entry(customer).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(id))
                {
                    return(NotFound());
                }

                throw;
            }

            return(NoContent());
        }
Beispiel #20
0
        public IActionResult Login([FromBody] LoginForm form)
        {
            if (ModelState.IsValid)
            {
                Customer customer = _customerService.Login(form.Email, form.Password);

                if (customer is null)
                {
                    return(NotFound());
                }

                ApiCustomer apiCustomer = new ApiCustomer(customer)
                {
                    Token = _tokenService.GenerateToken(customer)
                };

                return(Ok(apiCustomer));
            }

            return(BadRequest());
        }
Beispiel #21
0
            public void OnAuthorization(AuthorizationFilterContext context)
            {
                ITokenService tokenService = (ITokenService)context.HttpContext.RequestServices.GetService(typeof(ITokenService));

                context.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues authorizations);
                string token = authorizations.SingleOrDefault(authorization => authorization.StartsWith("Bearer "));

                if (token is null)
                {
                    context.Result = new UnauthorizedResult();
                    return;
                }

                ApiCustomer customer = tokenService.ValidateToken(token);

                if (customer is null)
                {
                    context.Result = new UnauthorizedResult();
                    return;
                }

                context.RouteData.Values.Add("CustomerId", customer.CustomerId);
            }
        public HttpResponseMessage Get(int id)
        {
            try
            {
                var entity = db.Customers.Find(id);

                if (entity == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                       "Customer with Id " + id.ToString() + " not found."));
                }

                var myApiCustomer = new ApiCustomer();

                PropertyCopier <Customer, ApiCustomer> .Copy(entity, myApiCustomer);

                return(Request.CreateResponse(HttpStatusCode.OK, myApiCustomer));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                   "Error in the code"));
            }
        }
        public HttpResponseMessage Post([FromBody] ApiCustomer newCustomer)
        {
            if (ModelState.IsValid)
            {
                Customer c = new Customer();
                PropertyCopier <ApiCustomer, Customer> .Copy(newCustomer, c);

                db.Customers.Add(c);
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                       "Cannot add new Customer, Try again." + e.StackTrace + "---" + e.InnerException));
                }
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, "Customer added."));
        }
Beispiel #24
0
        public ActionResult Delete(int id)
        {
            ApiCustomer customer = client.GetCustomer(id);

            return(View(customer));
        }