Esempio n. 1
0
        private async Task <Cart> GetUserCart()
        {
            Cart cart = await _cartRepository.FindByUserWithoutItemsData(User.Identity.Name);

            if (cart == null)
            {
                _logger.LogInformation("Creating new cart for user - " + User.Identity.Name);
                ShopUser user = await _userRepository.GetUserWithEmail(User.Identity.Name);

                cart = new Cart
                {
                    User  = user,
                    Items = new List <CartItem>()
                };
                await _cartRepository.Insert(cart);
            }
            return(cart);
        }
        public async Task <IActionResult> RegisterAsync([FromBody] UserDto userDto)
        {
            ShopUser user = new ShopUser()
            {
                Name = userDto.Username
            };

            try
            {
                await _userService.Create(user, userDto.Password);

                return(Ok());
            }
            catch (ArgumentException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(ShopUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Esempio n. 4
0
        public static async Task SeedAdmin(ShopContext context, IServiceProvider services)
        {
            var userManager = services.GetRequiredService <UserManager <ShopUser> >();

            if (userManager.FindByNameAsync("admin") == null)
            {
                ShopUser admin = new ShopUser()
                {
                    UserName = "******"
                };

                await userManager.CreateAsync(admin, "adminpass");

                await userManager.AddToRoleAsync(admin, "Admin");

                await context.SaveChangesAsync();
            }
        }
        public async Task <Shop[]> AddPreferredShopAsync(int shopId, string userId)
        {
            if (_context.ShopUsers.Any(su => su.ShopId == shopId && su.UserId == userId))
            {
                return(await GetPreferredShopsAsync(userId));
            }
            var query = new ShopUser
            {
                ShopId = shopId,
                UserId = userId
            };

            await _context.ShopUsers.AddAsync(query);

            await _context.SaveChangesAsync();

            return(await GetPreferredShopsAsync(userId));
        }
        public async Task Register(RegisterInputModel model)
        {
            await this.SeedRoles();

            ShopUser user = new ShopUser
            {
                Id           = Guid.NewGuid().ToString(),
                UserName     = model.UserName,
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                PhoneNumber  = model.PhoneNumber,
                RegisteredOn = DateTime.UtcNow,
                Email        = model.Email,
                BirthDate    = model.BirthDate
            };

            if (this.userManager.Users.Any(u => u.UserName == user.UserName))
            {
                throw new InvalidOperationException("Username is already taken.");
            }
            else if (this.userManager.Users.Any(u => u.Email == user.Email))
            {
                throw new InvalidOperationException("Email already exists.");
            }

            IdentityResult result = await this.userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException("Failed to register user.");
            }

            // the first registered user is the administrator
            if (this.dbContext.Users.Count() == 1)
            {
                await this.userManager.AddToRoleAsync(user.Id, RolesConstants.Administrator);
            }
            else if (this.dbContext.Users.Count() > 1)
            {
                await this.userManager.AddToRoleAsync(user.Id, RolesConstants.User);
            }

            await this.signInManager.PasswordSignInAsync(user.UserName, model.Password, true, false);
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var isRoot = !_userManager.Users.Any();
                var user   = new ShopUser {
                    UserName = Input.Username, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    if (isRoot)
                    {
                        await _userManager.AddToRoleAsync(user, "Admin");
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "User");
                    }

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Page(
                    //    "/Account/ConfirmEmail",
                    //    pageHandler: null,
                    //    values: new { userId = user.Id, code = code },
                    //    protocol: Request.Scheme);
                    //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 8
0
        public async Task <object> GetJWT(string userName)
        {
            ShopUser user = await _users.GetUserByUserName(userName);

            if (user != null)
            {
                var tokenTimeCreated = DateTime.UtcNow;

                var userRoles = await _users.GetUserRoles(user);

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim("ShopCartId", user.ShopCartId.ToString())
                };

                foreach (string role in userRoles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }

                string secretKey = _jwtOptions.Value.Key;
                int    expires   = _jwtOptions.Value.Expires;

                var jwt = new JwtSecurityToken(
                    issuer: "Me",
                    audience: "My Api",
                    notBefore: tokenTimeCreated,
                    claims: claims,
                    expires: tokenTimeCreated.AddMinutes(expires),
                    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(
                                                                   Encoding.ASCII.GetBytes(secretKey)),
                                                               SecurityAlgorithms.HmacSha256));

                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                return(encodedJwt);
            }
            else
            {
                throw new ArgumentNullException();
            }
        }
        public async Task ExternalLogin()
        {
            var info = await this._signInManager.GetExternalLoginInfoAsync();

            var email = info.Principal.Claims.First(x => x.Type.EndsWith("/emailaddress")).Value;

            var user = new ShopUser
            {
                UserName = email,
                Email    = email
            };

            if (!(this._dbContext.Users.Any(x => x.UserName == user.UserName)))
            {
                var createUserResult = await _userManager.CreateAsync(user);

                if (createUserResult.Succeeded)
                {
                    if (this._dbContext.Users.Any())
                    {
                        await this._userManager.AddToRoleAsync(user, RolesConstants.User);
                    }
                    else
                    {
                        await this._userManager.AddToRoleAsync(user, RolesConstants.Administrator);
                    }

                    createUserResult = await _userManager.AddLoginAsync(user, info);

                    if (createUserResult.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);
                    }
                }
                else
                {
                    throw new InvalidOperationException("Invalid email address.");
                }
            }

            var result =
                await this._signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false, true);
        }
