Пример #1
0
        private void EnsureAdminExists(string adminUsername, string adminEmail)
        {
            _firstRun = false;
            var admin = _userManager.FindByName(adminUsername);

            if (admin != null)
            {
                return;
            }

            string adminFirstName = "Administrator";

            var adminAccount = new ApplicationUser
            {
                UserName  = adminUsername,
                Email     = adminEmail,
                FirstName = adminFirstName,
                LastName  = Constants.AppName
            };

            var result = _userManager.Create(adminAccount, "Admin123!");

            if (!result.Succeeded)
            {
                throw new Exception("Błąd podczas tworzenia konta administratora");
            }

            _userManager.AddClaim(adminAccount.Id, new Claim(ClaimTypes.Role, RoleName.Administrator));
            _userManager.AddClaim(adminAccount.Id, new Claim("FirstName", adminFirstName));
            SendEmailConfirmationTokenAsync(adminAccount.Id, "Administratorze, potwierdź swoje konto", RoleName.Administrator).Wait();
        }
Пример #2
0
        public string PostEditUserSpace(string value)
        {
            try
            {
                JObject userSpace = JObject.Parse(value);
                ApplicationDbContext         context     = new ApplicationDbContext();
                IUserStore <ApplicationUser> store       = new UserStore <ApplicationUser>(context);
                ApplicationUserManager       UserManager = new ApplicationUserManager(store);

                var userid  = userSpace["userId"].ToString();
                var spaceId = userSpace["spaceId"].ToString();

                var claims = UserManager.GetClaims(User.Identity.GetUserId());
                var claim  = claims.Where(a => a.Type == "SpaceId").FirstOrDefault();

                if (claim == null)
                {
                    UserManager.AddClaim(userid, new Claim("SpaceId", spaceId));
                }
                else
                {
                    UserManager.RemoveClaim(userid, claim);
                    UserManager.AddClaim(userid, new Claim("SpaceId", spaceId));
                }

                // log creation user
                logger.Info(" User :"******" - PostEditUserSpace : " + value);
                return(JsonConvert.SerializeObject(new { error = false }));
            }
            catch (Exception ex)
            {
                logger.Error(" User :"******" - message : " + ex.Message);
                return(JsonConvert.SerializeObject(new { error = true, errorMessage = "PostEditUserSpaceFailed" }));
            }
        }
Пример #3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.phoneNo
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
                    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));
        }
Пример #4
0
        public async Task <ActionResult> RegisterCompany(RegisterViewModelCompany model, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext()));


                    if (!roleManager.RoleExists("Admin"))
                    {
                        var role = new IdentityRole();
                        role.Name = "Admin";
                        roleManager.Create(role);
                    }
                    var roleresult = UserManager.AddToRole(user.Id, "Admin");

                    ApplicationDbContext db = new ApplicationDbContext();
                    Company c = new Company();
                    c.CompanyName        = model.CompanyName.ToUpper();
                    c.CompanyDescription = model.CompanyDescription.ToUpper();
                    // c.CompanyLogo = model.CompanyLogo;
                    var path = Server != null?Server.MapPath("~") : "";

                    c.SaveLogo(image, path, "/ProfileImages/");
                    c.ApplicationUserId = user.Id;

                    db.Companies.Add(c);
                    db.SaveChanges();

                    // to display the name in the Hello user! a claim is created
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, c.CompanyName));

                    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", "Companies"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #5
0
        public async Task <ActionResult> Cadastro(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //Select max(idUser) + 1 from AspNetUsers
                var maxIdUser = (from u in context.Users
                                 orderby u.IdUser descending
                                 select u).Take(1);
                int x = await context.Users.MaxAsync(y => y.IdUser);

                var newIdUser = x + 1;
                model.IdUser = newIdUser;


                ApplicationUser user = new ApplicationUser();
                IModelFactory   mf   = new ModelFactory();
                user = mf.Create(model);

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

                if (result.Succeeded)
                {
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.UserData, model.IdUser.ToString()));

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmacaoEmail", "Conta",
                                                 new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id,
                                                     "Confirme sua conta", "Confirme sua conta clicando <a href=\""
                                                     + callbackUrl + "\">aqui</a>");

                    ViewBag.Msg = "<p>Email de confirmação enviado para <span style = 'color:#EE573C'>" + user.Email.ToString() + "</span></p> <br> <p>Verifique seu inbox e confirme seu endereço</p>";

                    return(View("ShowMsg"));
                }


                AddErrors(result);
            }

            var grads = GetLstGraduation();
            var sts   = GetUfs();

            model.Grads  = GetSelectListItems(grads);
            model.States = GetSelectListItems(sts);

            return(View(model));
        }
