コード例 #1
0
        private static async Task EnsureRole(IServiceProvider serviceProvider,
                                             string uid, string role)
        {
            IdentityResult IR          = null;
            var            roleManager = serviceProvider.GetService <RoleManager <IdentityRole> >();

            if (!await roleManager.RoleExistsAsync(role))
            {
                IR = await roleManager.CreateAsync(new IdentityRole(role));
            }
            if (IR.Succeeded != true)
            {
                throw new Exception(IR.ToString());
            }

            var userManager = serviceProvider.GetService <UserManager <ApplicationUser> >();

            var user = await userManager.FindByIdAsync(uid);

            IR = await userManager.AddToRoleAsync(user, role);

            if (IR.Succeeded != true)
            {
                throw new Exception(IR.ToString());
            }
        }
コード例 #2
0
 public void Handle(IdentityResult error)
 {
     if (error.ToString() != "Succeeded")
     {
         answer = new AnswerModel(400, null, error.ToString());
     }
     else
     {
         answer = new AnswerModel(200, null, "Succeeded");
     }
 }
コード例 #3
0
        public async Task <IActionResult> Register(UserDto user)
        {
            try
            {
                User registerUser = await _userManager.FindByNameAsync(user.Username);

                if (registerUser != null)
                {
                    TempData["msg"] = "Username " + user.Username + " already exist!";
                    return(RedirectToAction("RegisterPage"));
                }
                else
                {
                    registerUser          = new User();
                    registerUser.UserName = user.Username;
                    IdentityResult result = await _userManager.CreateAsync(registerUser, user.Password);

                    if (result.Succeeded)
                    {
                        var resultLogin = await _signInManager.PasswordSignInAsync(user.Username, user.Password, false, false);

                        if (resultLogin.Succeeded)
                        {
                            await _setUserStatus.Execute(user.Username, true);

                            var profileUpdate = await _getUserByUsername.Execute(user.Username);

                            await _chatHub.SendProfile(profileUpdate);

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

                        TempData["msg"] = result.ToString();
                        return(RedirectToAction("LoginPage"));
                    }
                    else
                    {
                        TempData["msg"] = result.ToString();
                        return(RedirectToAction("RegisterPage"));
                    }
                }
            }
            catch (Exception e)
            {
                TempData["msg"] = e.Message;
                return(RedirectToAction("RegisterPage"));
            }
        }
コード例 #4
0
        public async Task <IActionResult> Authentication(RegisterViewModel model)
        {
            var newUser = new User()
            {
                UserName    = model.Email,
                Email       = model.Email,
                Address     = model.Address ?? "",
                PhoneNumber = model.PhoneNumber,
                FirstName   = model.FirstName,
                LastName    = model.LastName,
                DateOfBirth = model.DateOfBirth
            };
            IdentityResult registerResult = await _userManager.CreateAsync(newUser, model.Password);

            Console.WriteLine(registerResult.ToString());

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

                RedirectToAction("UserDetail");
            }
            ModelState.AddModelError("DuplicateEmail", "Email already exists.");
            // Console.WriteLine("Error");
            return(View());
            // return RedirectToAction("Authentication");
        }
コード例 #5
0
        public async Task <ActionResult> Register([FromBody] RegisterModel registerModel)
        {
            IdentityUser identityUser = new IdentityUser()
            {
                Email = registerModel.Email, UserName = registerModel.Username
            };
            IdentityResult result = await userManager.CreateAsync(identityUser, registerModel.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.ToString()));
            }

            IdentityUser identityUserToLogIn = await userManager.FindByEmailAsync(registerModel.Email);

            User user = new User();

            user.Username = registerModel.Username;
            user.Role     = registerModel.Role;
            user.Avatar   = registerModel.Avatar;
            _context.User.Add(user);
            _context.SaveChanges();

            await LoginUser(identityUserToLogIn, registerModel.Password, false);

            LoginModel login = new LoginModel();

            login.Email    = registerModel.Email;
            login.Password = registerModel.Password;
            return(await Login(login));
        }
