예제 #1
0
        public async Task <IActionResult> Register(UserForRegisterDto model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Index", model));
            }

            var user = new AppIdentityUser
            {
                FirstName   = model.FirstName,
                LastName    = model.LastName,
                Email       = model.Email,
                DateOfBirth = model.DateOfBirth,
                Gender      = true,
                UserName    = model.Email
            };

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

            //var result1 = await _signInManager.PasswordSignInAsync(user, model.Password, false, false);
            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Home"));
            }
            return(View("Index"));
        }
예제 #2
0
        public async Task <IActionResult> Create(UserCreateModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityUser user = new AppIdentityUser
                {
                    UserName     = model.Name,
                    Email        = model.Email,
                    RegisterDate = DateTime.Now,
                    UserImage    = "/images/photo2.png"
                };
                IdentityResult result
                    = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(PartialView("~/Areas/AppIdentity/Views/UserAdmin/Create.cshtml", model));
        }
        public async Task <string> CreateToken(AppIdentityUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
            };

            var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256Signature);

            var getTime = DateTime.UtcNow;

            var utc7Time = Helper.ConvertUTCToTimeZone(getTime, Helper.idTimeZoneUtc7);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = utc7Time.AddMonths(6),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var test  = await _userManager.FindByIdAsync(user.Id);

            //Create refresh token
            user.RefreshToken = Guid.NewGuid().ToString();
            var result = await _userManager.UpdateAsync(user);

            return(tokenHandler.WriteToken(token));
        }
예제 #4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var user = new AppIdentityUser {
                    UserName = Input.Username
                };
                var result = await _identityUserManager.CreateAsync(user, Input.Password);

                if (result != null && result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, true);

                    return(RedirectToAction(nameof(HomeController.Dashboard), "Home"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }

            return(Page());
        }
예제 #5
0
        public async Task Impersonate(AppIdentityUser user)
        {
            var httpContext = _httpContextAccessor?.HttpContext;

            if (httpContext == null)
            {
                return;
            }

            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            var currentUserId = GetCurrentUserId();
            var identity      = principal.Identities.First();

            if (currentUserId.HasValue)
            {
                await _signInManager.SignOutAsync();
            }

            var id = user.Id;

            identity.AddClaim(new Claim(ClaimTypes.UserData, id.ToString()));
            await httpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);

            httpContext.User = principal;
            httpContext.Items[CurrentUserIdKey] = id;
            httpContext.Items[CurrentUserKey]   = user;
        }
예제 #6
0
        public async Task <IActionResult> VerifyEmailChange(string userId, string newEmail, string code)
        {
            AppIdentityUser user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound());
            }
            try
            {
                IdentityResult result = await _userManager.ChangeEmailAsync(user, newEmail, code);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user : user, isPersistent : false);

                    return(RedirectToAction(actionName: "ChangeConfirm"));
                }
            }
            catch (Exception ex)
            {
                return(NotFound());
            }
            return(NotFound());
        }
예제 #7
0
        public async Task <IActionResult> Login(LoginAccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityUser userLogin = await _userManager.FindByEmailAsync(model.Email);

                if (userLogin == null)
                {
                    return(NotFound());
                }
                var result = await _signInManager.PasswordSignInAsync(user : userLogin,
                                                                      password : model.Password,
                                                                      isPersistent : model.IsRemember,
                                                                      lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    if (!String.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    return(RedirectToAction(actionName: "Index", controllerName: "Home"));
                }
                ModelState.AddModelError("", "Something was wrong, please check again");
            }
            return(View(model));
        }