Пример #6
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            _logger.Debug("ini Register - process");
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.Debug("ini Register - inValid");
                    return(BadRequest(ModelState));
                }

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

                IdentityResult addUserResult = await _appUserManager.CreateAsync(user, model.Password);

                if (!addUserResult.Succeeded)
                {
                    _logger.Debug("ini Register - GetErrorResult");
                    return(GetErrorResult(addUserResult));
                }

                _logger.Debug(string.Format("user register info email:{0}, idUser:{1}", user.Email, user.Id));

                _appUserManager.AddToRole(user.Id, "member");
                _appUserManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "member"));
                _appUserManager.AddClaim(user.Id, new Claim(ClaimTypes.Authentication, "local"));

                string generatedCode = await _appUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                Uri callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { idUser = user.Id, code = generatedCode, confirmURL = Helpers.Encrypt(model.ConfirmURL) }));

                string bodyHtmlEmail = Helpers.CreateBodyEmail(user, callbackUrl.ToString());

                await _appUserManager.SendEmailAsync(user.Id, "Confirm your account", bodyHtmlEmail);

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

                _logger.Debug("ini Register - Success");
                _appUserManager.Update(user);
                return(Created(locationHeader, ModelFactory.Create(user)));
            }
            catch (Exception ex)
            {
                LogError(ex);
                return(InternalServerError(ex));
            }
        }
Пример #7
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    //FirstName = model.FirstName,
                    //LastName = model.LastName,
                    UserName = model.Email,
                    Email    = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.Surname, model.LastName));
                    /////////////
                    //password?////
                    /////////////

                    CMSComputersEntities db = new CMSComputersEntities();

                    db.Employees.Add(new CMSComputersMVC.Models.Employee()
                    {
                        FirstName    = model.FirstName,
                        LastName     = model.LastName,
                        LocalPhone   = null,
                        EmailAddress = user.Email,
                        UserName     = user.UserName,
                        Password     = BusinessLogic.HashMethods.HashSha256(model.Password),
                        Active       = true
                    });

                    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));
        }
        protected override void Seed(ApplicationDbContext context)
        {
            var store = new UserStore <ApplicationUser>(context);
            //var manager = new UserManager<ApplicationUser>(store);
            var manager = new ApplicationUserManager(store);

            if (!context.Users.Any(u => u.UserName == "Kevin"))
            {
                // Using a custom encrypted password.
                var password = HashHelper.Sha512("Kevin" + "secret");

                var user = new ApplicationUser
                {
                    UserName = "******",
                    IsActive = true,
                    Id       = "b05d3546-6ca8-4d32-b95c-77e94d705ddf",
                    Password = password
                };
                manager.Create(user, "secret");
            }

            if (context.Users.Any(u => u.UserName == "Kevin"))
            {
                var user = manager.Users.FirstOrDefault(u => u.UserName == "Kevin");

                if (!user.Claims.Any(c => c.ClaimType == "given_name"))
                {
                    manager.AddClaim(user.Id, new Claim("given_name", "Kevin"));
                }

                if (!user.Claims.Any(c => c.ClaimType == "family_name"))
                {
                    manager.AddClaim(user.Id, new Claim("family_name", "Dockx"));
                }

                if (!user.Claims.Any(c => c.ClaimType == "address"))
                {
                    manager.AddClaim(user.Id, new Claim("address", "1, Main Street, Antwerp, Belgium"));
                }

                if (!user.Claims.Any(c => c.ClaimType == "role"))
                {
                    manager.AddClaim(user.Id, new Claim("role", "PayingUser"));
                }

                if (!user.Claims.Any(c => c.ClaimType == "email"))
                {
                    manager.AddClaim(user.Id, new Claim("email", "*****@*****.**"));
                }
            }
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = UserManager.Find(model.UserName, model.Password);

            if (user != null)
            {
                if (!await UserManager.IsEmailConfirmedAsync(user.Id))
                {
                    ViewBag.errorMessage = "Debe tener un correo electrónico confirmado para iniciar sesión." +
                                           "El token de confirmación ha sido reenviado a su cuenta de correo electrónico.";
                    return(View("Error"));
                }
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                var data  = UserManager.Find(model.UserName, model.Password);
                var juser = JsonConvert.SerializeObject(new CurrentUser {
                    Email                = data.Email,
                    Name                 = data.Name,
                    LastName             = data.LastName,
                    UserName             = data.UserName,
                    UserId               = data.Id,
                    NumberIdentification = data.NumberIdentification
                });
                if (data.Name == null)
                {
                    return(RedirectToAction("UpdateAdminAccount", "Account"));
                }
                UserManager.AddClaim(data.Id, new Claim(ClaimTypes.UserData, juser));
                return(RedirectToAction("Index", "Admin"));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            default:
                ModelState.AddModelError("", "Intento de inicio de sesión inválido");
                return(View(model));
            }
        }