Esempio n. 10
0
        public void Ready()
        {
            var id = 0;

            if (!int.TryParse(ServerSerialNo, out id))
            {
                return;
            }

            DealLog = DealLogService.GetById(id);
            if (DealLog == null)
            {
                return;
            }
            if (DealLog.State != DealLogStates.Normal || DealLog.DealType != DealTypes.Deal)
            {
                DealLog = null;
                return;
            }
            var       user      = SecurityHelper.GetCurrentUser().CurrentUser;
            AdminUser adminUser = user as AdminUser;

            if (adminUser != null)
            {
                if (DealLog.SourceShopName != Constants.SystemShopName)
                {
                    DealLog = null;
                    return;
                }
            }
            ShopUser shopUser = user as ShopUser;

            if (shopUser != null)
            {
                var shop = ShopService.GetById(shopUser.ShopId);
                if (DealLog.SourceShopName != shop.Name)
                {
                    DealLog = null;
                    return;
                }
            }
        }
Esempio n. 11
0
        private async Task LoadAsync(ShopUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                FirstName   = user.FirstName,
                LastName    = user.LastName,
                City        = user.City,
                Street      = user.Street,
                PostalCode  = user.PostalCode,
                State       = user.State,
                Country     = user.Country,
                PhoneNumber = phoneNumber
            };
        }
Esempio n. 12
0
        public ShopUser CreateShopUser(
            string username, string password, string email)
        {
            var user = new ShopUser {
                Name     = username,
                Password = password,
                Email    = email
            };
            Role userRole = _context.ShopRoles.FirstOrDefault(r => r.Name == USER_ROLE);

            if (userRole != null)
            {
                user.Role = userRole;
            }

            _context.ShopUsers.Add(user);
            _context.SaveChangesAsync();

            return(user);
        }
Esempio n. 13
0
        public async Task <IActionResult> Edit(string userId)
        {
            ShopUser user = await _userManager.FindByIdAsync(userId);

            if (user != null)
            {
                var userRoles = await _userManager.GetRolesAsync(user);

                var allRoles = _roleManager.Roles.ToList();
                ChangeRoleViewModel model = new ChangeRoleViewModel
                {
                    UserId    = user.Id,
                    UserName  = user.UserName,
                    UserRoles = userRoles,
                    AllRoles  = allRoles
                };
                return(View(model));
            }
            return(NotFound());
        }
