コード例 #1
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));
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: CoderVision/NS45
        private void CreateIdentity(string sessionJson)
        {
            var session = _apiProvider.DeserializeJson <Session>(sessionJson);
            var appUser = new AppUser(session.UserId.ToString(), "User");
            var task    = _appUserManager.CreateIdentityAsync(appUser, DefaultAuthenticationTypes.ApplicationCookie);

            task.Wait();
            var claim = task.Result;

            var authMgr        = HttpContext.GetOwinContext().Authentication;
            var authProperties = new AuthenticationProperties()
            {
                IsPersistent = false
            };

            authProperties.Dictionary["Session"] = sessionJson;

            foreach (var role in session.Roles)
            {
                var appRole = _appRoleManager.FindById(role.RoleID.ToString());
                if (appRole != null)
                {
                    _appUserManager.AddToRoleAsync(appUser.Id.ToString(), appRole.Name);
                }
            }

            authMgr.SignIn(authProperties, claim);
        }
コード例 #3
0
        public async Task <ActionResult> Edit(RoleModificationViewModel model)
        {
            IdentityResult result;

            if (ModelState.IsValid)
            {
                foreach (string userId in model.IdsToAdd ?? new string[] { })
                {
                    result = await UserManager.AddToRoleAsync(userId, model.RoleName);

                    if (!result.Succeeded)
                    {
                        return(View("_Error", result.Errors));
                    }
                }
                foreach (string userId in model.IdsToDelete ?? new string[] { })
                {
                    result = await UserManager.RemoveFromRoleAsync(userId, model.RoleName);

                    if (!result.Succeeded)
                    {
                        return(View("_Error", result.Errors));
                    }
                }
                return(RedirectToAction("Index"));
            }
            return(View("_Error", new string[] { "Role Not Found" }));
        }
コード例 #4
0
        public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var RoleToJoin = new AppRole("user");
                var user       = new AppUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await UserManager.AddToRoleAsync(user.Id, RoleToJoin.Name);

                    await SignInManager.SignInAsync(user, false, false);

                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToAction("List", "Product"));
                    }

                    return(Redirect(returnUrl));
                }
                AddErrors(result);
            }

            return(View(model));
        }
コード例 #5
0
        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)));
        }
        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();
        }
コード例 #7
0
        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));
        }
コード例 #8
0
        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));
        }
コード例 #9
0
        public async Task <ActionResult> Edit(RoleModificationModel model)
        {
            IdentityResult result;

            if (!ModelState.IsValid)
            {
                return(View("Error", new[] { "Role Not Found" }));
            }

            foreach (var userId in model.IdsToAdd ?? Enumerable.Empty <string>())
            {
                var user = await _userManager.FindByIdAsync(userId);

                result = await _userManager.AddToRoleAsync(user, model.RoleName);

                if (!result.Succeeded)
                {
                    return(View("Error", result.Errors));
                }
            }

            foreach (var userId in model.IdsToDelete ?? Enumerable.Empty <string>())
            {
                var user = await _userManager.FindByIdAsync(userId);

                result = await _userManager.RemoveFromRoleAsync(user, model.RoleName);

                if (!result.Succeeded)
                {
                    return(View("Error", result.Errors));
                }
            }

            return(RedirectToAction("Index"));
        }
コード例 #10
0
ファイル: Configuration.cs プロジェクト: munzerawad/WebShop
        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);
        }
コード例 #11
0
ファイル: AccountController.cs プロジェクト: syeluru/MIS333k
        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));
        }
コード例 #12
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //TODO: Add in other fields
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email, FName = model.FName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                await UserManager.AddToRoleAsync(user.Id, "User");

                // --OR--
                // await UserManager.AddToRoleAsync(user.Id, "Employee");


                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));
        }