예제 #8
0
        public async Task <IActionResult> VerifyEmail(string userId, string code)
        {
            AppIdentityUser user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound());
            }
            if (!user.EmailConfirmed)
            {
                try
                {
                    IdentityResult result = await _userManager.ConfirmEmailAsync(user, code);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user : user, isPersistent : false);

                        return(RedirectToAction(actionName: "Index", controllerName: "Home"));
                    }
                }
                catch (Exception ex)
                {
                    return(BadRequest());
                }
            }
            return(NotFound());
        }
        public async Task <IActionResult> Login(LoginUser loginUser, [FromQuery] string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                AppIdentityUser user = await _userManager.FindByEmailAsync(loginUser.Email);

                if (user is null)
                {
                    return(View(loginUser));
                }

                var response = await _signInManager.PasswordSignInAsync(user.UserName, loginUser.Password, loginUser.RememberMe, false);

                if (response.Succeeded)
                {
                    if (!string.IsNullOrEmpty(ReturnUrl) && Url.IsLocalUrl(ReturnUrl))
                    {
                        return(Redirect(ReturnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("index", "home"));
                    }
                }
            }

            return(View(loginUser));
        }
        public static AppIdentityUser GetLoggedUser(this ControllerBase controller, IAuthRepository authRepo, IAppRepository appRepo)
        {
            var bearerToken = controller.Request.Headers["Authorization"].ToString();
            //var token = controller.Request.Headers["token"].ToString();
            string token = bearerToken.Substring(7);

            AppIdentityUser user = authRepo.GetUserFromToken(token);

            if (user != null)
            {
                if (user.UserType == "Student")
                {
                    Student student   = appRepo.GetByIdAsync <Student>(x => x.Id == user.Id).Result;
                    Group   group     = appRepo.GetByIdAsync <Group>(x => x.Id == student.GroupId).Result;
                    Photo   studPhoto = appRepo.GetPhoto(student.PhotoId).Result;
                    student.FacultyId = group.FacultyId;
                    student.Photo     = studPhoto;
                    student.Group     = group;
                    return(student);
                }
                if (user.UserType == "Teacher")
                {
                    Teacher teacher   = appRepo.GetByIdAsync <Teacher>(x => x.Id == user.Id).Result;
                    Photo   userPhoto = appRepo.GetPhoto(user.PhotoId).Result;
                    Faculty faculty   = appRepo.GetByIdAsync <Faculty>(x => x.Id == teacher.FacultyId).Result;
                    teacher.Faculty = faculty;
                    teacher.Photo   = userPhoto;
                    return(teacher);
                }
                return(user);
            }
            return(null);
        }
예제 #11
0
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            var brhEarningRecord = await _context.BrhEarningRecord.SingleOrDefaultAsync(m => m.EarningRecordId == id);

            AppIdentityUser _user = await _userManager.FindByNameAsync(User.Identity.Name);

            ViewData["UserName"] = _user.UserName;
            ViewData["Branch"]   = _user.Branch;

            var list_paymentType = _context.FncPaymentType.ToList();

            ViewData["PaymentType"] = new SelectList(list_paymentType, "PaymentType", "PaymentType", brhEarningRecord.PaymentType);
            var list_earningType = _context.FncEarningType.ToList();

            ViewData["EarningType"] = new SelectList(list_earningType, "EarningType", "EarningType", brhEarningRecord.EarningType);

            if (brhEarningRecord == null)
            {
                return(NotFound());
            }
            return(PartialView("~/Areas/Branch/Views/BrhEarningRecord/CreateEdit.cshtml", brhEarningRecord));
        }
        public async Task Initialize()
        {
            // create test user
            var user = new AppIdentityUser
            {
                Id               = "TestUser",
                UserName         = "******",
                Email            = "*****@*****.**",
                TwoFactorEnabled = true
            };

            var userManager = this._serviceProvider.GetRequiredService <UserManager <AppIdentityUser> >();
            await userManager.CreateAsync(user, "Pass@word1");

            // sign in test user
            var httpContext = this._serviceProvider.GetRequiredService <IHttpContextAccessor>().HttpContext;

            httpContext.User = new ClaimsPrincipal(
                new ClaimsIdentity(new GenericIdentity(user.Email), new[] { new Claim("ID", user.Id) }));
            httpContext.RequestServices = this._serviceProvider;

            this.walletController = new WalletController(
                this._serviceProvider.GetRequiredService <IWalletService>(),
                userManager);

            this.walletController.ControllerContext.HttpContext = httpContext;
        }
        public async Task <IActionResult> Post([FromBody] SignUpRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userIdentity = new AppIdentityUser
            {
                Email    = request.Email,
                UserName = request.Email,
            };
            var result = await _userManager.CreateAsync(userIdentity, request.Password);

            if (!result.Succeeded)
            {
                result.Errors.Select(error => { ModelState.AddModelError(error.Code, error.Description); return(error); }).ToArray();
                return(BadRequest(ModelState));
            }

            var userModel = await _userManager.FindByEmailAsync(request.Email);

            _appDbContext.AppUsers.Add(new User
            {
                Id        = userIdentity.Id,
                Email     = request.Email,
                FirstName = request.FirstName,
                LastName  = request.LastName,
            });

            await _appDbContext.SaveChangesAsync();

            return(Ok());
        }
예제 #14
0
        public IActionResult Register(Register register)
        {
            if (ModelState.IsValid)
            {
                if (!_roleManager.RoleExistsAsync("Manager").Result)
                {
                    var role = new AppIdentityRole();
                    role.Name        = "Manager";
                    role.Description = "Manager can perform CRUD operations";

                    var roleResult = _roleManager.CreateAsync(role).Result;
                }

                var user = new AppIdentityUser();
                user.UserName  = register.UserName;
                user.Email     = register.Email;
                user.FullName  = register.FullName;
                user.BirthDate = register.BirthDate;

                var result = _userManager.CreateAsync(user, register.Password).Result;

                if (result.Succeeded)
                {
                    _userManager.AddToRoleAsync(user, "Manager").Wait();
                    return(RedirectToAction("SignIn", "Security"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid User details");
                }
            }

            return(View(register));
        }
예제 #15
0
        public async Task <IActionResult> ForgotPassword([FromForm] ForgotPasswordModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    AppIdentityUser user = await _authrepository.FindUserByEmail(model.Email);

                    if (user != null)
                    {
                        var _code       = _authrepository.GeneratePasswordResetToken(user);
                        var callbackUrl = Url.Action(
                            "ResetPassword", "Auth",
                            new { userId = user.Id, code = _code },
                            protocol: HttpContext.Request.Scheme
                            );
                        await new EmailService().SendEmailAsync(user.Name, model.Email, $"{user.Name} - Password reset",
                                                                $"To reset click: <a href='{callbackUrl}'>link</a> ");
                        return(Ok($"{user.Name}, check your email for reset password"));
                    }
                    return(NotFound($"User with {model.Email} does not exist"));
                }
                return(BadRequest("Model is not valid"));
            }
            catch (Exception ex)
            {
                var arguments = this.GetBaseData(_context, _authrepository);
                _logger.LogException(ex, arguments.Email, arguments.Path);
                return(BadRequest($"{ex.GetType().Name} was thrown."));
            }
        }
예제 #16
0
        public AppIdentityUser ConvertUserToIdentityUser(User user)
        {
            //return new User { Id = appIdentityUser.Id,UserName=appIdentityUser.UserName, Email = appIdentityUser.Email, PhoneNumber = appIdentityUser.PhoneNumber };
            AppIdentityUser appIdentityUser = _userManager.FindByEmailAsync(user.Email).Result;

            appIdentityUser.UserName    = user.UserName;
            appIdentityUser.PhoneNumber = user.PhoneNumber;
            appIdentityUser.Birthday    = user.Birthday;
            appIdentityUser.Gender      = user.Gender;
            appIdentityUser.Picture     = user.Picture;
            appIdentityUser.City        = user.City;
            appIdentityUser.Adresse     = user.Adresse;

            //AppIdentityUser adpUser = user.Adapt<AppIdentityUser>();

            //foreach (PropertyInfo propertyIdentity in appIdentityUser.GetType().GetProperties())
            //{
            //    foreach (PropertyInfo propertyUser in appIdentityUser.GetType().GetProperties())
            //    {
            //        if (propertyIdentity.Name ==propertyUser.Name)
            //        {

            //        }
            //    }
            //}

            return(appIdentityUser);
        }