Esempio n. 14
0
        public async Task <IActionResult> Edit(string userId, List <string> roles)
        {
            ShopUser user = await _userManager.FindByIdAsync(userId);

            if (user != null)
            {
                var userRoles = await _userManager.GetRolesAsync(user);

                var allRoles    = _roleManager.Roles.ToList();
                var addRoles    = roles.Except(userRoles);
                var removeRoles = userRoles.Except(roles);

                await _userManager.AddToRolesAsync(user, addRoles);

                await _userManager.RemoveFromRolesAsync(user, removeRoles);

                return(RedirectToAction("UserList"));
            }
            return(NotFound());
        }
        public ActionResult Signup(ShopUser user)
        {
            try
            {
                domainIndentifier = new DomainIdentifier(Request.Url.Host, Request.ServerVariables["SERVER_NAME"]);
                User User = domainIndentifier.GetUserRelatedDomain();
                UserID = User != null ? User.Id : 0;
                Menu UserData = db.Menus.FirstOrDefault(x => x.Name == "Index" && x.UserID == UserID);
                ViewBag.UserID           = UserID;
                Session["CurrentUserID"] = UserID;


                if (ModelState.IsValid)
                {
                    var isUserExist = db.ShopUsers.FirstOrDefault(x => x.Email == user.Email.ToLower() && x.UserID == UserID);
                    if (isUserExist != null)
                    {
                        TempData["Msg"] = "<p class='text-danger text-center'>Sorry! This Email is already register with us.</p>";
                    }
                    else
                    {
                        user.UserID          = UserID;
                        user.CreatedDateTime = DateTime.UtcNow;
                        user.Email           = user.Email.ToLower();
                        db.ShopUsers.Add(user);
                        db.SaveChanges();
                        TempData["Msg"] = "<p class='text-success text-center'>Account has been created succesfully! Please Login.</p>";
                        return(RedirectToAction("Login"));
                    }
                }
                else
                {
                    TempData["Msg"] = "<p class='text-danger text-center'>Please fill required fileds!</p>";
                }
            }
            catch
            {
                TempData["Msg"] = "<p class='text-danger text-center'>Sorry! There is an error. Please try again.</p>";
            }
            return(View());
        }
Esempio n. 16
0
 protected void OnSave(Shop shop, ShopUser owner)
 {
     if (!string.IsNullOrWhiteSpace(HostSite.MessageTemplateOfIdentity))
     {
         var code   = CodeHelper.GetObject <string>("sms", false);
         var mobile = CodeHelper.GetObject <string>("sms_mobile", false);
         // 校验成功
         if (!string.IsNullOrWhiteSpace(code) && code == this.Mobile.Code)
         {
             // 校验成功,并且提交号码和校验号码相同,则为绑定
             if (this.Mobile.Value1 == mobile)
             {
                 owner.Mobile            = mobile;
                 owner.IsMobileAvailable = true;
             }
             else // 否则为取消绑定
             {
                 owner.Mobile            = "";
                 owner.IsMobileAvailable = false;
             }
         }
     }
     else
     {
         owner.Mobile            = this.Mobile.Value1;
         owner.IsMobileAvailable = !string.IsNullOrWhiteSpace(owner.Mobile);
     }
     owner.Mobile2        = Mobile.Value2;
     shop.Description     = Description;
     shop.BankUserName    = BankUserName;
     shop.BankAccountName = BankAccountName;
     shop.DealWayId       = DealWay;
     shop.Mobile          = owner.Mobile;
     shop.Mobile2         = owner.Mobile2;
     shop.PhoneNumber     = PhoneNumber.Value1;
     shop.PhoneNumber2    = PhoneNumber.Value2;
     shop.Bank            = HostSite.GetBank(this.Bank);
     shop.BankPoint       = BankPoint;
     shop.Address         = this.Address;
 }