Пример #10
0
        protected override void Seed(MoviesWebAPIApp.Models.ApplicationDbContext context)
        {
            // let's add some users
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new ApplicationUserManager(userStore);

            // Ensure Mike (admin)
            var mike = userManager.FindByName("*****@*****.**");

            if (mike == null)
            {
                // create user
                mike = new ApplicationUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };
                userManager.Create(mike, "Secret123!");

                // add claims
                userManager.AddClaim(mike.Id, new Claim("CanEditMovies", "true"));
                userManager.AddClaim(mike.Id, new Claim(ClaimTypes.DateOfBirth, "12/25/1977"));
            }
            // Ensure Alex (non-admin)
            var alex = userManager.FindByName("*****@*****.**");

            if (alex == null)
            {
                // create user
                alex = new ApplicationUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };
                userManager.Create(alex, "Secret123!");
            }


            // Ensure one guestbook entry
            if (context.Entries.Count() == 0)
            {
                context.Entries.Add(new Entry()
                {
                    Author      = "Stephen",
                    DateCreated = DateTime.Now,
                    Message     = "Thanks for visiting Coder Camps!"
                });
            }
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                // 20190515 -PS- Add claim
                var person = _context.Persons.Where(p => p.Name == model.UserName).FirstOrDefault <Person>();
                if (person != null)
                {
                    UserManager.AddClaim(model.UserName, new Claim("PublisherName", person.Name));
                }

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Пример #12
0
        private void UpdateStravaAccessTokenClaim(AccessToken accessToken)
        {
            var userId = User.Identity.GetUserId();

            _log.Debug("Update strava access token claim for {userId}", userId);

            var context = Request.GetOwinContext();
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            var claims    = manager.GetClaims(userId).ToList();
            var oldClaims = claims.Where(c => c.Type == StravaAccessTokenClaim);

            _log.Debug("Removing nr of old tokens {nrOfOldClaims}", oldClaims.Count());

            foreach (var claim in oldClaims)
            {
                manager.RemoveClaim(userId, claim);
            }

            if (accessToken != null && !string.IsNullOrEmpty(accessToken.Token))
            {
                _log.Debug("Adding token claim for user {userId}, token: {token}", userId, accessToken.Token);

                manager.AddClaim(userId, new Claim(StravaAccessTokenClaim, accessToken.Token));
            }
        }
    public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value, ApplicationUserManager userManager)
    {
        var identity = currentPrincipal.Identity as ClaimsIdentity;

        if (identity == null)
        {
            return;
        }
        // check for existing claim and remove it
        var existingClaim = identity.FindFirst(key);

        if (existingClaim != null)
        {
            RemoveClaim(currentPrincipal, key, userManager);
        }
        // add new claim
        var claim = new Claim(key, value);

        identity.AddClaim(claim);
        var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

        authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties()
        {
            IsPersistent = true
        });
        //Persist to store
        userManager.AddClaim(identity.GetUserId(), claim);
    }
Пример #14
0
        public new ActionResult Profile(ProfileViewModel model, string returnUrl = null)
        {
            var user = UserManager.FindById(User.Identity.GetUserId());

            if (ModelState.IsValid)
            {
                var claims = UserManager.GetClaims(user.Id);

                user.FirstName = model.FirstName;
                user.LastName  = model.LastName;
                user.BarCode   = model.BarCode;
                UserManager.Update(user);

                foreach (var claim in claims)
                {
                    UserManager.RemoveClaim(user.Id, claim);
                }

                UserManager.AddClaim(user.Id, new Claim("FirstName", user.FirstName));
                return(RedirectToAction(nameof(HomeController.Index), "Home"));
            }
            else
            {
                ViewBag.user      = user;
                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

                //   string outputdata = Newtonsoft.Json.JsonConvert.SerializeObject(user);

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

                if (result.Succeeded)
                {
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));

                    // var service = new SurveryManageService(HttpContext.GetOwinContext().Get<ApplicationDbContext>());
                    //service.CreateCheckingAccount(model.FirstName, model.LastName, user.Id, 0);

                    await SignInAsync(user, 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));
        }
