Esempio n. 1
0
        public IActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new PandaUser
                {
                    UserName = model.Username,
                    Email    = model.Email,
                };

                var result = userManager.CreateAsync(user, model.Password).Result;

                if (result.Succeeded)
                {
                    IdentityRole role;

                    if (this.applicationDb.Users.Count() == 1)
                    {
                        role = this.applicationDb.Roles.FirstOrDefault(r => r.Name == "Administrator");
                    }
                    else
                    {
                        role = this.applicationDb.Roles.FirstOrDefault(r => r.Name == "User");
                    }

                    var addtoRoleResult = userManager.AddToRoleAsync(user, role.Name).Result;
                }

                return(RedirectToAction("Login", "Account"));
            }

            return(View());
        }
Esempio n. 2
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new PandaUser {
                    UserName = model.Username, Email = model.Email,
                };

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

                await createRoles(new string[] { "Admin", "User" });

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "User");

                    await this._signInManager.SignInAsync(user, false);

                    return(Redirect("/"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View());
        }
Esempio n. 3
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new PandaUser {
                    UserName = Input.Username, Email = Input.Email
                };

                //todo make admin
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");



                    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. 4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new PandaUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    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 _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. 5
0
 protected override IdentityUserLogin <string> CreateUserLogin(PandaUser user, UserLoginInfo login) =>
 new IdentityUserLogin <string>
 {
     UserId              = user.Id,
     ProviderKey         = login.ProviderKey,
     LoginProvider       = login.LoginProvider,
     ProviderDisplayName = login.ProviderDisplayName,
 };
Esempio n. 6
0
        protected override IdentityUserClaim <string> CreateUserClaim(PandaUser user, Claim claim)
        {
            var identityUserClaim = new IdentityUserClaim <string> {
                UserId = user.Id
            };

            identityUserClaim.InitializeFromClaim(claim);
            return(identityUserClaim);
        }
        public int CountOfAddressesPerUser(PandaUser user)
        {
            var count = pandaDbContext
                        .Addresses
                        .Where(a => a.IsDeleted == false)
                        .Count(a => a.UserId == user.Id);

            return(count);
        }