Esempio n. 17
0
        public ProfileViewModel GetProfileInfo(string username)
        {
            ShopUser userEntity = this.GetUserByName(username);

            if (userEntity == null)
            {
                throw new InvalidOperationException("Invalid user!");
            }

            ProfileViewModel profileModel = new ProfileViewModel
            {
                FirstName    = userEntity.FirstName,
                LastName     = userEntity.LastName,
                BirthDate    = userEntity.BirthDate,
                EmailAddress = userEntity.Email,
                Orders       = userEntity.Orders?.Take(5),
                PhoneNumber  = userEntity.PhoneNumber,
                RegisteredOn = userEntity.RegisteredOn
            };

            return(profileModel);
        }
Esempio n. 18
0
        public void Ready()
        {
            var request = new ShopRequest()
            {
                State = ShopStates.Normal
            };


            var      currentUser = SecurityHelper.GetCurrentUser();
            ShopUser shopUser    = currentUser.CurrentUser as ShopUser;

            if (shopUser != null)
            {
                request.ShopId = shopUser.ShopId;
            }
            var query = ShopService.Query(request);

            this.Shop.Bind(query.Select(x => new IdNamePair()
            {
                Key = x.ShopId, Name = x.DisplayName
            }), true);
        }
Esempio n. 19
0
        public async Task <Result <string> > Handle(UserRegisterCommand request, CancellationToken cancellationToken)
        {
            var user = new ShopUser {
                UserName = request.Login, Email = request.Email
            };
            var result = await _userManager.CreateAsync(user, request.Password);

            if (!result.Succeeded)
            {
                return(Result.Failure <string>(JsonConvert.SerializeObject(result.Errors, Formatting.None)));
            }
            var userFromDb = await _userManager.FindByNameAsync(request.Login);

            await _userManager.AddToRoleAsync(userFromDb, Roles.USER);

            var refreshToken = _tokenFactory.GenerateToken();
            await _userManager.RemoveAuthenticationTokenAsync(user, "Shop", "RefreshToken");

            await _userManager.SetAuthenticationTokenAsync(userFromDb, "Shop", "RefreshToken", refreshToken);

            return(Result.Success("User created"));
        }
Esempio n. 20
0
        /// <summary>
        /// Создание пользователя.
        /// </summary>
        /// <param name="userDto"></param>
        /// <returns></returns>
        public async Task <OperationDetails> Create(UserDTO userDto)
        {
            ApplicationUser user = await db.UserManager.FindByEmailAsync(userDto.Email);

            if (user == null)
            {
                //создаем пользователя
                user = new ApplicationUser {
                    Email = userDto.Email, UserName = userDto.UserName
                };
                var result = await db.UserManager.CreateAsync(user, userDto.Password);

                if (result.Errors.Count() > 0)
                {
                    return(new OperationDetails(false, result.Errors.FirstOrDefault(), ""));
                }
                //добавляем пользователю роль
                await db.UserManager.AddToRoleAsync(user.Id, userDto.Role);

                //создаём профиль пользователя
                ShopUser shopUser = new ShopUser
                {
                    Id           = user.Id,
                    UserName     = userDto.UserName,
                    Email        = userDto.Email,
                    Role         = userDto.Role,
                    RegisterDate = DateTime.Now
                };
                db.Users.Add(shopUser);
                await db.SaveAsync();

                return(new OperationDetails(true, "Регистрация успешно завершена", ""));
            }
            else
            {
                return(new OperationDetails(false, "Пользователь с таким email уже существует", "Email"));
            }
        }
Esempio n. 21
0
        public async Task <ShopUser> RegisterUser(RegisterDto register)
        {
            if (!(await _shopUsers.AnyAsync(x => x.Email == register.Email || x.PhoneNumber == register.Phone)))
            {
                ShopUser shopUser = new ShopUser()
                {
                    FullName    = register.FullName,
                    Email       = register.Email,
                    PhoneNumber = register.Phone,
                    CompanyName = "",
                    Password    = register.Password
                };
                await _shopUsers.AddAsync(shopUser);

                await _context.SaveChangesAsync();

                return(_shopUsers.FirstOrDefault(x => x.Email == register.Email));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 22
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            UserModel userModel;

            if (filterContext.Controller.ViewBag.UserModel == null)
            {
                userModel = new UserModel();
                filterContext.Controller.ViewBag.UserModel = userModel;
            }
            else
            {
                userModel = filterContext.Controller.ViewBag.UserModel as UserModel;
            }
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                ShopUser ShopUser = filterContext.HttpContext.User.GetShopUser();
                userModel.IsUserAuthenticated = ShopUser.IsAuthenticated;
                userModel.UserName            = ShopUser.DisplayName;
                userModel.RoleName            = ShopUser.RoleName;
            }

            base.OnActionExecuted(filterContext);
        }