Пример #16
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //Adding a claim & add to details to db details for user.

                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));//adding claims(by GivenNames)
                    var service = new CheckingAccountService(HttpContext.GetOwinContext().Get <ApplicationDbContext>());
                    service.CreateCheckingAccount(model.FirstName, model.LastName, user.Id, 0);
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);


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

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

                if (result.Succeeded)
                {
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
                    var db      = new ApplicationDbContext();
                    var service = new CheckingAccountService(HttpContext.GetOwinContext().Get <ApplicationDbContext>());
                    service.CreateCheckingAccount(model.FirstName, model.LastName, user.Id, 0);
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // E-Mail-Nachricht mit diesem Link senden
                    // 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, "Konto bestätigen", "Bitte bestätigen Sie Ihr Konto. Klicken Sie dazu <a href=\"" + callbackUrl + "\">hier</a>");

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

            // Wurde dieser Punkt erreicht, ist ein Fehler aufgetreten; Formular erneut anzeigen.
            return(View(model));
        }
Пример #18
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AutoScoutIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //get the context
                    var service = new DealershipAccountService(HttpContext.GetOwinContext().Get <AutoScoutDBContext>());

                    //register dealers AutoScout account from Identity
                    service.RegisterDealershipAccount(model.CompanyName, user.Id, model.Email, model.City, model.State, model.ZipCode, model.PhoneNumber, model.FaxNumber, model.Notes);

                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.CompanyName));

                    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));
        }
Пример #19
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (user.Email == "*****@*****.**")
                    {
                        UserManager.AddToRole(user.Id, "Admin");
                        UserManager.AddClaim(user.Id, new Claim("access", "partial"));
                    }
                    //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit https://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("PromptEmailConfirmation", "Account"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #20
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));

                    var service = new CheckingAccountService(HttpContext.GetOwinContext().Get <ApplicationDbContext>());

                    service.CreateCheckingAccount(model.FirstName, model.LastName, user.Id, 0.00m);

                    //var db = new ApplicationDbContext();
                    //var totalAccounts = db.CheckingAccounts.Count();
                    //var checkingAccount = new CheckingAccount
                    //{
                    //    FirstName = model.FirstName,
                    //    LastName = model.LastName,
                    //    AccountNumber = String.Format($"{totalAccounts}").PadLeft(10, '0'),
                    //    Balance = 0.00m,
                    //    ApplicationUserId = user.Id
                    //};

                    //db.CheckingAccounts.Add(checkingAccount);
                    //db.SaveChanges();

                    //try
                    //{
                    //    db.CheckingAccounts.Add(checkingAccount);
                    //    db.SaveChanges();
                    //}
                    //catch (DbEntityValidationException e)
                    //{
                    //    var newException = new FormattedDbEntityValidationException(e);
                    //    throw newException;
                    //}

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://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));
        }
Пример #21
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, Name = model.Name
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var roleStore   = new RoleStore <IdentityRole>(new ApplicationDbContext());
                    var roleManager = new RoleManager <IdentityRole>(roleStore);
                    await roleManager.CreateAsync(new IdentityRole(RoleName.Patient));

                    await UserManager.AddToRoleAsync(user.Id, RoleName.Patient);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);


                    Patient patient = new Patient()
                    {
                        Name         = model.Name,
                        Patient_Id   = user.Id,
                        PatientEmail = model.Email,
                        BirthDate    = DateTime.Now
                    };

                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, user.Name));
                    db.Patients.Add(patient);
                    db.SaveChanges();
                    // For more information on how to enable account confirmation and password reset please visit https://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));
        }
Пример #22
0
        private void CreateEntrantUsers()
        {
            var user = new ApplicationUser();

            user.UserName = "******";
            const string password = "******";

            if (_userManager.FindByName(user.UserName) == null)
            {
                var identityResult = _userManager.Create(user, password);

                if (identityResult.Succeeded)
                {
                    _userManager.AddToRole(user.Id, Role.Entrant);
                    _userManager.AddClaim(user.Id, new Claim(MyClaimTypes.EntityUserId, "1"));
                }
            }
        }