コード例 #13
0
ファイル: UserService.cs プロジェクト: developeramarish/PTMS
        public async Task <UserModel> CreateUserAsync(NewUserModel model)
        {
            var user = new AppUser()
            {
                UserName             = model.Email,
                FirstName            = model.FirstName,
                LastName             = model.LastName,
                MiddleName           = model.MiddleName,
                Description          = model.Description,
                Email                = model.Email,
                EmailConfirmed       = true,
                PhoneNumber          = model.PhoneNumber,
                PhoneNumberConfirmed = true,
                Enabled              = true,
                ProjectId            = model.ProjectId,
                RouteIds             = model.RouteIds
            };

            var role = await _roleRepository.GetByIdAsync(model.RoleId);

            CheckRoleData(user, role);

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

            if (userResult.Succeeded)
            {
                var roleResult = await _userManager.AddToRoleAsync(user, role.NormalizedName);

                if (!roleResult.Succeeded)
                {
                    ThrowIdentityError(roleResult.Errors);
                }

                await _emailService.SendEmailAsync(
                    user.Email,
                    "Регистрация в системе ЦОДД",
                    GetNewUserEmail(user, model.Password));
            }
            else
            {
                ThrowIdentityError(userResult.Errors);
            }

            var result = await GetByIdFullAsync(user.Id);

            return(result);
        }
コード例 #14
0
        public async Task <IHttpActionResult> ManageUsersInRole(UsersInRoleModel model)
        {
            var role = await AppRoleManager.FindByIdAsync(model.Id);

            if (role == null)
            {
                ModelState.AddModelError("", "Role does not exist");
                return(BadRequest(ModelState));
            }

            foreach (string user in model.EnrolledUsers)
            {
                var appUser = await AppUserManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    ModelState.AddModelError("", String.Format("User: {0} does not exists", user));
                    continue;
                }

                if (!AppUserManager.IsInRole(user, role.Name))
                {
                    IdentityResult result = await AppUserManager.AddToRoleAsync(user, role.Name);

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", String.Format("User: {0} could not be added to role", user));
                    }
                }
            }

            foreach (string user in model.RemovedUsers)
            {
                var appUser = await AppUserManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    ModelState.AddModelError("", String.Format("User: {0} does not exists", user));
                    continue;
                }

                IdentityResult result = await AppUserManager.RemoveFromRoleAsync(user, role.Name);

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", String.Format("User: {0} could not be removed from role", user));
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
コード例 #15
0
        public async Task <ActionResult> CreateEmployee(CreateEmployeeViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, MI = model.MI, Address = model.Address, City = model.City, State = model.State, ZipCode = model.ZipCode, PhoneNumber = model.PhoneNumber, DOB = DateTime.Now, IsTerminated = false, IsActive = true, HasAccount = false
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await UserManager.AddToRoleAsync(user.Id, "Employee");

                    return(RedirectToAction("EmployeePortal", "Manage"));
                }
                AddErrors(result);
            }
            return(View(model));
        }
コード例 #16
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //TODO: Add fields to user here so they will be saved to do the database
                var user = new AppUser {
                    UserName = model.EmailAddress, Email = model.EmailAddress, FName = model.FName, LName = model.LName, DOB = model.DOB, StreetAddress = model.Address, City = model.City, ZIP = model.ZIP, PhoneNumber = model.PhoneNumber, PasswordHash = model.Password, State = model.State
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                string  user1 = User.Identity.GetUserId();
                AppUser u     = db.Users.Find(user1);
                if (User.IsInRole("Manager"))
                {
                    await UserManager.AddToRoleAsync(user.Id, "Employee");

                    Success(string.Format("New Employee created!"), true);
                    return(RedirectToAction("ManagerHome", "Account"));
                }
                else
                {
                    await UserManager.AddToRoleAsync(user.Id, "Customer");
                }
                // --OR--
                // await UserManager.AddToRoleAsync(user.Id, "Employee");

                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", "Apply"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #17
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FName       = model.FName,
                    LName       = model.LName,
                    PhoneNumber = model.phoneNumber,
                    OkToText    = model.OkToText,
                    Major       = model.Major
                };

                // Populate the data to Member as well and linked with UserID
                var member = new Member
                {
                    UserId      = user.Id,
                    Email       = model.Email,
                    FirstName   = model.FName,
                    LastName    = model.LName,
                    phoneNumber = model.phoneNumber,
                    OkToText    = model.OkToText,
                    Major       = model.Major
                };

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

                if (result.Succeeded)
                {
                    // Add to Role
                    await UserManager.AddToRoleAsync(user.Id, "Member");

                    // Add the record to Members
                    var db = new AppDbContext();
                    db.Members.Add(member);
                    db.SaveChanges();

                    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));
        }
