public async Task <IActionResult> PutLineItem(int id, LineItem lineItem)
        {
            // NLog
            string message = $"(API Server) -Try to PUT (update) LineItem " + id + "(Id) - Controller : LineItemsController; " +
                             "Actionname: PutLineItem(...); HTTP method : HttpPut; Time: " + DateTime.Now + "\n";

            _logger.Info(message);

            try
            {
                _context.Entry(lineItem).State = EntityState.Modified;
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                // NLog Framework Call

                // LOG INFO
                _logger.Info("INFORMATION DETAILS, Exception occured during operation : " + message);
                _logger.Info("EXCEPTION DETAILS: " + ex.Message + "\n");

                // LOG WARN
                _logger.Warn("WARNING DETAILS, Exception occured during operation : " + message);
                _logger.Warn("EXCEPTION DETAILS: " + ex.Message + "\n");


                // LOG ERROR
                _logger.Error("ERROR DETAILS, Exception occured during operation : " + message);
                _logger.Error("EXCEPTION DETAILS: " + ex.Message + "\n");


                // LOG TRACE
                _logger.Trace("WARNING DETAILS, Exception occured during operation : " + message);
                _logger.Trace("EXCEPTION DETAILS: " + ex.Message + "\n");


                // LOG FATAL
                _logger.Fatal("FATAL DETAILS, Exception occured during operation : " + message);
                _logger.Fatal("EXCEPTION DETAILS: " + ex.Message + "\n");


                // LOG DEGUG
                _logger.Debug("DEGUG DETAILS, Exception occured during operation : " + message);
                _logger.Debug("EXCEPTION DETAILS: " + ex.Message + "\n");

                if (id != lineItem.Id)
                {
                    return(BadRequest());
                }
                else if (!LineItemExists(id))
                {
                    return(NotFound());
                }

                return(NotFound());
            }

            return(NoContent());
        }
        public async Task <ActionResult <ShoppingCart> > PostShoppingCart(ShoppingCart shoppingCart)
        {
            // NLog
            string message = $"(API Server) -Try to POST ShoppingCart " + shoppingCart.Id + " (Id) - Controller : ShoppingCartsController; " +
                             "Actionname: PostShoppingCart(...); HTTP method : HttpPost; Time: " + DateTime.Now + "\n";

            _logger.Info(message);

            try
            {
                _context.ShoppingCarts.Add(shoppingCart);
                await _context.SaveChangesAsync();

                _context.Entry(shoppingCart).GetDatabaseValues();

                return(CreatedAtAction("GetShoppingCarts", new { id = shoppingCart.Id }, shoppingCart));
            }
            catch (Exception ex)
            {
                // NLog Framework Call

                // LOG INFO
                _logger.Info("INFORMATION DETAILS, Exception occured during operation : " + message);
                _logger.Info("EXCEPTION DETAILS: " + ex.Message + "\n");

                // LOG WARN
                _logger.Warn("WARNING DETAILS, Exception occured during operation : " + message);
                _logger.Warn("EXCEPTION DETAILS: " + ex.Message + "\n");

                // LOG ERROR
                _logger.Error("ERROR DETAILS, Exception occured during operation : " + message);
                _logger.Error("EXCEPTION DETAILS: " + ex.Message + "\n");

                // LOG TRACE
                _logger.Trace("WARNING DETAILS, Exception occured during operation : " + message);
                _logger.Trace("EXCEPTION DETAILS: " + ex.Message + "\n");

                // LOG FATAL
                _logger.Fatal("FATAL DETAILS, Exception occured during operation : " + message);
                _logger.Fatal("EXCEPTION DETAILS: " + ex.Message + "\n");

                // LOG DEGUG
                _logger.Debug("DEGUG DETAILS, Exception occured during operation : " + message);
                _logger.Debug("EXCEPTION DETAILS: " + ex.Message + "\n");

                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
Exemple #3
0
        public async Task <IActionResult> DeleteUser(string id)
        {
            var user = await userManager.FindByIdAsync(id);

            if (user == null)
            {
                ViewBag.ErrorMessage = $"L'utilisateur avec l'ID : {id} est introuvable";
                return(View("NotFound"));
            }
            else
            {
                var IdShopcart = (from i in _context.ShoppingCarts
                                  where i.UserId == id
                                  select i.Id).First();
                var ShopCart = await _context.ShoppingCarts.FindAsync(IdShopcart);

                _context.ShoppingCarts.Remove(ShopCart);

                var IdWishList = (from i in _context.Wishlists
                                  where i.UserId == id
                                  select i.Id).First();
                var WishList = await _context.Wishlists.FindAsync(IdWishList);

                _context.Wishlists.Remove(WishList);

                await _context.SaveChangesAsync();

                var result = await userManager.DeleteAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectToAction("ListUsers"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }

                return(View("ListUsers"));
            }
        }
        private async Task <ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims)
        {
            // create a list of claims that we want to transfer into our store
            var filtered = new List <Claim>();

            // user's display name
            var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                       claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            if (name != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Name, name));
            }
            else
            {
                var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
                else if (first != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first));
                }
                else if (last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, last));
                }
            }

            // email
            var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                        claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            if (email != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Email, email));
            }

            var customer = new Customer
            {
                Firstname = claims.FirstOrDefault(x => x.Type.Contains("givenname")).Value,
                Lastname  = claims.FirstOrDefault(x => x.Type.Contains("surname")).Value,
                City      = claims.FirstOrDefault(x => x.Type.Contains("urn:facebook:location")).Value
            };

            _context.Customers.Add(customer);
            await _context.SaveChangesAsync();

            var user = new ApplicationUser
            {
                UserName   = ("fb_" + claims.FirstOrDefault(x => x.Type.Contains("givenname")).Value).ToLower(),
                IdCustomer = customer.Id,
                Email      = claims.FirstOrDefault(x => x.Type.Contains("email")).Value
            };

            var services = new ServiceCollection();

            services.AddLogging();
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Startup.ConnectionString));
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            var serviceProvider = services.BuildServiceProvider();
            var scope           = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope();
            var context         = scope.ServiceProvider.GetService <ApplicationDbContext>();
            var userMgr         = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();

            ApplicationUser checkUserMail = userMgr.FindByEmailAsync(user.Email).Result;

            if (checkUserMail == null)
            {
                var identityResult = await _userManager.CreateAsync(user);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }

                if (filtered.Any())
                {
                    identityResult = await _userManager.AddClaimsAsync(user, filtered);

                    if (!identityResult.Succeeded)
                    {
                        throw new Exception(identityResult.Errors.First().Description);
                    }
                }

                identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }

                ShoppingCart sp = new ShoppingCart
                {
                    UserId      = user.Id,
                    CreatedDate = DateTime.Now
                };
                _context.ShoppingCarts.Add(sp);
                await _context.SaveChangesAsync();

                Wishlist wl = new Wishlist
                {
                    UserId      = user.Id,
                    CreatedDate = DateTime.Now
                };
                _context.Wishlists.Add(wl);
                await _context.SaveChangesAsync();
            }
            else
            {
                return(null);
            }

            return(user);
        }
