Esempio n. 1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                    // Enviar correo electrónico con este vínculo
                    // 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, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>");

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

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return(View(model));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (await UserManager.FindByNameAsync(model.Email) != null)
            {
                ModelState.AddModelError("email_invalid", "Email đã tồn tại");
                return(View(model));
            }

            var user = new AppUser
            {
                UserName  = model.Email,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName
            };

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

            if (result.Succeeded)
            {
                await UserManager.AddToRolesAsync(user.Id, "Member");

                //                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                TempData["RegisterSuccessed"] = true;
                return(RedirectToAction("Login"));
            }

            return(View(model));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new SecurityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, 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"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 4
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                    // 发送包含此链接的电子邮件
                    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, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">这里</a>来确认你的帐户");

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

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
Esempio n. 5
0
        //[HttpPost("sign-up", Name = "PostRegister")]
        public async Task <IActionResult> Register(RegisterAccount account, string returnTo)
        {
            if (ModelState.IsValid)
            {
                User user = new User()
                {
                    UserName      = account.UserName,
                    Email         = account.Email,
                    FirstName     = account.FirstName,
                    LastName      = account.LastName,
                    RegisteredOn  = account.RegisteredOn,
                    PhotoFileName = "user_avatar.png",
                    GeneratedKey  = Guid.NewGuid().ToString("N"),
                    PhoneNumber   = account.PhoneNumberUser
                };

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

                if (result.Succeeded)
                {
                    if (_userManager.Options.SignIn.RequireConfirmedEmail)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callBackUrl = Url.RouteUrl("ConfirmEmail", new { code, key = user.GeneratedKey },
                                                       Request.Scheme);

                        var message = $"<a href=\"{callBackUrl}\"> Confirm Email </a>";

                        await _emailSender.SendEmailAsync(user.Email, "Confirm Email", message);

                        return(View("SuccessRegister", user));
                    }
                    if (_userManager.Options.SignIn.RequireConfirmedPhoneNumber)
                    {
                        var token = await _userManager
                                    .GenerateChangePhoneNumberTokenAsync(user, user.PhoneNumber);

                        await _smsSender.SendSmsAsync(account.PhoneNumberUser, token);

                        return(View("ConfirmPhone", new Confirmphone  {
                            Returnto = returnTo, Username = account.UserName
                        }));
                    }

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

                    return(RedirectToLocal(returnTo));
                }

                this.AddErrors(result);
            }

            return(View(account));
        }
Esempio n. 6
0
        public async Task Given_BogusSecurityQuestion_When_CreateUser_Then_UserCreatedFailure()
        {
            var userName = "******";

            _userStore.Expect(a => a.FindByNameAsync(userName)).Return(Task.FromResult <User>(null));

            // Act
            var result = await _sut.CreateAsync(userName, "bob", "the bod", "Secure1HJ", "Secure1HJ", 143, "Jo was my mother");

            // Assert
            Assert.IsFalse(result.Succeeded);
            Assert.IsTrue(result.Errors.Contains("Illegal security question"));
            _userStore.AssertWasNotCalled(u => u.CreateAsync(Arg <User> .Is.Anything));
        }
Esempio n. 7
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //TODO: Add fields to user here so they will be saved to the database
                //Create a new user with all the properties you need for the class
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email, FName = model.FirstName, LName = model.LastName, MidInitial = model.MidInitial, PhoneNumber = model.PhoneNumber, Address = model.Address, City = model.City, State = model.State, ZipCode = model.ZipCode, CreditCardOne = model.CreditCardOne, CreditCardTypeOne = model.CreditCardTypeOne
                };

                //Add the new user to the database
                var result = await UserManager.CreateAsync(user, model.Password);

                if (User.IsInRole("Manager"))
                {
                    var result1 = await UserManager.CreateAsync(user, "password");

                    if (result1.Succeeded) //user was created successfully
                    {
                        await UserManager.AddToRoleAsync(user.Id, "Employee");

                        //sign the user in
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        //send them to the home page
                        return(RedirectToAction("Index", "Home"));
                    }
                }


                if (result.Succeeded) //user was created successfully
                {
                    await UserManager.AddToRoleAsync(user.Id, "Customer");

                    //sign the user in
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    EmailMessaging.SendEmail(user.Email, "Welcome to LHM!", "Thank You for Joining Longhorn Music, " + user.FName + "!");

                    //send them to the home page
                    return(RedirectToAction("Index", "Home"));
                }

                //if there was a problem, add the error messages to what we will display
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IHttpActionResult> Create(UserAddRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new AppUser {
                UserName = request.Username, Email = request.Email, JoinDate = DateTime.Now.Date
            };

            IdentityResult createUserResult = await AppUserManager.CreateAsync(user, request.Password);

            if (!createUserResult.Succeeded)
            {
                return(GetErrorResult(createUserResult));
            }

            IdentityResult addUserToRoleResult = await AppUserManager.AddToRoleAsync(user.Id, "user");

            if (!addUserToRoleResult.Succeeded)
            {
                return(GetErrorResult(addUserToRoleResult));
            }

            string code = await this.AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code }));

            await this.AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            return(Created(new Uri(Url.Link("GetUserById", new { id = user.Id })), TheModelFactory.Create(user)));
        }