コード例 #6
0
        protected override void Seed(WritingTutor.Web.Data.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.


            //if (System.Diagnostics.Debugger.IsAttached == false)
            //    System.Diagnostics.Debugger.Launch();

            // based on S Allen's MVC 5 Fundamentals Pluralsight Course
            // note foced block on async call with .Result
            var userManager = CreateUserManager(context);

            string[] emails = { "[email protected]", "[email protected]" };
            if (userManager.FindByEmail(emails[0]) == null)
            {
                foreach (string email in emails)
                {
                    IdentityResult x = userManager.Create(new ApplicationUser {
                        UserName = email, Email = email
                    }, "password");
                    Console.WriteLine(x.ToString());
                }
            }

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
コード例 #7
0
        public IActionResult Register([FromBody] RegisterViewModel registerObj)
        {
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();
                user.UserName  = registerObj.UserName;
                user.Email     = registerObj.Email;
                user.FullName  = registerObj.FullName;
                user.BirthDate = registerObj.BirthDate;

                IdentityResult result = _userManager.CreateAsync(user, registerObj.Password).Result;
                _logger.LogError(result.ToString());
            }
            else
            {
                foreach (var modelStateValue in ModelState.Values)
                {
                    foreach (var modelError in modelStateValue.Errors)
                    {
                        _logger.LogError(modelError.Exception, modelError.ErrorMessage);
                    }
                }
            }

            return(Json(true));
        }