コード例 #18
0
        public async Task <HttpResponseMessage> KorisnikUpdate(HttpRequestMessage request, [FromBody] KorisnikModel model)
        {
            HttpResponseMessage response = null;

            try
            {
                var user = await AppUserManager.FindByIdAsync(model.Id);

                user.Id            = model.Id;
                user.Email         = model.Email;
                user.GradId        = model.GradId;
                user.Ime           = model.Ime;
                user.Prezime       = model.Prezime;
                user.Ulica         = model.Ulica;
                user.Broj          = model.Broj;
                user.Telefon       = model.Telefon;
                user.PostanskiBroj = model.PostanskiBroj;
                user.IsDeleted     = model.IsOnemogucen;


                var result = await AppUserManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    var prethodneUloge = await AppUserManager.GetRolesAsync(user.Id);

                    foreach (var uloga in prethodneUloge)
                    {
                        await AppUserManager.RemoveFromRoleAsync(user.Id, uloga);
                    }

                    if ((model.Uloge.Contains("Admin") || model.Uloge.Contains("Uposlenik")) && model.Uloge.Contains("Klijent"))
                    {
                        model.Uloge = model.Uloge.Where(val => val != "Klijent").ToArray();
                    }

                    foreach (var uloga in model.Uloge)
                    {
                        await AppUserManager.AddToRoleAsync(user.Id, uloga);
                    }
                    response = request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    response = request.CreateResponse(HttpStatusCode.BadRequest, result.Errors);
                }
            }
            catch (Exception ex)
            {
                response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }

            return(response);
        }
コード例 #19
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.FName, MName = model.MName, LName = model.LName, StreetAddress = model.StreetAddress, City = model.City, State = model.State, ZipCode = model.ZipCode, PhoneNumber = model.PhoneNumber, IsAccountEnabled = model.IsAccountEnabled
                };


                db.SaveChanges();

                //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, "User"); //adds user to role called "User"
                // --OR--

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

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

                    //Send confirmation email
                    EmailController.AccountCreation(user);

                    //send them to the page to add their credit cards
                    return(RedirectToAction("CustomerDashboard", "Account"));
                }

                //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));
        }
コード例 #20
0
ファイル: Register.cshtml.cs プロジェクト: 1n1n1t3/qBIPro
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var role   = Input.Role;
                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

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

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

                    await _userManager.AddToRoleAsync(user, role);

                    //Add area
                    Area organization = new Area();
                    organization.Name = Input.Area;
                    _context.Add(organization);
                    if (await _context.SaveChangesAsync() != 0)
                    {
                        user.AreaId = organization.AreaId;
                        await _userManager.UpdateAsync(user);
                    }

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

            // If we got this far, something failed, redisplay form
            return(Page());
        }
コード例 #21
0
ファイル: AccountController.cs プロジェクト: Xunder46/HGRest
        public async Task <IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_repo.Exists(createUserModel.PhoneNumber))
            {
                return(BadRequest("Phone number is already taken"));
            }

            var user = new ApplicationUser()
            {
                UserName       = createUserModel.UserName,
                Email          = createUserModel.Email,
                CustomerInfoId = createUserModel.CustomerInfoId,
                JoinDate       = DateTime.Now.Date,
                PhoneNumber    = createUserModel.PhoneNumber,
                EmailConfirmed = true
            };

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

            if (addUserResult.Succeeded)
            {
                IdentityResult addRoleResult = await AppUserManager.AddToRoleAsync(user.Id, "Customer");

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

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

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

            //TODO: Uncomment to send email confirmations
            //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)));
        }
コード例 #22
0
        protected override async Task <CreateUserResult> RunAsync(YbpContext <UserRegistrationProcess> context, CreateUserInfo prm)
        {
            var user = new AppUser
            {
                Email       = prm.Email,
                UserName    = $"{prm.FirstName}_{prm.LastName}".Trim(),
                PhoneNumber = prm.PhoneNumber
            };

            var result = new CreateUserResult {
                Errors = new List <string>()
            };

            foreach (var v in _userManager.UserValidators)
            {
                var ir = await v.ValidateAsync(_userManager, user);

                if (ir.Succeeded)
                {
                    continue;
                }

                result.Errors.AddRange(ir.Errors.Select(x => x.Description));
            }

            if (result.Errors.Any())
            {
                return(result);
            }

            var u = await _userManager
                    .CreateAsync(user);

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

            result.UserId  = user.Id;
            result.Success = true;
            context.Id     = $"{user.Id}";
            await _userManager.AddToRoleAsync(user, prm.Role);

            if (prm.Role == SystemRole.RegularUser)
            {
                context.Flags[UserRegistrationProcess.Flags.NeedSendInvitation] = true;
            }

            return(result);
        }