예제 #17
0
        public IResult AddRolesToUser(List <Role> roles, string userId)
        {
            AppIdentityUser appIdentityUser = _userManager.FindByIdAsync(userId).Result;

            if (appIdentityUser != null)
            {
                var userRoles = _userManager.GetRolesAsync(appIdentityUser).Result;
                if (userRoles != null && userRoles.Count > 0)
                {
                    _userManager.RemoveFromRolesAsync(appIdentityUser, userRoles.ToArray()).Wait();
                }

                foreach (var role in roles)
                {
                    if (role.IsChecked)
                    {
                        _userManager.AddToRoleAsync(appIdentityUser, role.RoleName).Wait();
                    }
                }

                return(new SuccessResult());
            }

            return(new ErrorResult("User not found"));
        }
 public IActionResult Register(RegisterViewModel model)
 {
     if (ModelState.IsValid)
     {
         AppIdentityUser appIdentityUser = new AppIdentityUser
         {
             UserName = model.UserName,
             Email    = model.Email
         };
         IdentityResult result = _userManager.CreateAsync(appIdentityUser, model.Password).Result;
         if (result.Succeeded)
         {
             if (!_roleManager.RoleExistsAsync("Admin").Result)
             {
                 IdentityRole appIdentityRole = new IdentityRole
                 {
                     Name = "Admin"
                 };
                 IdentityResult roleResult = _roleManager.CreateAsync(appIdentityRole).Result;
                 if (!roleResult.Succeeded)
                 {
                     ModelState.AddModelError("", "We can't add the role!");
                     return(View(model));
                 }
             }
             _userManager.AddToRoleAsync(appIdentityUser, "Admin");
             return(RedirectToAction("Login", "Security"));
         }
     }
     return(View(model));
 }
예제 #19
0
        public async Task <CreateUserRes> CreateNewUser(AppIdentityUser newUser, string password)
        {
            CreateUserRes response = new CreateUserRes();

            try
            {
                newUser.DepartmentId = newUser.DepartmentId == "" ? null : newUser.DepartmentId;
                var result = await _userManager.CreateAsync(newUser, password);

                if (result.Succeeded)
                {
                    response.UserId  = newUser.Id;
                    response.Message = "Tài khoản mới đã được tạo";
                }
                else
                {
                    response.Message = "Có lỗi đã xảy ra, xin mời liên lạc Quản trị hệ thống";
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Message = "Có lỗi đã xảy ra, xin mời liên lạc Quản trị hệ thống";
                return(response);
            }
        }
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppIdentityUser()
                {
                    Address     = model.Address,
                    Email       = model.Email,
                    UserName    = model.Email,
                    Fullname    = $"{model.Firstname} {model.Lastname}",
                    PhoneNumber = model.PhoneNumber
                };
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var role = await roleManager.FindByNameAsync("Customer");

                    await userManager.AddToRoleAsync(user, role.Name);

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

                    return(RedirectToAction("Index", "Home"));
                }
                foreach (var errors in result.Errors)
                {
                    ModelState.AddModelError("", errors.Description);
                }
                ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
            }
            return(View());
        }
예제 #21
0
        public async Task <IActionResult> Edit(string userId)
        {
            AppIdentityUser user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound());
            }
            EditUserViewModel editUser = new EditUserViewModel()
            {
                UserId      = user.Id,
                FirstName   = user.FirstName,
                LastName    = user.LastName,
                MiddleName  = user.MiddleName,
                Email       = user.Email,
                ClassId     = user.ClassId,
                PhoneNumber = user.PhoneNumber,
                Classes     = _context.Classes.Select(e => e).ToList(),
            };

            editUser.RolesName = await _userManager.GetRolesAsync(user);

            editUser.Roles = _roleManager.Roles.Select(r => new RoleViewModel()
            {
                RoleId   = r.Id,
                RoleName = r.Name
            }).ToList();
            return(View(editUser));
        }
예제 #22
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppIdentityUser()
                {
                    Email       = model.Email,
                    UserName    = model.Email,
                    FullName    = model.FullName,
                    Address     = model.Address,
                    PhoneNumber = model.PhoneNumber
                };
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction(actionName: "Index", controllerName: "Home"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }

                return(View());
            }
            return(View());
        }
예제 #23
0
        private static AppIdentityUser SeedAccountData(
            UserManager <AppIdentityUser> _userManager,
            RoleManager <AppIdentityRole> _roleManager)
        {
            //Check and add roles
            foreach (var r in SYSTEM_ROLES)
            {
                if (_roleManager.Roles.Select(role => role.Name).Contains(r))
                {
                    continue;
                }
                _roleManager.CreateAsync(new AppIdentityRole(r)).Wait();
            }
            //Add email to new user account
            var defaultAccount = new AppIdentityUser(DEFAULT_ACCOUNT_NAME)
            {
                Email = "*****@*****.**"
            };

            //Create new user
            if (!_userManager.Users.Select(u => u.UserName).Contains(DEFAULT_ACCOUNT_NAME))
            {
                _userManager.CreateAsync(defaultAccount, DEFAULT_ACCOUNT_PASSWORD).Wait();
            }

            _userManager.AddToRolesAsync(defaultAccount, SYSTEM_ROLES).Wait();
            return(defaultAccount);
        }
예제 #24
0
        public void TestUserMocking()
        {
            var fixture = new Fixture();
            //var lockedUser = fixture.Build<IdentityUser>().With(u => u.Email, "").Create();

            var user = new AppIdentityUser()
            {
                UserName = "******", Id = "1", Email = "*****@*****.**", EmailConfirmed = false, PasswordHash = "123", PhoneNumber = "1234567", PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnabled = false, AccessFailedCount = 0, Age = 31
            };
            var role = new IdentityRole()
            {
                Id = "1", Name = "Role 01", NormalizedName = "1", ConcurrencyStamp = "fdf"
            };

            var listUsers = new List <AppIdentityUser>();

            listUsers.Add(user);

            var listRoles = new List <IdentityRole>();

            listRoles.Add(role);

            //var usersMock = CreateDbSetMock(listUsers);

            //var options = new DbContextOptionsBuilder<AppIdentityDbContext>()
            //                .Options;

            //var userContextMock = new Mock<AppIdentityDbContext>(options);
            //userContextMock.Setup(x => x.Users).Returns(usersMock.Object);
        }
예제 #25
0
        public static async Task Seed(UserManager <AppIdentityUser> userManager, RoleManager <IdentityRole> roleManager, IConfiguration configuration)
        {
            var username = configuration["Data:AdminUser:username"];
            var password = configuration["Data:AdminUser:password"];
            var email    = configuration["Data:AdminUser:email"];
            var role     = configuration["Data:AdminUser:role"];

            if (await userManager.FindByNameAsync(username) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role));

                var user = new AppIdentityUser()
                {
                    UserName       = username,
                    Email          = email,
                    EmailConfirmed = true,
                };

                var result = await userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, role);
                }
            }
        }
예제 #26
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                if (!await roleManager.RoleExistsAsync("Manager"))
                {
                    AppIdentityRole role = new AppIdentityRole();
                    role.Name        = "Manager";
                    role.Description = "Can perform CRUD operations.";
                    IdentityResult roleResult = await roleManager.
                                                CreateAsync(role);
                }

                AppIdentityUser user = new AppIdentityUser();
                user.UserName  = RegisterData.UserName;
                user.Email     = RegisterData.Email;
                user.FullName  = RegisterData.FullName;
                user.BirthDate = RegisterData.BirthDate;

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

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, "Manager");

                    return(RedirectToPage("/Security/SignIn"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid user details!");
                }
            }
            return(Page());
        }
예제 #27
0
        public async Task <IActionResult> Register(RegisterViewModel registerViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerViewModel));
            }

            var user = new AppIdentityUser
            {
                UserName = registerViewModel.UserName,
                Email    = registerViewModel.Email,
                Age      = registerViewModel.Age
            };

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

            if (result.Succeeded)
            {
                var confirmationCode = _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callBackUrl      = Url.Action("ConfirmEmail", "Security", new { userId = user.Id, code = confirmationCode.Result });

                //send email

                return(RedirectToAction("Index", "Students"));
            }

            return(View(registerViewModel));
        }
예제 #28
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 AppIdentityUser(Input.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);

                        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>.");

                        // 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, info.LoginProvider);

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

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
예제 #29
0
        public async Task <JsonResult> Edit([FromBody] Event2 event2)
        {
            AppIdentityUser _user = await _userManager.FindByNameAsync(User.Identity.Name);

            BrhScalp brhScalp = new BrhScalp();

            var ParentType = typeof(BrhScalp);
            var Properties = ParentType.GetProperties();

            foreach (var Propertie in Properties)
            {
                //循环遍历属性
                if (Propertie.CanRead && Propertie.CanWrite)
                {
                    //进行属性拷贝
                    Propertie.SetValue(brhScalp, Propertie.GetValue(event2, null), null);
                }
            }
            _context.Update(brhScalp);
            _context.SaveChanges();

            var total             = _context.BrhScalp.Where(x => x.ImprestAccountsId == brhScalp.ImprestAccountsId && !x.IsMove).Sum(x => x.TotalPrice);
            var brhImprestAccount = _context.BrhImprestAccounts.SingleOrDefault(x => x.ImprestAccountsId == brhScalp.ImprestAccountsId);

            brhImprestAccount.Equity = brhImprestAccount.Balance - total;
            _context.Update(brhImprestAccount);
            await _context.SaveChangesAsync();

            return(Json(event2));
        }