コード例 #8
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            try
            {
                ViewBag.Message = "Toks vartotojo vardas jau registruotas";
                User usr = await UserMgr.FindByNameAsync(model.Email);

                if (usr == null)
                {
                    usr = new User
                    {
                        UserName = model.Email,
                        Email    = model.Email
                    };

                    IdentityResult result = await UserMgr.CreateAsync(usr, model.Password);

                    if (result.Succeeded)
                    {
                        ViewBag.Message = "Vartotojas sukurtas";
                    }
                    else
                    {
                        ViewBag.Message = result.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }
            return(View());
        }
 // Adiciona os erros capturadores no login ao objeto ao objeto de notificação
 private void AdicionarErrosIdentity(IdentityResult result)
 {
     foreach (var error in result.Errors)
     {
         _mediator.PublicarEvento(new DomainNotification(result.ToString(), error.Description));
     }
 }
コード例 #10
0
        public async Task <JsonResult> ChangePassword(int userId, string currentPassword, string newPassword)
        {
            var user = await UserManager.FindByIdAsync(userId.ToString());

            if (user == null)
            {
                return(Json(new
                {
                    success = false,
                    response = "User does not exist"
                }, JsonRequestBehavior.AllowGet));
            }
            IdentityResult result = await UserManager.ChangePasswordAsync(user.Id, currentPassword, newPassword);

            if (result.Succeeded)
            {
                return(Json(new
                {
                    success = true,
                    response = ""
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                string responseJson = result.ToString();
                return(Json(new
                {
                    success = false,
                    response = responseJson
                }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #11
0
 /// <summary>
 /// 把身份验证错误引发错误通知
 /// </summary>
 /// <param name="result"></param>
 protected void AddIdentityErrors(IdentityResult result)
 {
     foreach (var error in result.Errors)
     {
         NotifyError(result.ToString(), error.Description);
     }
 }
コード例 #12
0
        public async Task <IActionResult> Edit(string id, bool isAdmin)
        {
            ViewBag.LinkText = "UserAccounts";
            var user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NotFound());
            }
            var            isCurrentlyAdmin = (await _userManager.GetRolesAsync(user)).Contains("Administrator");
            IdentityResult IR = null;

            if (isAdmin != isCurrentlyAdmin)
            {
                if (isAdmin)
                {
                    IR = await _userManager.AddToRoleAsync(user, "Administrator");
                }
                else
                {
                    IR = await _userManager.RemoveFromRoleAsync(user, "Administrator");
                }
            }
            if (IR != null && !IR.Succeeded)
            {
                ViewBag.ErrorMessage = IR.ToString();
                return(View(user));
            }
            return(View(user));
        }
コード例 #13
0
 /// <summary>
 /// Adiciona os erros capturadores no login ao objeto ao objeto de notificação
 /// </summary>
 /// <param name="result"></param>
 private void AdicionarErrosIdentity(IdentityResult result)
 {
     foreach (var error in result.Errors)
     {
         _bus.RaiseEvent(new DomainNotification(result.ToString(), error.Description));
     }
 }
コード例 #14
0
        public async Task ChangePasswordAsync(string userId, string currentPassword, string newPassword)
        {
            var user = await _userRepository.GetUserByIdAsync(userId);

            if (user == null)
            {
                throw new NotFoundException("User does not exist.");
            }

            IdentityResult result = await user.ChangePasswordAsync(_userManager, currentPassword, newPassword);

            if (!result.Succeeded)
            {
                throw new BadRequestException(result.ToString());
            }

            // Blacklist all user's token
            var userTokens = await _identityTokenRepository.GetTokenByUserIdAsync(user.Id);

            foreach (var userToken in userTokens)
            {
                if (userToken.IdentityTokenBlacklist == null)
                {
                    userToken.Block();
                }
            }
            await _userRepository.SaveAsync();
        }
コード例 #15
0
 protected void AdicionarErrosIdentity(IdentityResult result)
 {
     foreach (var error in result.Errors)
     {
         NotificarErro(result.ToString(), error.Description);
     }
 }
コード例 #16
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                Random          random = new Random();
                ApplicationUser user   = null;
                IdentityResult  result = null;
                int             code   = random.Next(1001, 9999);

                user = new ApplicationUser()
                {
                    Email = model.Email, DisplayName = model.Name, codefromemail = code, UserName = model.Email
                };
                result = await UserManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    return(BadRequest(result.ToString()));
                }
                await EmailProvider.SentCodeToEmail(model.Email, code.ToString());

                return(Ok());
            }
            catch (Exception e)
            {
                await EmailProvider.SentCodeToEmail(model.Email, e.ToString());

                return(BadRequest());
            }
        }
コード例 #17
0
        public async Task AddUserToRoleAsync(string userName, string role)
        {
            var existingUser = await _userManager.FindByNameAsync(userName);

            if (existingUser == null)
            {
                throw new NoSuchEntityException(existingUser.GetType().Name);
            }

            IdentityResult result = await _userManager.AddToRoleAsync(existingUser, role);

            if (!result.Succeeded)
            {
                throw new UserInvalidOperationException(result.ToString());
            }
        }
コード例 #18
0
        public async Task <IdentityResult> AddUserAsync(UserDTO user)
        {
            string          defaultStatus = "Active";
            ApplicationUser userToAdd     = new ApplicationUser {
                UserName = user.UserName,
                Email    = user.Email,
                Status   = defaultStatus
            };
            IdentityResult result = await _userManager.CreateAsync(userToAdd, user.Password);

            if (!result.Succeeded)
            {
                throw new UserInvalidOperationException(result.ToString());
            }
            return(result);
        }
コード例 #19
0
ファイル: UserSerivce.cs プロジェクト: nsolovyoff/BuyAndRun
        public async Task AddUserToRole(string userName, string role)
        {
            var user = await _unitOfWork.Users.SingleOrDefaultAsync(u => u.UserName == userName);

            if (user == null)
            {
                throw ExceptionBuilder.Create("User with provided UserName does not exist");
            }

            IdentityResult result = await _userManager.AddToRoleAsync(user, role);

            if (!result.Succeeded)
            {
                throw ExceptionBuilder.Create("Eror when adding roles to user - " + result.ToString(), HttpStatusCode.BadRequest);
            }
        }
コード例 #20
0
        public async Task <Unit> Handle(RegisterCommand request, CancellationToken cancellationToken)
        {
            ApplicationUser userWithEmail = await _userManager.FindByEmailAsync(request.Email);

            if (userWithEmail != null)
            {
                throw new DuplicateException($"User with email {request.Email} is already existed.");
            }

            ApplicationUser userWithUserName = await _userManager.FindByNameAsync(request.UserName);

            if (userWithUserName != null)
            {
                throw new DuplicateException($"User with request.UserName {request.UserName} is already existed.");
            }

            var user = new ApplicationUser
            {
                Email    = request.Email,
                UserName = request.UserName
            };

            IdentityResult result = await _userManager.CreateAsync(user, request.Password);

            if (!result.Succeeded)
            {
                throw new DomainException(result.ToString());
            }

            await _userManager.AddToRoleAsync(user, Enums.Role.User.ToString());

            string confirmCode = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            _logger.LogInformation($"Generated confirm code : {confirmCode} with user {request.UserName}");

            await _emailService.SendAsync(BuildConfirmEmail(user, confirmCode));

            await _mediator.Publish(new RegisteredEvent
            {
                Email    = user.Email,
                UserName = user.UserName
            }, cancellationToken);

            return(Unit.Value);;
        }
コード例 #21
0
        private async Task SeedUserAsync(ApplicationSeededUserOptions options)
        {
            ApplicationUser user =
                await _userManager.FindByNameAsync(options.UserName);

            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = options.UserName,
                    Email    = options.Email,
                    // email is automatically confirmed for a stock user
                    EmailConfirmed = true,
                    SecurityStamp  = Guid.NewGuid().ToString(),
                    FirstName      = options.FirstName,
                    LastName       = options.LastName
                };
                IdentityResult result =
                    await _userManager.CreateAsync(user, options.Password);

                if (!result.Succeeded)
                {
                    _logger.LogError(result.ToString());
                    return;
                }
                user = await _userManager.FindByNameAsync(options.UserName);
            }
            // ensure that user is automatically confirmed
            if (!user.EmailConfirmed)
            {
                user.EmailConfirmed = true;
                await _userManager.UpdateAsync(user);
            }

            if (options.Roles != null)
            {
                foreach (string role in options.Roles)
                {
                    if (!await _userManager.IsInRoleAsync(user, role))
                    {
                        await _userManager.AddToRoleAsync(user, role);
                    }
                }
            }
        }
コード例 #22
0
        public async Task <ActionResult> Register([FromBody] RegisterModel registerModel)
        {
            IdentityUser identityUser = new IdentityUser()
            {
                Email = registerModel.Email, UserName = registerModel.Email
            };

            IdentityResult result = await userManager.CreateAsync(identityUser, registerModel.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.ToString()));
            }

            IdentityUser user = await userManager.FindByEmailAsync(registerModel.Email);

            return(Ok(GenerateToken(registerModel.Email, user)));
        }