Пример #23
0
 private void AddNameAsClaim(CCGAppUser user)
 {
     if (user != null)
     {
         // Adds claim with name which is appended to the cookie. This allows
         // for the display of the user's name in the nav bar.
         UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, user.FirstName));
     }
 }
Пример #24
0
        protected override void Seed(MyFamilyPlanner.Models.ApplicationDbContext context)
        {
            var members = new Member[] {
                new Member {
                    FirstName = "Jessica",
                    LastName  = "Sapio",
                    Email     = "*****@*****.**",
                    Phone     = "832-296-0149"
                },
                new Member {
                    FirstName = "Stacy",
                    LastName  = "Sapio",
                    Email     = "*****@*****.**",
                    Phone     = "832-326-2842"
                }
            };

            // Add or update based off of last name
            context.Members.AddOrUpdate(p => p.LastName, members);

            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new ApplicationUserManager(userStore);

            // Ensure Stephen
            var user = userManager.FindByName("*****@*****.**");

            if (user == null)
            {
                // create user
                user = new ApplicationUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };
                userManager.Create(user, "Secret123!");

                // add claims
                userManager.AddClaim(user.Id, new Claim("CanEditProducts", "true"));
                userManager.AddClaim(user.Id, new Claim(ClaimTypes.DateOfBirth, "12/25/1966"));
            }
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new SchedulerUser
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                // Todo: this will throw an error if the password isn't correct.. hence ViewModel password regex validation
                if (result.Errors.Any())
                {
                    AddErrors(result);
                    return(View(model));
                }


                UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, user.FirstName));

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, false, 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));
        }
Пример #26
0
        public async Task <IHttpActionResult> PostUsers(UserModel model)
        {
            try
            {
                _logger.Debug(string.Format("ini process - Post,idUser:{0}", CurrentIdUser));

                if (!ModelState.IsValid)
                {
                    _logger.Debug(string.Format("ini Post - inValid,idUser:{0}", CurrentIdUser));
                    return(BadRequest(ModelState));
                }

                User user = AutoMapper.Mapper.Map <User>(model);

                _logger.Debug(string.Format("ini create ,idUser:{0}", CurrentIdUser));

                IdentityResult addUserResult = _appUserManager.Create(user, model.Password);

                if (!addUserResult.Succeeded)
                {
                    _logger.Debug(string.Format("ini Post - GetErrorResult,idUser:{0}", CurrentIdUser));
                    return(GetErrorResult(addUserResult));
                }

                _logger.Debug(string.Format("user Post info email:{0}, idUser:{1}", user.Email, user.Id));

                Role role = _roleBL.Get(model.IdRole);

                _logger.Debug(string.Format("user Post info role:{0}, idUser:{1}", role.Name, user.Id));

                _appUserManager.AddToRole(user.Id, role.Name);
                _appUserManager.AddClaim(user.Id, new Claim(ClaimTypes.Authentication, "local"));

                string generatedCode = await _appUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                string callbackUrl = string.Format("{0}/{1}/{2}", model.ConfirmURL, user.Id, System.Web.HttpUtility.UrlEncode(generatedCode));

                string bodyHtmlEmail = Helpers.CreateBodyEmail(user, callbackUrl);

                await _appUserManager.SendEmailAsync(user.Id, "Confirm your account", bodyHtmlEmail);

                _logger.Debug(string.Format("finish create ,idUser:{0},newIdUser{1}", CurrentIdUser, user.Id));

                return(Ok(new JsonResponse {
                    Success = true, Message = "User was Saved successfully", Data = user
                }));
            }
            catch (Exception ex)
            {
                LogError(ex);
                return(InternalServerError(ex));
            }
        }
Пример #27
0
        //Mycode
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //======Review 18/2
                    //var db = new ApplicationDbContext();
                    //var accountNumber = (123456 + db.CheckingAccounts.Count()).ToString().PadLeft(10,'0');
                    //var checkingAccount = new CheckingAccount {
                    //    FirstName = model.FirstName, LastName = model.LastName,AccountNumber= accountNumber,
                    //    Balance=0
                    //,ApplicationUserId= user.Id};
                    //
                    //db.CheckingAccounts.Add(checkingAccount);
                    //db.SaveChanges();
                    //========end review 18/2

                    //21/2 coding the service
                    var service = new CheckingAccountService(HttpContext.GetOwinContext().Get <ApplicationDbContext>());
                    service.CreateCheckingAccount(
                        firstName: model.FirstName,
                        lastName: model.LastName,
                        userId: user.Id,
                        initialBalance: 0
                        );
                    //21/2

                    //add a Claim to use easly
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));


                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://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));
        }
Пример #28
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                user.LockoutEndDateUtc = DateTime.Now.Add(UserManager.DefaultAccountLockoutTimeSpan);
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var db          = new ApplicationDbContext();
                    var newEmployee = new Employee {
                        ApplicationUserId = user.Id,
                        LastName          = model.LastName,
                        FirstName         = model.FirstName,
                        DateOfBirth       = model.DateOfBirth,
                        Email             = model.Email,
                        sex              = model.Gender.ToString(),
                        MaritalStatus    = model.MaritalStatus.ToString(),
                        NumberOfChildren = model.NoOfChildren
                    };

                    db.AllEmployees.Add(newEmployee);
                    db.SaveChanges();
                    //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    UserManager.AddClaim(user.Id, new Claim("LastName", model.LastName));
                    UserManager.AddClaim(user.Id, new Claim("FirstName", model.FirstName));
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.MobilePhone, model.Phone));
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.Email, model.Email));
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.DateOfBirth, model.DateOfBirth.ToString()));
                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.Gender, model.Gender.ToString()));
                    UserManager.AddClaim(user.Id, new Claim("MaritalStatus", model.MaritalStatus.ToString()));
                    UserManager.AddClaim(user.Id, new Claim("NumberOfChildren", model.NoOfChildren.ToString()));
                    // For more information on how to enable account confirmation and password reset please visit https://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("Lockout", "Employee"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #29
0
        protected override void Seed(ApplicationDbContext context)
        {
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new ApplicationUserManager(userStore);

            // Ensure Stephen
            var user = userManager.FindByName("*****@*****.**");

            if (user == null)
            {
                // create user
                user = new ApplicationUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };
                userManager.Create(user, "Secret123!");

                // add claims
                userManager.AddClaim(user.Id, new Claim("CanViewMovies", "true"));
                userManager.AddClaim(user.Id, new Claim(ClaimTypes.DateOfBirth, "12/25/1966"));
            }
        }
Пример #30
0
        public JsonResult Create(string model)
        {
            try
            {
                UserInvitationViewModel invitation = JsonConvert.DeserializeObject <UserInvitationViewModel>(model);
                if (_userManager.FindByEmail(invitation.UserEmail) != null)
                {
                    Response.StatusCode = (int)System.Net.HttpStatusCode.Conflict;
                    return(JsonError("User already exists."));
                }

                DojoLogger.Trace(string.Format("Inviting user '{0}', email '{1} to join Dojo.", invitation.UserName, invitation.UserEmail), typeof(UserRoleManagerController));

                ApplicationUser newUser = new ApplicationUser()
                {
                    UserName = invitation.UserName,
                    Email    = invitation.UserEmail,
                };

                IdentityResult result = _userManager.Create(newUser, invitation.InvitationCode);
                DojoLogger.Trace(string.Format("Creating User '{0}', email '{1} in DB.", invitation.UserName, invitation.UserEmail), typeof(UserRoleManagerController));
                if (result == IdentityResult.Success)
                {
                    newUser = _userManager.FindByEmail(invitation.UserEmail);
                    _userManager.AddClaim(newUser.Id, new Claim(AppConstants.INVITATION_CLAIM, "1"));
                    _userManager.AddClaim(newUser.Id, new Claim(AppConstants.INVITATION_CODE_CLAIM, invitation.InvitationCode));
                    _userManager.AddClaim(newUser.Id, new Claim(AppConstants.EXPIRATION_DATE_CLAIM, invitation.ExpirationDate.ToString("MM/dd/yyyy")));
                    _userManager.AddClaim(newUser.Id, new Claim(AppConstants.ROLES_CLAIM, StringifyTuples(invitation.UserRoles)));

                    DojoLogger.Trace(string.Format("Sending invitation email to User '{0}', ID {1}.", invitation.UserName, newUser.Id), typeof(UserRoleManagerController));

                    // send invitation email to user
                    SendInvitationEmail(newUser.Id, invitation);

                    Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
                    return(Json(invitation, JsonRequestBehavior.AllowGet)); // keep claims out of it
                }
                else
                {
                    Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                    return(Json("Unable to create invited user.", JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("Inviting user fails. {0}", ex.Message);
                DojoLogger.Warn(message, typeof(UserRoleManagerController));

                Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return(Json(message, JsonRequestBehavior.AllowGet));
            }
        }