Esempio n. 9
0
        public async Task <IActionResult> Register(RegisterInputModel parameters)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(state => state.Errors)
                                  .Select(error => error.ErrorMessage)
                                  .FirstOrDefault()));
            }

            var user = new AppUser();

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

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors.FirstOrDefault()?.Description));
            }

            return(await Login(new LoginInputModel
            {
                Key = parameters.UserName,
                Password = parameters.Password
            }));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //Create a new user with all the properties you need for the class
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email, FName = model.FName, LName = model.LName, PhoneNumber = model.PhoneNumber, Address = model.Address, City = model.City, State = model.State, Zip = model.Zip
                };

                //Add the new user to the database
                var result = await UserManager.CreateAsync(user, model.Password);

                // Once you get roles working, you may want to add users to roles upon creation
                await UserManager.AddToRoleAsync(user.Id, "Customer"); //adds user to role called "User"


                if (result.Succeeded) //user was created successfully
                {
                    //sign the user in
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    //send them to the home page
                    return(RedirectToAction("Index", "Home"));
                }

                //if there was a problem, add the error messages to what we will display
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 11
0
        public async Task <RepositoryResult <UserInterfaceModel> > CreateUserAsync(UserInterfaceModel createUser)
        {
            try
            {
                if (await AppUserManager.FindByIdAsync(createUser.Id) != null)
                {
                    return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.Conflict));
                }

                if (string.IsNullOrWhiteSpace(createUser.NewPassword))
                {
                    return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.BadRequest, "パスワードは必須項目です。"));
                }

                var user = new UserModel();
                user.UserName = createUser.UserName;
                user.Name     = createUser.Name;
                user.Email    = createUser.Email;
                user.Enabled  = createUser.Enabled;

                var result = new RepositoryResult <UserInterfaceModel>(HttpStatusCode.Created);
                result.identityResult = await AppUserManager.CreateAsync(user, createUser.NewPassword);

                if (!result.identityResult.Succeeded)
                {
                    result.Code = HttpStatusCode.BadRequest;
                }
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = new User
            {
                UserName = model.UserName,
                Email    = model.Email,
            };

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

            if (result.Succeeded)
            {
                userManager.AddToRole(user.Id, "User");
                await SignIn(user);

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

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

            return(View());
        }
Esempio n. 13
0
        public async Task <IActionResult> Create(User user)
        {
            var aUser = await userManager.GetUserAsync(User);

            userManager.TenantId = aUser.TenantId;
            if (ModelState.IsValid)
            {
                AppUser appUser = new AppUser
                {
                    UserName = user.Name,
                    Email    = user.Email,
                };

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

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View(user));
        }
        public static void EnsureSeedData(this AppIdentityDbContext context)
        {
            AppUserManager userMgr  = new AppUserManager(new UserStore <AppUser, AppRole, AppIdentityDbContext, string>(context), null, new PasswordHasher <AppUser>(), null, null, null, null, null, null);
            AppRoleManager roleMgr  = new AppRoleManager(new RoleStore <AppRole, AppIdentityDbContext, string>(context), null, null, null, null, null);
            string         roleName = "Administrators";
            string         userName = "******";
            string         password = "******";
            string         email    = "*****@*****.**";

            if (!roleMgr.RoleExistsAsync(roleName).Result)
            {
                roleMgr.CreateAsync(new AppRole(roleName)).Wait();
            }

            AppUser user = userMgr.FindByNameAsync(userName).Result;

            if (user == null)
            {
                user = new AppUser {
                    UserName = userName, Email = email
                };
                userMgr.CreateAsync(user, password).Wait();
                user = userMgr.FindByNameAsync(userName).Result;
            }

            if (!userMgr.IsInRoleAsync(user, roleName).Result)
            {
                userMgr.AddToRoleAsync(user, roleName).Wait();
            }

            context.SaveChanges();
        }