예제 #30
0
        public IActionResult Register(Register obj)
        {
            if (ModelState.IsValid)
            {
                if (!roleManager.RoleExistsAsync("Manager").Result)
                {
                    AppIdentityRole role = new AppIdentityRole();
                    role.Name = "Manager";
                    IdentityResult roleResult = roleManager.
                                                CreateAsync(role).Result;
                }

                AppIdentityUser user = new AppIdentityUser();
                user.UserName = obj.UserName;
                user.Email    = obj.Email;

                IdentityResult result = userManager.CreateAsync
                                            (user, obj.Password).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Manager").Wait();
                    return(RedirectToAction("SignIn", "Security"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid user details");
                }
            }
            return(View(obj));
        }
 public Task<IdentityResult> AddUserToRoleAsync(AppIdentityUser user, string role)
 {
     return _userMenager.AddToRoleAsync(user.Id, role);
 }
 public Task<ClaimsIdentity> CreateUserIdentityAsync(AppIdentityUser user, string type)
 {
     return _userMenager.CreateIdentityAsync(user, type);
 }
 public async Task<IdentityResult> RemoveUserData(AppIdentityUser user)
 {
     return await _userMenager.DeleteAsync(user);
 }
 public async Task<IdentityResult> UpdateUserData(AppIdentityUser user)
 {
     return await _userMenager.UpdateAsync(user);
 }
 public Task<IdentityResult> CreateUserAsync(AppIdentityUser user, string password)
 {
     return _userMenager.CreateAsync(user, password);
 }
예제 #36
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new AppIdentityUser { Email = model.Email };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
 public Task<IdentityResult> RemoveUserFromRoleAsync(AppIdentityUser user, string role)
 {
     return _userMenager.RemoveFromRoleAsync(user.Id, role);
 }
 public Task SignUserAsync(AppIdentityUser user, bool isPersistant)
 {
     return _signInMenager.SignInAsync(user, isPersistant, false);
 }
예제 #39
0
        public async Task<ActionResult> SignUp(SignUpViewModel model)
        {
            model.EmailAddress = AppUtilities.ProcessEmailAddressInput(model.EmailAddress, ModelState, "model.EmailAddress");
            AppUtilities.ProcessPasswordInput(model.Password1, ModelState, "model.Password1");
            if (model.Password1 != model.Password2)
            {
                ModelState.AddModelError("", StringResources.ErrorMessage_PasswordAndItsConfirmationAreNotEqual);
            }
            if (!ModelState.IsValid) return View(model);

            var appIdentityUser = new AppIdentityUser { Email = model.EmailAddress,};
            IdentityResult result = null;
            try
            {
                result = await UserManager.CreateAsync(appIdentityUser, model.Password1);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(appIdentityUser, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
            }
            catch (AggregateException ex1)
            {
                List<Exception> innerExceptionsFiltered = new List<Exception>();
                foreach (var ex2 in ex1.InnerExceptions)
                {
                    var ex3 = ex2 as DbUpdateException;
                    if (ex3 != null && !AppUtilities.HandleCreateOrUpdateOneUserException(ex3, ModelState, "model.EmailAddress", null))
                    {
                        continue;
                    }
                    innerExceptionsFiltered.Add(ex2);
                }
                CommonUtilities.ThrowZeroOrMoreException_UsingAggregateExceptionOnlyIfNeeded(innerExceptionsFiltered);
            }
            catch (DbUpdateException dbUpdateEx)
            {
                if (AppUtilities.HandleCreateOrUpdateOneUserException(dbUpdateEx, ModelState, "model.EmailAddress", null))
                {
                    throw dbUpdateEx;
                }
            }
            if (result != null && !result.Succeeded)
            {
                AddErrors(result);
            }
            return View(model);

        }