コード例 #23
0
ファイル: AccountController.cs プロジェクト: Jatarie/Redd
        public async void Register([FromForm] UserRegistrationModel userRegistration)
        {
            AppUser user = await AppUserManager.FindByNameAsync(userRegistration.UserName);

            if (user == null)
            {
                user = new AppUser();
                user.PasswordHash = AppUserManager.PasswordHasher.HashPassword(user, userRegistration.Password);
                user.UserName     = userRegistration.UserName;
                await AppUserManager.CreateAsync(user);

                await AppUserManager.AddToRoleAsync(user, "Admin");
            }
        }
コード例 #24
0
        public async Task <IHttpActionResult> RegisterExternal(ExternalUserAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var externalAccessToken = await VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken);

            if (externalAccessToken == null)
            {
                return(BadRequest("Invalid Provider or External Access Token"));
            }

            AppUser appUser = await AppUserManager.FindAsync(new UserLoginInfo(model.Provider, externalAccessToken.user_id));

            if (appUser != null)
            {
                return(BadRequest("External user is already registered"));
            }

            appUser = new AppUser {
                UserName = model.Username, Email = model.Email, EmailConfirmed = true, JoinDate = DateTime.Now
            };

            IdentityResult result = await AppUserManager.CreateAsync(appUser, model.Password);

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

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

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

            var info = new ExternalLoginInfo
            {
                DefaultUserName = model.Username,
                Login           = new UserLoginInfo(model.Provider, externalAccessToken.user_id)
            };

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

            return(result.Succeeded ? Ok(GenerateLocalAccessTokenResponse(model.Username)) : GetErrorResult(result));
        }
コード例 #25
0
        public async Task <HttpResponseMessage> KorisnikKreiraj(HttpRequestMessage request, [FromBody] KorisnikModel model)
        {
            HttpResponseMessage response = null;

            try
            {
                var user = new Korisnik
                {
                    UserName      = model.Email,
                    Email         = model.Email,
                    GradId        = model.GradId,
                    Ime           = model.Ime,
                    Prezime       = model.Prezime,
                    Ulica         = model.Ulica,
                    Broj          = model.Broj,
                    Telefon       = model.Telefon,
                    PostanskiBroj = model.PostanskiBroj,
                    IsDeleted     = model.IsOnemogucen
                };
                var result = await AppUserManager.CreateAsync(user, model.Lozinka);

                if (result.Succeeded)
                {
                    if ((model.Uloge.Contains("Admin") || model.Uloge.Contains("Uposlenik")) && model.Uloge.Contains("Klijent"))
                    {
                        model.Uloge = model.Uloge.Where(val => val != "Klijent").ToArray();
                    }
                    foreach (var uloga in model.Uloge)
                    {
                        await AppUserManager.AddToRoleAsync(user.Id, uloga);
                    }
                    response = request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    response = request.CreateResponse(HttpStatusCode.BadRequest, result.Errors);
                }
            }
            catch (Exception ex)
            {
                response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }

            return(response);
        }
コード例 #26
0
        public async Task <IHttpActionResult> CreateUser(AccountCreateBindingModels accountCreateBindingModels)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var userInfo = new UserInfo()
            {
                FirstName         = accountCreateBindingModels.FirstName,
                LastName          = accountCreateBindingModels.LastName,
                JobTitle          = accountCreateBindingModels.JobTitle,
                Address           = accountCreateBindingModels.Address,
                Sex               = accountCreateBindingModels.Sex,
                IsEmployeeProfile = accountCreateBindingModels.IsEmployeeProfile,
                IsActiveEmployee  = accountCreateBindingModels.IsActiveEmployee
            };

            var user = new ApplicationUser()
            {
                UserName = accountCreateBindingModels.UserName,
                Email    = accountCreateBindingModels.Email,
                UserInfo = userInfo
            };

            IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, accountCreateBindingModels.Password).ConfigureAwait(true);

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

            // assigning default user role to user
            var            addedUser         = this.AppUserManager.FindByName(user.UserName);
            IdentityResult assignRolesResult = await AppUserManager.AddToRoleAsync(addedUser.Id, "User").ConfigureAwait(true);

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

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

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
コード例 #27
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            try
            {
                //Checks if model is valid
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                //Converts RegisterModel to AppUser type
                AppUser newUser = model.ToAppUserEntity();
                //Sets default properties for new user
                newUser.SetDefaultPhotoPathAndUserName();

                //Creates new user
                var result = await _appUserManager.CreateAsync(newUser, newUser.PasswordHash);

                //Checks if user is created and returns model with errors if it isn't
                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }

                    return(View("Index", model));
                }

                //Adds new user to role
                await _appUserManager.AddToRoleAsync(newUser, "normaluser");

                //Signs in new user
                await _signInManager.SignInAsync(newUser, false);

                //Gets id of new user to redirect him to his profile
                int currentUserId = await _appUserManager.GetCurrentUserIdAsync(newUser.Email);

                return(RedirectToAction("Profile", "User", new { id = currentUserId }));
            }
            catch
            {
                return(View(model));
            }
        }