Exemple #5
0
        public async System.Threading.Tasks.Task <IActionResult> CreateDoneAsync(CreateUserViewModel createUserViewModel)
        {
            ApplicationUser user = new ApplicationUser
            {
                UserName     = createUserViewModel.UserName,
                PasswordHash = createUserViewModel.PasswordHash,
                Email        = createUserViewModel.Email,
                PhoneNumber  = createUserViewModel.CountryCode + createUserViewModel.PhoneNumber
            };

            var services = new ServiceCollection();

            services.AddLogging();
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Startup.ConnectionString));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            using (var serviceProvider = services.BuildServiceProvider())
            {
                using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    var context = scope.ServiceProvider.GetService <ApplicationDbContext>();

                    var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();

                    if (user.UserName == null)
                    {
                        resView = "ErrorUserName";
                    }
                    else
                    {
                        var checkUser = userMgr.FindByEmailAsync(user.Email).Result;
                        if (checkUser == null)
                        {
                            Customer newCust = new Customer();
                            _context.Customers.Add(newCust);
                            await _context.SaveChangesAsync();

                            user.IdCustomer = _context.Customers.Max(u => u.Id);

                            checkUser = user;
                            var result = userMgr.CreateAsync(checkUser, user.PasswordHash).Result;
                            if (checkUser.UserName.Contains("alice"))
                            {
                                if (await _roleManager.RoleExistsAsync("Admin"))
                                {
                                    await _roleManager.CreateAsync(new IdentityRole("Admin"));
                                }
                                await userMgr.AddToRoleAsync(checkUser, "Admin");
                            }
                            else
                            {
                                if (await _roleManager.RoleExistsAsync("User"))
                                {
                                    await _roleManager.CreateAsync(new IdentityRole("User"));
                                }
                                await userMgr.AddToRoleAsync(checkUser, "User");
                            }

                            if (!result.Succeeded)
                            {
                                resView = "ErrorPassword";
                            }
                            else
                            {
                                Log.Debug($"{checkUser.UserName} created");

                                ShoppingCart sp = new ShoppingCart
                                {
                                    UserId      = checkUser.Id,
                                    CreatedDate = DateTime.Now
                                };
                                _context.ShoppingCarts.Add(sp);
                                await _context.SaveChangesAsync();

                                Wishlist wl = new Wishlist
                                {
                                    UserId      = checkUser.Id,
                                    CreatedDate = DateTime.Now
                                };
                                _context.Wishlists.Add(wl);
                                await _context.SaveChangesAsync();


                                var code = await userMgr.GenerateEmailConfirmationTokenAsync(checkUser);

                                var callbackUrl = Url.Action("ConfirmEmailAsync", "ApplicationUser", new EmailConfirmViewModel {
                                    UserId = checkUser.Id, code = code
                                }, "http");
                                string      subject = "Confirmez votre email";
                                string      body    = "Cliquez sur ce lien pour confirmmer votre email: <a href='" + callbackUrl + "'>Reinit</a>";
                                EmailSender es      = new EmailSender(_configuration["sendgridApi"], _configuration["email"]);
                                es.SendEmail(checkUser.Email, subject, body);

                                resView = "CreateDone";
                            }
                        }
                        else
                        {
                            Log.Debug($"{checkUser.UserName} already exists");
                        }
                    }
                }
            }
            return(View(resView));
        }