Esempio n. 15
0
        public async Task <IHttpActionResult> CreateUser(CreateUser createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApiUser()
            {
                UserName  = createUserModel.Email,
                Email     = createUserModel.Email,
                FirstName = createUserModel.FirstName,
                LastName  = createUserModel.LastName,
                Level     = 3,
                JoinDate  = DateTime.Now.Date,
            };

            IdentityResult addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            string code = await this.AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));

            await this.AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //Add fields to user here so they will be saved to do the database
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email, FName = model.FName, MInitial = model.MInitial, LName = model.LName, StreetAddress = model.StreetAddress, City = model.City, State = model.State, Zip = model.Zip, Phone = model.Phone, Birthday = model.Birthday
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                db.SaveChanges();

                //Once you get roles working, you may want to add users to roles upon creation
                await UserManager.AddToRoleAsync(user.Id, "User");

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, 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"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 17
0
        public async Task <IHttpActionResult> Register(RegisterClientModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var client = new Client
            {
                UserName = model.Email,
                Email    = model.Email,
                Name     = model.Name,
                Address  = model.Address,
                Location = model.Location
            };

            IdentityResult result;
            var            existingUser = await _userManager.FindByEmailAsync(client.Email);

            if (existingUser != null)
            {
                result = IdentityResult.Failed(new[] { "User with this email already exists" });
            }
            else
            {
                result = await _clientManager.CreateAsync(client, model.Password);
            }

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Esempio n. 18
0
        public async Task RegisterAdminAsync(RegisterAdminModel model)
        {
            try
            {
                if (!model.Password.ToLower().Equals(model.ConfirmPassword.ToLower()))
                {
                    throw new Exception("Password and confirm password must be matched.");
                }
                if ((await _userManager.FindByNameAsync(model.Email)) != null)
                {
                    throw new Exception("Username already exist.");
                }
                AppUser user = new AppUser();
                user.UserName    = model.Email;
                user.Email       = model.Email;
                user.PhoneNumber = model.PhoneNumber;
                var result = await _userManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    throw new Exception(result.ErrorGathering());
                }
                await AssignRoleToUser(user.Id, PharmacyRoles.Admin);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <ActionResult> Register(RegisterUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.IsSucceeded = false;
                return(View(model));
            }

            var newuser = new AcidCodeUser
            {
                UserName = model.UserName,
            };

            var usermanager = new AppUserManager(_userStore);

            var result = await usermanager.CreateAsync(newuser, model.Password);

            ViewBag.returnUrl = model.ReturnUrl;
            if (!result.Succeeded)
            {
                model.IsSucceeded = false;
                foreach (var item in result.Errors)
                {
                    ModelState.AddModelError("", item);
                }
                return(View("RegisterResult", model));
            }

            model.IsSucceeded = true;
            return(View("RegisterResult", model));
        }
Esempio n. 20
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    UserName = model.Email, Email = model.Email, RegisterDate = DateTime.Now, LastOnline = DateTime.Now, Name = model.Name
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    ClaimsIdentity claim = await UserManager.CreateIdentityAsync(user,
                                                                                 DefaultAuthenticationTypes.ApplicationCookie);

                    UserManager.AddToRole(user.Id, "user");
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return(View(model));
        }
Esempio n. 21
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser()
                {
                    UserName = model.UserName, Age = model.Age, Email = model.Email, LastName = model.LastName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    //AddErrors(result);
                }
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return(View(model));
        }
Esempio n. 22
0
        public async Task <IHttpActionResult> CreateUser(CreateUserDto createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser(createUserModel.Username);
            //{
            //    UserName = createUserModel.Username,
            //    Email = createUserModel.Email,
            //    FirstName = createUserModel.FirstName,
            //    LastName = createUserModel.LastName,
            //    Level = 3,
            //    JoinDate = DateTime.Now.Date,
            //};

            IdentityResult addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, TheDtoFactory.Create(user)));
        }
Esempio n. 23
0
        public async Task <IHttpActionResult> CreateUser(CreateUserVM createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser()
            {
                UserName       = createUserModel.UserName,
                Email          = createUserModel.Email,
                FirstName      = createUserModel.FirstName,
                LastName       = createUserModel.LastName,
                JoinDate       = DateTime.UtcNow,
                RoleName       = createUserModel.RoleName,
                Branch         = createUserModel.Branch,
                Studies        = createUserModel.Studies,
                Year           = createUserModel.Year,
                EmailConfirmed = true,
            };


            IdentityResult addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, user));
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    UserName    = model.UserName,
                    Email       = model.UserName,
                    PhoneNumber = model.PhoneNumber,
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }
            return(View(model));
        }
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var info = await Authentication.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(InternalServerError());
            }

            var user = new ApplicationUser()
            {
                UserName = model.Email, Email = model.Email
            };

            IdentityResult result = await AppUserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            result = await AppUserManager.AddLoginAsync(user.Id, info.Login);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            return(Ok());
        }
Esempio n. 26
0
        private async Task SeedAsync(AppContext context)
        {
            var user = new ShopUser()
            {
                UserName  = AdminUser.UserName,
                Email     = AdminUser.Email,
                FirstName = AdminUser.FirstName,
                LastName  = AdminUser.LastName,
            };
            var role = new AppRole(RoleNames.Admin);

            ///
            UserStore <ShopUser> uStore = new UserStore <ShopUser>(context);
            var userManager             = new AppUserManager(uStore);
            RoleStore <AppRole> rStore  = new RoleStore <AppRole>(context);
            var roleManager             = new AppRoleManager(rStore);
            var adminRole = await roleManager.FindByNameAsync(RoleNames.Admin);

            if (adminRole == null)
            {
                adminRole = new AppRole(RoleNames.Admin);
                await roleManager.CreateAsync(adminRole);
            }

            // await roleManager.CreateAsync(new AppRole(RoleNames.Admin));
            var result = await userManager.CreateAsync(user, AdminUser.Password);

            user = await userManager.FindByNameAsync(AdminUser.UserName);

            await userManager.AddToRoleAsync(user.Id, RoleNames.Admin);
        }
Esempio n. 27
0
        public async Task <IHttpActionResult> PostApplicationUser(ApplicationUser applicationUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            applicationUser.UserName       = applicationUser.Email;
            applicationUser.EmailConfirmed = true;

            try
            {
                var result = await AppUserManager.CreateAsync(applicationUser, applicationUser.PasswordHash);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }
            catch (DbUpdateException)
            {
                if (ApplicationUserExists(applicationUser.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }
            return(CreatedAtRoute("DefaultApi", new { id = applicationUser.Id }, applicationUser));
        }
Esempio n. 28
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //TODO: Add fields to user here so they will be saved to the database
                //Create a new user with all the properties you need for the class
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, OKToText = model.OKToText, McCombsMajors = model.McCombsMajors
                };

                //Add the new user to the database
                var result = await UserManager.CreateAsync(user, model.Password);

                //TODO: Once you get roles working, you may want to add users to roles upon creation
                await UserManager.AddToRoleAsync(user.Id, "Member"); //adds user to role called "Member"

                // --OR--
                //await UserManager.AddToRoleAsync(user.Id, "Employee"); //adds user to role called "Employee"

                if (result.Succeeded) //user was created successfully
                {
                    //sign the user in
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    //send them to the home page
                    return(RedirectToAction("Index", "Home"));
                }

                //if there was a problem, add the error messages to what we will display
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 29
0
        public async Task <IHttpActionResult> CreateUserAdmin(CreateUser createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ApiUser user = new ApiUser()
            {
                Email          = createUserModel.Email,
                FirstName      = createUserModel.FirstName,
                LastName       = createUserModel.LastName,
                UserName       = createUserModel.Email,
                Level          = 3,
                JoinDate       = DateTime.Now.Date,
                EmailConfirmed = true
            };

            IdentityResult addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
Esempio n. 30
0
        public async Task <IHttpActionResult> Register(UserRegisterModel userRegisterModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var result = await AppUserManager.CreateAsync(new User
            {
                Email    = userRegisterModel.Email,
                UserName = userRegisterModel.UserName,
                JoinDate = DateTime.UtcNow,
                Image    = "avatar.jpg"
            }, userRegisterModel.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok(new
            {
                Message = "User registered."
            }));
        }