コード例 #28
0
        public async Task <IHttpActionResult> AddUserToRole([FromBody] RoleBindingModel userData)
        {
            var role = await AppRoleManager.FindByIdAsync(userData.RoleId);

            if (role != null)
            {
                IdentityResult result = await AppUserManager.AddToRoleAsync(userData.UserId, role.Name);

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

                return(Ok());
            }

            return(NotFound());
        }
コード例 #29
0
        public async Task <ActionResult> AuditClubAY(int?id, string AuditDesc = "")
        {
            if (id == null)
            {
                Session["Error"] = "错误操作!审批过程未发现任务编号";
                return(RedirectToAction("Error404", "Home"));
            }
            ClubNumber club = db.ClubNumbers.Where(c => c.AuditID == id).FirstOrDefault();

            if (club == null)
            {
                Session["Error"] = "未发现社团";
                return(RedirectToAction("Error404", "Home"));
            }
            int res = AuditFun(id ?? 0, EnumAuditState.通过, AuditDesc);

            if (res == 1)
            {
                return(RedirectToAction("AuditClub", new { Msg = "社团申请任务[" + id + "]审批成功" }));
            }
            else if (res == 2)
            {
                club.State           = (int)EnumState.正常;
                club.CreateDate2     = DateTime.Now;
                db.Entry(club).State = System.Data.Entity.EntityState.Modified;
                if (club.User != null)
                {
                    AppUser        uid         = db.Users.Where(u => u.UserName == club.User.UserId).FirstOrDefault();
                    AppUserManager userManager = HttpContext.GetOwinContext().GetUserManager <AppUserManager>();
                    bool           c           = userManager.IsInRoleAsync(uid.Id, "CAdmin").Result;
                    if (!c)
                    {
                        await userManager.AddToRoleAsync(uid.Id, "CAdmin");
                    }
                }
                db.SaveChanges();
                return(RedirectToAction("AuditClub", new { Msg = "社团申请任务[" + id + "]审批成功" }));
            }
            else
            {
                return(RedirectToAction("AuditClub", new { Msg = "失败!社团申请任务[" + id + "]审批失败" }));
            }
        }
コード例 #30
0
ファイル: RolesController.cs プロジェクト: MrRevalis/Library
        public async Task <ActionResult> ManageRole(UserInRoleViewModel userList)
        {
            AppRole appRole = await RoleManager.FindByIdAsync(userList.RoleID);

            if (appRole == null)
            {
                ViewBag.Error = $"Error occurred while looking for role with ID = {userList.RoleID ?? "NULL ID"}";
                return(View("Error"));
            }

            for (int i = 0; i < userList.IsInRole.Count; i++)
            {
                AppUser user = await UserManager.FindByNameAsync(userList.Users[i]);

                IdentityResult result;
                if (userList.IsInRole[i] && !(await UserManager.IsInRoleAsync(user.Id, userList.RoleName)))
                {
                    result = await UserManager.AddToRoleAsync(user.Id, userList.RoleName);
                }
                else if (!userList.IsInRole[i] && await UserManager.IsInRoleAsync(user.Id, userList.RoleName))
                {
                    result = await UserManager.RemoveFromRoleAsync(user.Id, userList.RoleName);
                }
                else
                {
                    continue;
                }

                if (result.Succeeded)
                {
                    if (i < userList.IsInRole.Count)
                    {
                        continue;
                    }
                    else
                    {
                        return(RedirectToAction("EditRole", new { id = userList.RoleID }));
                    }
                }
            }

            return(RedirectToAction("EditRole", new { id = userList.RoleID }));
        }