Esempio n. 23
0
        public async Task <IActionResult> SignUp(SignUpViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ShopUser
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    Cart     = new Cart()
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (model.Role == "Admin")
                    {
                        await _userManager.AddToRoleAsync(user, "Admin");
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "User");
                    }

                    await _signInManager.SignInAsync(user, false);

                    return(RedirectToAction("index", "home"));
                }

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

            return(View(model));
        }
Esempio n. 24
0
        public ActionResult Index()
        {
            //co quyen moi duoc xem
            if (!CheckRole(_httpContext, int.Parse(Roles.Phan_Quyen_View)))
            {
                return(View("_NoAuthor"));
            }

            ShopUser           userLogin             = _httpContext.User.GetShopUser();
            IList <Account298> account298s           = _account298Repository.GetAll().ToList();
            IList <PhanQuyenModel.QuyenModel> models = new List <PhanQuyenModel.QuyenModel>();
            IList <RoleList> roles = Roles.GetRoles();

            if (account298s.Any())
            {
                foreach (var account298 in account298s)
                {
                    //cat tu chuoi sang list int
                    IList <int> ids = !string.IsNullOrEmpty(account298.Roles)
                                         ? account298.Roles.Split(',').Select(o => Convert.ToInt32(o)).ToList()
                                         : new List <int>();

                    IList <RoleList> QuyenUsers = (from roleList in roles
                                                   where ids.Contains(roleList.Id)
                                                   select roleList).ToList();

                    IList <string> tens = QuyenUsers.Select(o => o.Name).ToList();
                    models.Add(new PhanQuyenModel.QuyenModel()
                    {
                        NhanVienId  = account298.id_,
                        TenNhanVien = account298.Fullname,
                        Quyen       = string.Join(",", tens)
                    });
                }
            }
            return(View(models));
        }
Esempio n. 25
0
        //public bool EmailExists(string email)
        //{
        //    var emailExists = this.dbService.DbContext.Users.Any(u => u.Email == email);

        //    return emailExists;
        //}

        private IdentityResult OnPostRegister(IRegisterInputModel viewModel, string password)
        {
            var model = new ShopUser
            {
                UserName  = viewModel.Username,
                Email     = viewModel.Email,
                BirthDate = viewModel.BirthDate
            };

            var result = userManager.CreateAsync(model, password).GetAwaiter().GetResult();

            if (result.Succeeded)
            {
                if (this.dbService.DbContext.Users.Count() == 1)
                {
                    this.userManager.AddToRoleAsync(model, Role.Owner).GetAwaiter().GetResult();
                }
                else if (this.dbService.DbContext.Users.Count() == 2)
                {
                    this.userManager.AddToRoleAsync(model, Role.Administrator).GetAwaiter().GetResult();
                }
                else
                {
                    this.userManager.AddToRoleAsync(model, Role.User).GetAwaiter().GetResult();
                }

                //if (viewModel.Image != null)
                //{
                //    this.profileService.UploadProfilePicture(viewModel.Image, viewModel.Username);
                //}

                signInManager.SignInAsync(model, isPersistent: false).GetAwaiter().GetResult();
            }


            return(result);
        }