コード例 #23
0
        public async Task <IHttpActionResult> DeleteRole(string Id)
        {
            var role = await this.AppRoleManager.FindByIdAsync(Id);

            if (role != null)
            {
                IdentityResult result = await this.AppRoleManager.DeleteAsync(role);

                if (!result.Succeeded)
                {
                    return(InternalServerError(new Exception(result.ToString())));
                }

                return(Ok());
            }

            return(NotFound());
        }
        public async Task <Unit> Handle(ConfirmEmailCommand request, CancellationToken cancellationToken)
        {
            ApplicationUser user = await _userManager.FindByNameAsync(request.UserName);

            if (user is null)
            {
                throw new NotFoundException($"Can't get user with UserName is {request.UserName}");
            }

            IdentityResult result = await _userManager.ConfirmEmailAsync(user, request.Code);

            if (result.Succeeded)
            {
                return(Unit.Value);
            }
            _logger.LogError($"An error occurred while processing confirm email with command {request}");
            throw new DomainException(result.ToString());
        }
コード例 #25
0
        public async void Initialize(UserManager <User> userManager, RoleManager <IdentityRole> roleManager)
        {
            // Ensure that all roles exist in the DB
            foreach (string role in User.ALL_ROLES)
            {
                if (!await roleManager.RoleExistsAsync(role))
                {
                    await roleManager.CreateAsync(new IdentityRole(role));
                }
            }

            // If there are no users, create the default user.
            if (await this.Users.CountAsync() == 0)
            {
                Console.WriteLine("[INFO]: No users in database. Creating default user. (See DataContext.cs)");
                User           newUser      = new User(DEFAULT_USERNAME);
                IdentityResult createResult = await userManager.CreateAsync(newUser, DEFAULT_PASSWORD);

                if (createResult.Succeeded)
                {
                    //await this.SaveChangesAsync();
                    await userManager.AddToRoleAsync(newUser, User.ROLE_SPECTATOR);

                    await userManager.AddToRoleAsync(newUser, User.ROLE_ADMIN);

                    await this.SaveChangesAsync();
                }
                else
                {
                    throw new Exception("Couldn't create default user: "******"Other", ID = new Guid().ToString(), DonateURL = "", HomepageURL = "", Summary = ""
                };
                Endorsements.Add(otherEndorsement);
                await this.SaveChangesAsync();
            }
        }
コード例 #26
0
        public async Task ConfirmEmailAsync(string userId, string token)
        {
            var user = await _userRepository.GetUserByIdAsync(userId);

            if (user == null)
            {
                throw new NotFoundException("User does not exist.");
            }

            IdentityResult result = await user.EmailConfirmeAsync(_userManager, token);

            if (!result.Succeeded)
            {
                throw new BadRequestException(result.ToString());
            }

            // TODO: db save 可以省略, 因为identity result已经存过数据了
            await _userRepository.SaveAsync();
        }
コード例 #27
0
ファイル: UserManagerService.cs プロジェクト: Calkines/TryLog
        /// <summary>
        /// Gera uma nova conta de usuário.
        /// E envia email de confirmação.
        /// </summary>
        /// <param name="userCreate"></param>
        /// <param name="callback"></param>
        /// <returns>O resultado do comando.</returns>
        public async Task <UserCreateOutView> Create(UserCreateView userCreate, string callback)
        {
            User user = _mapper.Map <User>(userCreate);

            IdentityResult result = await _userManager.CreateAsync(user, userCreate.Password);

            if (!result.Succeeded)
            {
                return(new UserCreateOutView(400, result.ToString()));
            }

            var token = await CreateTokenEmailConfirmation(user);

            string bodyMessage =
                CreateBodyEmail(Messages.AccountEmailActivation, user.FullName, callback, user.Email, token);

            await _emailService.SendEmailAsync(user.FullName, user.Email, "Account activation.", bodyMessage);

            return(new UserCreateOutView(201, "Waiting for activation."));
        }
コード例 #28
0
        public async Task <ActionResult> Register([FromBody] RegisterModel registerModel)
        {
            IdentityUser identityUser = new IdentityUser()
            {
                Email = registerModel.Email, UserName = String.Concat(registerModel.FirstName, registerModel.LastName), PhoneNumber = registerModel.PhoneNumber,
            };

            IdentityResult result = await userManager.CreateAsync(identityUser, registerModel.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.ToString()));
            }

            IdentityUser user = await userManager.FindByEmailAsync(registerModel.Email);

            await LoginUser(user, registerModel.Password, false);

            return(Ok(GenerateToken(registerModel.Email, user)));
        }
コード例 #29
0
        public async Task <IActionResult> AddRoleForUser(string userEmail, string userRole)
        {
            var user = await _userManager.FindByEmailAsync(userEmail);

            var role = await _context.Roles.FirstOrDefaultAsync(x => x.Name == userRole);

            if (user != null && role != null)
            {
                IdentityResult result = await _userManager.AddToRoleAsync(user, userRole);

                if (result.Succeeded)
                {
                    return(Ok($"Added user: {user.DisplayName} to the Role {userRole}."));
                }
                return(BadRequest($"Error: {result.ToString()}"));
            }
            return(user == null
                ? NotFound($"Can't find user {userEmail}.")
                : NotFound($"Can't find role {userRole}"));
        }
コード例 #30
0
ファイル: UserSerivce.cs プロジェクト: nsolovyoff/BuyAndRun
        public async Task <UserResource> CreateUser(CreateUserResource newUser)
        {
            var validator        = new CreateUserResourceValidator();
            var validationResult = await validator.ValidateAsync(newUser);

            if (!validationResult.IsValid)
            {
                throw new ValidationException(validationResult.Errors);
            }

            var            user   = _mapper.Map <CreateUserResource, User>(newUser);
            IdentityResult result = await _userManager.CreateAsync(user, newUser.Password);

            if (!result.Succeeded)
            {
                throw ExceptionBuilder.Create("Eror when creating user - " + result.ToString(), HttpStatusCode.BadRequest);
            }

            var userModel = _mapper.Map <UserResource>(user);

            return(userModel);
        }