Esempio n. 8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new PandaUser {
                    UserName = Input.Username, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (_userManager.Users.Count() == 1)
                {
                    await _userManager.AddToRoleAsync(user, "Admin");
                }
                else
                {
                    await _userManager.AddToRoleAsync(user, "User");
                }
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    //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 = user.Id, code = code, returnUrl = returnUrl },
                    //    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>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        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. 9
0
        public async Task <PandaUser> GetUserByIdWithDeletedAsync(string id)
        {
            PandaUser userDb = await this.pandaDbContext
                               .Users
                               .Include(p => p.Addresses)
                               .FirstOrDefaultAsync
                                   (user =>
                                   user.Id == id);

            return(userDb);
        }
Esempio n. 10
0
        public Receipt CreateReceipt(Package package, PandaUser user)
        {
            var receipt = new Receipt()
            {
                Fee       = package.Weight * 2.67m,
                IssuedOn  = DateTime.UtcNow,
                Package   = package,
                Recipient = user
            };

            return(receipt);
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            IdentityResult result;

            returnUrl = returnUrl ?? this.Url.Content("~/");
            if (this.ModelState.IsValid)
            {
                var user = new PandaUser {
                    UserName = this.Input.Email, Email = this.Input.Email
                };
                if (!this.userManager.Users.Any())
                {
                    result = await this.userManager.CreateAsync(user, this.Input.Password);

                    var role = new PandaUserRole("Admin");
                    await this.userManager.AddToRoleAsync(user, "Admin");
                }
                else
                {
                    result = await this.userManager.CreateAsync(user, this.Input.Password);

                    await this.userManager.AddToRoleAsync(user, "User");
                }


                if (result.Succeeded)
                {
                    this.logger.LogInformation("User created a new account with password.");

                    var code = await this.userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = this.Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: this.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 this.signInManager.SignInAsync(user, isPersistent : false);

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

            // If we got this far, something failed, redisplay form
            return(this.Page());
        }
Esempio n. 12
0
        public async Task <bool> DeleteAccountAsync(PandaUser currentUser)
        {
            var user = await this.pandaDbContext.Users
                       .Where(u => u.Id == currentUser.Id).FirstOrDefaultAsync();

            user.IsDeleted          = true;
            user.UserName           = null;
            user.PasswordHash       = null;
            user.NormalizedUserName = null;

            await this.pandaDbContext.SaveChangesAsync();

            return(true);
        }
        public static PandaUser CreateUserSuccessPandaUser(DateTime dateTime)
        {
            PandaUser newAccount = new PandaUser
            {
                Email     = pandaUser.Email,
                FirstName = pandaUser.FirstName,
                LastName  = pandaUser.LastName,
                UserName  = pandaUser.Email,
                CreatedAt = dateTime,
                UpdatedAt = dateTime,
            };

            return(newAccount);
        }
        public CreateUserTest()
        {
            var mock = new MockRepository(MockBehavior.Default);

            _userRepoMocking = mock.Create <IUserRepository>();

            _userRepoMocking = new Mock <IUserRepository>();

            _userManagerMocking = new Mock <UserManager <PandaUser> >(
                new Mock <IUserStore <PandaUser> >().Object,
                new Mock <IOptions <IdentityOptions> >().Object,
                new Mock <IPasswordHasher <PandaUser> >().Object,
                new IUserValidator <PandaUser> [0],
                new IPasswordValidator <PandaUser> [0],
                new Mock <ILookupNormalizer>().Object,
                new Mock <IdentityErrorDescriber>().Object,
                new Mock <IServiceProvider>().Object,
                new Mock <ILogger <UserManager <PandaUser> > >().Object
                );

            _signInManagerMocking = new Mock <SignInManager <PandaUser> >(
                _userManagerMocking.Object,
                new Mock <IHttpContextAccessor>().Object,
                new Mock <IUserClaimsPrincipalFactory <PandaUser> >().Object,
                new Mock <IOptions <IdentityOptions> >().Object,
                new Mock <ILogger <SignInManager <PandaUser> > >().Object,
                new Mock <IAuthenticationSchemeProvider>().Object);


            _mapperMocking = new Mock <IMapper>();

            PandaUser nullUser = null;

            _userManagerMocking
            .Setup(s => s.FindByEmailAsync(TestDataCreateUserTest.pandaUser.Email))
            .Returns(Task.FromResult(nullUser));



            _userManagerMocking
            .Setup(s => s.CreateAsync(It.IsAny <PandaUser>(), TestDataCreateUserTest.pandaUser.Password))
            .Returns(Task.FromResult(IdentityResult.Success));

            userLogic = new UserLogic(
                _userManagerMocking.Object,
                _signInManagerMocking.Object,
                _userRepoMocking.Object,
                _mapperMocking.Object);
        }
Esempio n. 15
0
        public async Task <SignInResult> Register(AccountRegisterInputModel model)
        {
            var user = new PandaUser {
                UserName = model.Username, Email = model.Email
            };

            var registerResult = await this.userManager.CreateAsync(user, model.Password);

            if (!registerResult.Succeeded)
            {
                throw new Exception(string.Join(Environment.NewLine, registerResult.Errors));
            }

            var adminRoleExists = await this.roleManager.RoleExistsAsync("Admin");

            if (!adminRoleExists)
            {
                await this.roleManager.CreateAsync(new PandaUserRole { Name = "Admin" });
            }

            var userRoleExists = await this.roleManager.RoleExistsAsync("User");

            if (!userRoleExists)
            {
                await this.roleManager.CreateAsync(new PandaUserRole { Name = "User" });
            }

            var usersCount = this.userManager.Users.Count();

            if (usersCount == 1)
            {
                await this.userManager.AddToRoleAsync(user, "Admin");
            }
            else
            {
                await this.userManager.AddToRoleAsync(user, "User");
            }

            var loginModel = new AccountLoginInputModel
            {
                Username   = model.Username,
                Password   = model.Password,
                RememberMe = false
            };

            var result = await this.Login(loginModel);

            return(result);
        }
        public static PandaUser CreateUserFailPandaUser(DateTime dateTime)
        {
            PandaUser newAccount = new PandaUser
            {
                Email        = pandaUser.Email,
                FirstName    = pandaUser.FirstName,
                LastName     = pandaUser.LastName,
                UserName     = pandaUser.Email,
                CreatedAt    = dateTime,
                UpdatedAt    = dateTime,
                RefreshToken = "refresh token is have",
            };

            return(newAccount);
        }
Esempio n. 17
0
        protected override IdentityUserToken <string> CreateUserToken(
            PandaUser user,
            string loginProvider,
            string name,
            string value)
        {
            var token = new IdentityUserToken <string>
            {
                UserId        = user.Id,
                LoginProvider = loginProvider,
                Name          = name,
                Value         = value,
            };

            return(token);
        }
Esempio n. 18
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            //either that or homeUrl



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

                //todo: we add logic for admin here

                if (_userManager.Users.Count() == 1)
                {
                    await _userManager.AddToRoleAsync(user, "Admin");
                }
                else
                {
                    await _userManager.AddToRoleAsync(user, "User");
                }


                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    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. 19
0
        public void AcquirePackage(Package package, PandaUser user)
        {
            decimal Total = (decimal)package.Weight * 2.67m;

            Receipt receipt = new Receipt
            {
                Package     = package,
                PackageId   = package.Id,
                IssuedOn    = DateTime.Now,
                Recipient   = user,
                RecipientId = user.Id,
                Fee         = Total
            };

            package.Status = Status.Acquired;

            this.dbContext.Receipts.Add(receipt);
            this.dbContext.SaveChanges();
        }
Esempio n. 20
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var roleName = _context.Users.Any() ? "User" : "Administrator";
                var role     = await _roleManager.Roles.FirstOrDefaultAsync(r => r.Name.Equals(roleName));

                var user = new PandaUser()
                {
                    UserName = Input.Username, Email = Input.Email, Role = role
                };

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

                if (result.Succeeded)
                {
                    var roleResult = await _signInManager.UserManager.AddToRoleAsync(user, roleName);

                    if (roleResult.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                        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. 21
0
        public async Task <Results <long> > CreateUser(PandaUserContract account)
        {
            var emailValid = PandaValidator.EmailIsValid(account.Email);

            if (!emailValid)
            {
                return(PandaResponse.CreateErrorResponse <long>("Email Invalid"));
            }

            var user = await _userManager.FindByEmailAsync(account.Email);

            if (user != null)
            {
                return(PandaResponse.CreateSuccessResponse(user.Id));
            }

            var newAccount = new PandaUser
            {
                Email     = account.Email,
                FirstName = account.FirstName,
                LastName  = account.LastName,
                UserName  = account.Email,
                CreatedAt = now,
                UpdatedAt = now,
            };

            var result = await _userManager.CreateAsync(newAccount, account.Password);

            if (result.Succeeded)
            {
                return(PandaResponse.CreateSuccessResponse(newAccount.Id));
            }
            else
            {
                return(PandaResponse.CreateErrorResponse <long>(result.Errors.Select(s => s.Code + " : " + s.Description).ToArray()));
            }
        }
Esempio n. 22
0
 protected override IdentityUserRole <string> CreateUserRole(PandaUser user, PandaUserRole role)
 {
     return(new IdentityUserRole <string> {
         RoleId = role.Id, UserId = user.Id
     });
 }
Esempio n. 23
0
        public PandaUser GetUser(string username)
        {
            PandaUser userDb = this.pandaDbContext.Users.SingleOrDefault(user => user.UserName == username);

            return(userDb);
        }
Esempio n. 24
0
        public PandaUser GetUser(string userName)
        {
            PandaUser user = this.dbContext.Users.FirstOrDefault(u => u.UserName == userName);

            return(user);
        }
Esempio n. 25
0
 public async Task UpdateUserInfoAsync(PandaUser user)
 {
     this.pandaDbContext.Update(user);
     await this.pandaDbContext.SaveChangesAsync();
 }