Esempio n. 26
0
        public async Task <IActionResult> ChangeRole([FromBody] RoleChangeRequest request)
        {
            _logger.LogInformation($"Changing role of user with email ${request.Email} to ${request.Role}");

            ShopUser user = await _userManager.FindByEmailAsync(request.Email);

            if (user == null)
            {
                _logger.LogInformation($"Role changing failed, no user with such email found");
                return(StatusCode((int)HttpStatusCode.NotFound,
                                  new ErrorResponse(ErrorReasons.NotFound, "User was not found")));
            }

            try
            {
                UserRole role = (UserRole)Enum.Parse(typeof(UserRole), request.Role);
            }
            // happens if role string cannot be parsed
            catch (ArgumentException)
            {
                _logger.LogInformation($"Role changing failed, bad role provided");
                return(StatusCode((int)HttpStatusCode.BadRequest,
                                  new ErrorResponse(ErrorReasons.BadRequest, "Provided role does not exist")));
            }

            IList <string> roles = await _userManager.GetRolesAsync(user);

            await _userManager.RemoveFromRolesAsync(user, roles);

            await _userManager.AddToRoleAsync(user, request.Role);

            await _userManager.UpdateSecurityStampAsync(user);

            _logger.LogInformation($"Role succesfully changed");
            return(StatusCode((int)HttpStatusCode.NoContent));
        }
Esempio n. 27
0
        public static async Task InitializeAsync(UserManager <ShopUser> userManager, RoleManager <IdentityRole> roleManager, WebShopContext context)
        {
            string adminEmail = "*****@*****.**";
            string adminName  = "admin";
            string password   = "******";

            if (await roleManager.FindByNameAsync("admin") == null)
            {
                await roleManager.CreateAsync(new IdentityRole("admin"));
            }
            if (await roleManager.FindByNameAsync("moderator") == null)
            {
                await roleManager.CreateAsync(new IdentityRole("moderator"));
            }

            if (await roleManager.FindByNameAsync("user") == null)
            {
                await roleManager.CreateAsync(new IdentityRole("user"));
            }

            if (await roleManager.FindByNameAsync(adminEmail) == null)
            {
                ShopUser admin = new ShopUser {
                    Email = adminEmail, UserName = adminName
                };
                context.Carts.Add(new Cart {
                    ShopUser = admin
                });
                IdentityResult result = await userManager.CreateAsync(admin, password);

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(admin, "admin");
                }
            }
        }
Esempio n. 28
0
        //инициализация ролей и админа в Identity
        public async Task Init()
        {
            ApplicationRole userRole = new ApplicationRole {
                Name = "User"
            };
            ApplicationRole modRole = new ApplicationRole {
                Name = "Moderator"
            };
            ApplicationRole adminRole = new ApplicationRole {
                Name = "Admin"
            };
            await db.RoleManager.CreateAsync(userRole);

            await db.RoleManager.CreateAsync(modRole);

            await db.RoleManager.CreateAsync(adminRole);

            ApplicationUser admin = new ApplicationUser {
                Email = "*****@*****.**", UserName = "******"
            };
            await db.UserManager.CreateAsync(admin, "123456");

            await db.UserManager.AddToRoleAsync(admin.Id, "Admin");

            ShopUser adminProfile = new ShopUser
            {
                Id           = admin.Id,
                UserName     = admin.UserName,
                Email        = admin.Email,
                RegisterDate = DateTime.Now,
                Role         = "Admin"
            };

            db.Users.Add(adminProfile);
            await db.SaveAsync();
        }
Esempio n. 29
0
        /// <inheritdoc />
        public async Task <bool> ChangeCount(ShopUser user, ItemAmountChangeRequest request)
        {
            if (user == null)
            {
                throw new Exception();
            }

            var item = await items.SingleAsync(s => s.Id == request.Id);

            if ((request.Amount < 0 && Math.Abs(request.Amount) > item.Count))//Avoid negative numbers
            {
                throw new ArgumentException("You can't change an Item's count below zero!");
            }

            item.Count += request.Amount;

            items.Update(item);

            var returnamount = await context.SaveChangesAsync() > 0;

            await LogItem(user, item, request.Amount);

            return(returnamount);
        }
Esempio n. 30
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ShopUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }