Esempio n. 1
0
        public ActionResult Register(RegisteredUser newUser)
        {
            // TAKING THE WRONG MODEL AS INPUT???
            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore)
            {
                UserLockoutEnabledByDefault = true,
                DefaultAccountLockoutTimeSpan = new TimeSpan(0, 10, 0),
                MaxFailedAccessAttemptsBeforeLockout = 3
            };

            var identityUser = new IdentityUser()
            {
                UserName = newUser.UserName,
                Email = newUser.Email
            };

            // this threw an error, but it also worked so what gives???
            IdentityResult result = manager.Create(identityUser, newUser.Password);
            if (result.Succeeded)
            {
                CreateTokenProvider(manager, EMAIL_CONFIRMATION);
                // identityUser.Id use this to create an entry in our accounts table 
                var code = manager.GenerateEmailConfirmationToken(identityUser.Id);
                var callbackUrl = Url.Action("VerifiedEmail", "Accounts",
                                                new { userId = identityUser.Id, code = code },
                                                    protocol: Request.Url.Scheme);

                string email = "Please confirm your account by clicking this link: <a href=\""
                                + callbackUrl + "\">Confirm Registration</a>";


                ViewBag.FakeConfirmation = email;
                UserAccountVMRepo uaRepo = new UserAccountVMRepo();
                uaRepo.CreateAccount(newUser.FirstName, newUser.LastName, identityUser.Id);

                // CREATE WITH CONSUMER ROLE BY DEFAULT
                SecurityEntities context = new SecurityEntities();
                AspNetUser user = context.AspNetUsers
                                 .Where(u => u.UserName == newUser.UserName).FirstOrDefault();
                AspNetRole role = context.AspNetRoles
                                 .Where(r => r.Name == "consumer").FirstOrDefault();

                user.AspNetRoles.Add(role);
                context.SaveChanges();

                MailHelper mailer = new MailHelper();
                string response = mailer.EmailFromArvixe(
                                           new RegisteredUser(newUser.Email, newUser.Subject = "Confirm Email", newUser.Body = email));

                ViewBag.Response = response;
                return View("ConfirmEmail");
            }
            return View();
        }
        private void sendConfirmationEmail(User user)
        {
            var provider = new MachineKeyProtectionProvider();
            UserManager<User, int> um = new UserManager<User, int>(ur);
            um.UserTokenProvider = new DataProtectorTokenProvider<User, int>(provider.Create("EmailConfirmation"));
            um.EmailService = new EmailService();
            TempData.Add("confirmEmail", "Le hemos enviado un correo electrónico para confirmar su cuenta, comprube la carpeta spam");

            if (Url != null)
            {
                var code = um.GenerateEmailConfirmationToken(user.U_id);
           
                var callbackUrl = Url.Action(
                "ConfirmEmail", "Home",
                new { userId = user.Id, code = code },
                protocol: "http");
                um.SendEmail(user.Id,
                           "Confirma tu correo",
                           "Por favor confirme su correo haciendo click en este <a href=\""
                                                           + callbackUrl + "\">link</a>");
            }
        }
        public ActionResult Register(RegisteredUser newUser)
        {
            CaptchaHelper captchaHelper = new CaptchaHelper();
            string captchaResponse = captchaHelper.CheckRecaptcha();
            if (captchaResponse != "Valid")
            {
                ViewBag.ErrorResponse = "The captcha must be valid";
                return View();

            }

            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore)
            {
                UserLockoutEnabledByDefault = true,
                DefaultAccountLockoutTimeSpan = new TimeSpan(0, 10, 0),
                MaxFailedAccessAttemptsBeforeLockout = 3
            };

            var identityUser = new IdentityUser()
            {
                UserName = newUser.UserName,
                Email = newUser.Email
            };
            IdentityResult result = manager.Create(identityUser, newUser.Password);

            if (result.Succeeded)
            {

                if (newUser.UserRole.Equals("Buyer") || newUser.UserRole.Equals("Farm"))
                {
                    //Taking the username on the account successful creation and applying it to the
                    //Farm database to create a Farm table with that username under the 'farmName' field.
                    AccountRepo accountRepo = new AccountRepo();
                    accountRepo.InitializeUserAccount(newUser);
                }

                var authenticationManager
                                  = HttpContext.Request.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(identityUser,
                                           DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { },
                                             userIdentity);
                string testVariable = newUser.UserRole;
                AddUserToRole(newUser.UserName, newUser.UserRole);

                CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                var code = manager.GenerateEmailConfirmationToken(identityUser.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                new { userId = identityUser.Id, code = code },
                                                    protocol: Request.Url.Scheme);

                string emailMessage = "Please confirm your account by clicking this link: <a href=\""
                                    + callbackUrl + "\">Confirm Registration</a>";

                string response = new MailHelper().EmailFromArvixe(new ViewModels.Message(newUser.Email, emailMessage));

                ViewBag.ConfirmationResponse = response;
                TempData["ConfirmationResponse"] = "You have successfully registered for an account. Please verify your account by clicking on the link sent to you in your e-mail.";
                return RedirectToAction("Login");
            }
            ViewBag.ErrorResponse = "There was an error with the input provided";
            return View();
        }
Esempio n. 4
0
        public ActionResult Register(RegisteredUserVM newUser)
        {
            var userStore = new UserStore <IdentityUser>();
            UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore)
            {
                UserLockoutEnabledByDefault          = true,
                DefaultAccountLockoutTimeSpan        = new TimeSpan(0, 10, 0),
                MaxFailedAccessAttemptsBeforeLockout = 5
            };
            var identityUser = new IdentityUser()
            {
                UserName = newUser.UserName,
                Email    = newUser.Email
            };

            if (ModelState.IsValid)
            {
                CaptchaHelper     captchaHelper   = new CaptchaHelper();
                OneListCAEntities context         = new OneListCAEntities();
                string            captchaResponse = captchaHelper.CheckRecaptcha();
                if (captchaResponse == "Valid")
                {
                    if (manager.FindByEmail(newUser.Email) == null)
                    {
                        ViewBag.CaptchaResponse = captchaResponse;
                        IdentityResult result = manager.Create(identityUser, newUser.Password);
                        if (result.Succeeded)
                        {
                            AspNetUser user = context.AspNetUsers
                                              .Where(u => u.UserName == newUser.UserName).FirstOrDefault();
                            AspNetRole role = new AspNetRole();
                            role.Id   = "User";
                            role.Name = "User";

                            user.AspNetRoles.Add(context.AspNetRoles.Find(role.Id));
                            context.SaveChanges();
                            //add information of user and password to table users in core
                            CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                            var code        = manager.GenerateEmailConfirmationToken(identityUser.Id);
                            var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                         new { userId = identityUser.Id, code = code },
                                                         protocol: Request.Url.Scheme);

                            //string email = "Please confirm your account by clicking this link: <a href=\""
                            //                + callbackUrl + "\">Confirm Registration</a>";
                            SendGrid.sendEmail(newUser, callbackUrl);
                            ViewBag.Result = "Please check your email to activate your account!";
                        }
                        else
                        {
                            ViewBag.Result = "User already exist!";
                        }
                    }
                    else
                    {
                        ViewBag.Result = "User already exist!";
                    }
                }
                else
                {
                    ViewBag.Result = "Registration failed!";
                }
            }

            return(View());
        }
Esempio n. 5
0
        /// <summary>
        /// Creates new user and assigns user to role
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            //var manager = new UserManager();
            //var user = new ApplicationUser() { UserName = UserName.Text, Email = UserName.Text };
            //IdentityResult result = manager.Create(user, Password.Text);
            //if (result.Succeeded)
            //{
            //    IdentityHelper.SignIn(manager, user, isPersistent: false);
            //    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            //}
            //else
            //{
            //    ErrorMessage.Text = result.Errors.FirstOrDefault();
            //}

            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdUserResult;

            // Create a RoleStore object by using the ApplicationDbContext object.
            // The RoleStore is only allowed to contain IdentityRole objects.
            var roleStore = new RoleStore <IdentityRole>(context);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
            var roleMgr = new RoleManager <IdentityRole>(roleStore);

            var userMgr = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = UserName.Text,
                Email    = Email.Text
            };

            IdUserResult = userMgr.Create(appUser, Password.Text);

            //assign new user to default biostat role
            if (IdUserResult.Succeeded)
            {
                //Add email confirmation

                var provider = new DpapiDataProtectionProvider("ProjectManagement");
                userMgr.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(
                    provider.Create("EmailConfirmation"));


                string code        = userMgr.GenerateEmailConfirmationToken(appUser.Id);
                string callBackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, appUser.Id, Request);

                string sendTo  = Email.Text;
                string subject = "QHS Project Tracking System - Confirm your account";
                string body    = "Please confirm your account by clicking <a href=\"" + callBackUrl + "\">here</a>";

                IdentityMessage im = new IdentityMessage()
                {
                    Subject     = subject,
                    Destination = sendTo,
                    Body        = body,
                };
                EmailService emailService = new EmailService();
                emailService.Send(im);

                //Add user as guest
                if (roleMgr.RoleExists("Guest"))
                {
                    if (!userMgr.IsInRole(userMgr.FindByEmail(Email.Text).Id, "Guest"))
                    {
                        IdUserResult = userMgr.AddToRole(userMgr.FindByEmail(Email.Text).Id, "Guest");
                    }
                }

                //Website should automatically log user in if email is already confirmed,
                //otherwise, they should click the confirmation link in their email.
                if (appUser.EmailConfirmed)
                {
                    var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();
                    signinManager.PasswordSignIn(UserName.Text, Password.Text, isPersistent: true, shouldLockout: false);
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else
                {
                    ErrorMessage.Text = "An email has been sent to your account.  Please view the email and confirm your" +
                                        " account to complete the registration process.";
                    registerForm.Visible = false;
                }
            }
            else
            {
                ErrorMessage.Text = IdUserResult.Errors.FirstOrDefault();
            }
        }
        public ActionResult Register(RegisteredUser newUser)
        {
            //when user registers in checks model requirements to ensure valid input
            if (ModelState.IsValid)
            {
                CaptchaHelper captchaHelper = new CaptchaHelper();
                string captchaResponse = captchaHelper.CheckRecaptcha();
                ViewBag.CaptchaResponse = captchaResponse;

                // add user to database, lock account until email confirmation
                var userStore = new UserStore<IdentityUser>();
                UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore)
                {
                    //set account to lock after consecutive failed login attempts
                    UserLockoutEnabledByDefault = true,
                    DefaultAccountLockoutTimeSpan = new TimeSpan(0, 10, 0),
                    MaxFailedAccessAttemptsBeforeLockout = 3
                };

                var identityUser = new IdentityUser()
                {
                    UserName = newUser.UserName,
                    Email = newUser.Email
                };
                IdentityResult result = manager.Create(identityUser, newUser.Password);

                if (result.Succeeded)
                {
                    samUserRegEntities context = new samUserRegEntities();
                    AspNetUser user = context.AspNetUsers
                        .Where(u => u.UserName == newUser.UserName).FirstOrDefault();
                    AspNetRole role = context.AspNetRoles
                        .Where(r => r.Name == "registered").FirstOrDefault();

                    user.AspNetRoles.Add(role);
                    context.SaveChanges();

                    //creates token to be passed to mail helper to allow email confirmation
                    CreateToken ct = new CreateToken();
                    CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                    var code = manager.GenerateEmailConfirmationToken(identityUser.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                    new { userId = identityUser.Id, code = code },
                                                        protocol: Request.Url.Scheme);
                    //send callbackURL to email helper
                    MailHelper mailer = new MailHelper();
                    string email = "Please confirm your account by clicking this link: <a href=\""
                                    + callbackUrl + "\">Confirm Registration</a>";
                    string subject = "Please confirm your email";
                    //try
                    //{
                        mailer.EmailFromArvixe(email, identityUser.Email, subject);
                        ViewBag.FakeConfirmation =
                            "An account confirmation has been sent to your email, please confirm before attempting to login";
                    //}
                    //catch (System.Exception ex)
                    //{
                    //    ViewBag.FakeConfirmation = ex.Message;
                    //}

                }
            }
            return View();
        }
Esempio n. 7
0
        public async Task <IHttpActionResult> PostApplicationUsers(UserInfoViewModel u)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var             context    = new ApplicationDbContext();
            ApplicationUser dbUser     = context.Users.FirstOrDefault(d => d.Email == u.Email);
            string          activeLink = "";
            string          password   = u.UserName;


            if (dbUser == null)
            {
                dbUser = new ApplicationUser();
                var user = new ApplicationUser()
                {
                    UserName = u.Email, Email = u.Email
                };
                user.CreatedDate = DateTime.UtcNow;
                user.CreatedBy   = Username;
                IdentityResult result = await UserManager.CreateAsync(user, password);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                else
                {
                    string code = System.Web.HttpUtility.UrlEncode(UserManager.GenerateEmailConfirmationToken(user.Id));
                    activeLink = string.Format(domain + "Home/ConfirmEmail/?userId={0}&code={1}", user.Id, code);
                }

                dbUser = context.Users.FirstOrDefault(d => d.Email == u.Email);
            }
            else
            {
                return(BadRequest("Account with email is exits: " + u.Email));
            }

            #region Update roles
            if (User.IsInRole("HOST"))
            {
                var user = UserManager.FindById(dbUser.Id);
                UserManager.RemoveFromRoles(dbUser.Id, UserManager.GetRoles(dbUser.Id).ToArray());
                if (u.Roles != null)
                {
                    foreach (var r in u.Roles)
                    {
                        UserManager.AddToRole(dbUser.Id, r.RoleId);
                    }
                }
                UserManager.Update(user);
            }
            #endregion



            dbUser.UserName = dbUser.Email = string.IsNullOrEmpty(u.Email) ? null : u.Email.ToLower();

            dbUser.FullName    = u.FullName;
            dbUser.Avatar      = u.Avatar;
            dbUser.PhoneNumber = u.PhoneNumber;
            dbUser.Address     = u.Address;
            dbUser.Gender      = u.Gender;
            dbUser.DOB         = u.DOB;
            dbUser.StaffID     = u.StaffID;
            dbUser.PartnerID   = u.PartnerID;

            dbUser.LockoutEnabled = u.LockoutEnabled;

            try
            {
                context.SaveChanges();

                // using RazorEngine;
                // using RazorEngine.Templating; // Dont forget to include this.
                string template =
                    @"
                        Xin chào <strong>@Model.FullName</strong>,
                        <br>
                        <br>Bạn vừa được tạo tài khoản truy cập vào hệ thống Quản lý Đề tài Nghiên cứu khoa học.
                        <br>
                        <br>Tài khoản đăng nhập:
                        <br>Email: <strong>@Model.Email</strong>
                        <br>Mật khẩu: <strong>@Model.Password</strong>
                        <br>
                        <br>Vui lòng đăng nhập
                        <br> - Đối với mạng của BV Mỹ Đức: <a href='@Model.Domain2'>@Model.Domain2</a> 
                        <br> - Đối với mạng ngoài BV: <a href='@Model.Domain'>@Model.Domain</a> 
                        <br>";

                var html = Engine.Razor.RunCompile(template, "Register_EmailTemplate", null, new { FullName = dbUser.FullName, Email = dbUser.Email, Password = password, Domain = domain, Domain2 = domain2 });

                EmailService emailService = new EmailService();
                emailService.Send(new IdentityMessage()
                {
                    Subject = "Quản lý Đề tài Nghiên cứu khoa học - thông tin tài khoản", Destination = dbUser.Email, Body = html
                });

                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (Exception ex)
            {
                log.Error("PostApplicationUsers", ex);
                throw;
            }
        }
        public ActionResult CompleteInfo(ClientInterestViewModel client)
        {
            repo.saveClientInfo(client);

            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

            CreateTokenProvider(manager, EMAIL_CONFIRMATION);

              var user = manager.FindByName(client.userName);
            var code = manager.GenerateEmailConfirmationToken(user.Id);

            var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                            new { userId = user.Id, code = code },
                                                protocol: Request.Url.Scheme);

            string emailBody = "Please confirm your account by clicking this link: <a href=\""
                            + callbackUrl + "\">Confirm Registration</a>";

            MailHelper mailer = new MailHelper();

            string Subject = "Confirm registration";
            string response = mailer.EmailFromArvixe(
                                       new Message(client.email, Subject, emailBody));

            if (response.IndexOf("Success") >= 0)
            {
             //   ViewBag.Message = "A confirm email has been sent. Please check your email.";
                TempData["Message"] = "A confirm email has been sent. Please check your email.";
                return RedirectToAction("CompleteRegistration");
            }
            else {
                ViewBag.Message = response;
            }

            ClientInterestViewModel newClient = repo.getClientInterest(client.userId);
            return View(newClient);
               // return RedirectToAction("UserProfile", new { userName = client.userName});
        }
Esempio n. 9
0
        public ActionResult UsersCreate(RegisterCustomerUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                CustomerUser user = (CustomerUser)model.GetUser();
                user.CustomerID      = model.CustomerID;
                user.UserName        = model.Email;
                user.FirstName       = model.FirstName;
                user.LastName        = model.LastName;
                user.IsCustomerAdmin = model.IsCustomerAdmin;
                user.JobPosition     = model.JobPosition;
                user.Initials        = model.Initials;
                try
                {
                    var result = userManager.Create(user, model.Password);

                    if (result.Succeeded)
                    {
                        //NO SE ESTA USANDO
                        //if (model.IsCustomerAdmin)
                        //{
                        //    userManager.AddToRole(user.Id, "CustomerAdminUser");
                        //}
                        //else
                        //{
                        //    userManager.AddToRole(user.Id, "CustomerUser");
                        //}

                        //Se crea el Usuario
                        userManager.AddToRole(user.Id, "CustomerUser");

                        //Se envian mail de Activacion
                        var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                        userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <CustomerUser>(provider.Create("EmailConfirmation"));
                        string code        = userManager.GenerateEmailConfirmationToken(user.Id);
                        var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        workflowMessageService.SendConfirmEmail(user.Email, "Confirme su cuenta de acceso", "Por favor confirme su cuenta haciendo click <a href=\"" + callbackUrl + "\">aqui</a>");

                        //Se asigna el Canal de Venta
                        AssignSalesChannel(user.Id, model.SalesChannelID);

                        //Se redireccion al Listado de Usuarios
                        return(RedirectToAction("Users", "Customer", new { id = model.CustomerID }));
                    }
                    else
                    {
                        var errors = string.Join(",", result.Errors);
                        ModelState.AddModelError(string.Empty, errors);
                    }
                }
                catch (DbEntityValidationException e)
                {
                    var errors = string.Join("; ", e.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
                    ModelState.AddModelError(string.Empty, errors);
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 10
0
        public ActionResult Register(RegisteredUser newUser)
        {
            CaptchaHelper captchaHelper = new CaptchaHelper();
            string captchaResponse = captchaHelper.CheckRecaptcha();
            ViewBag.CaptchaResponse = captchaResponse;
            TempData["captcha"] = captchaResponse;
            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore)
            {
                UserLockoutEnabledByDefault = true,
                DefaultAccountLockoutTimeSpan = new System.TimeSpan(0, 10, 0),
                MaxFailedAccessAttemptsBeforeLockout = 3
            };
            var identityUser = new IdentityUser()
            {
                UserName = newUser.UserName,
                Email = newUser.Email
            };
            IdentityResult result = manager.Create(identityUser, newUser.Password);

            if (result.Succeeded && captchaResponse == VALID_CAPTCHA)
            {
                CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                var code = manager.GenerateEmailConfirmationToken(identityUser.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                new { userId = identityUser.Id, code = code },
                                                    protocol: Request.Url.Scheme);

                string email = "<h3>Please confirm your account by clicking this link:</h3><a href=\""
                                + callbackUrl + "\">Confirm Registration</a>";
                MailHelper mailer = new MailHelper();
                string response = mailer.EmailFromArvixe(newUser, email);
                ViewBag.Response = response;
                TempData["response"] = response;
            }
                return RedirectToAction("Index","Home");
        }
Esempio n. 11
0
        protected override void Seed(ReWork.Model.Context.ReWorkContext context)
        {
            base.Seed(context);

            RoleStore <IdentityRole>   roleStore   = new RoleStore <IdentityRole>(context);
            RoleManager <IdentityRole> roleManager = new RoleManager <IdentityRole>(roleStore);

            if (!roleManager.RoleExists("moderator") && !roleManager.RoleExists("user"))
            {
                IdentityRole roleModerator = new IdentityRole()
                {
                    Name = "moderator"
                };
                IdentityRole roleUser = new IdentityRole()
                {
                    Name = "user"
                };

                roleManager.Create(roleModerator);
                roleManager.Create(roleUser);
            }

            UserStore <User>   userStore   = new UserStore <User>(context);
            UserManager <User> userManager = new UserManager <User>(userStore);


            var moderator = userManager.FindByName("alex");

            if (moderator == null)
            {
                moderator = new User()
                {
                    UserName = "******", Email = "*****@*****.**", FirstName = "Aleksey", LastName = "Programmer", RegistrationdDate = DateTime.UtcNow
                };

                string pathToDefaultImage = HttpContext.Current.Server.MapPath("~/Content/cube-512.png");
                byte[] defaultImage       = File.ReadAllBytes(pathToDefaultImage);
                moderator.Image = defaultImage;

                userManager.Create(moderator, "123456");
                userManager.AddToRole(moderator.Id, "user");
                userManager.AddToRole(moderator.Id, "moderator");

                CustomerProfile customerProfile = new CustomerProfile()
                {
                    User = moderator
                };
                context.CustomerProfiles.Add(customerProfile);

                DpapiDataProtectionProvider dataProtectionProvider = new DpapiDataProtectionProvider();
                userManager.UserTokenProvider = new DataProtectorTokenProvider <User>(dataProtectionProvider.Create());

                string token = userManager.GenerateEmailConfirmationToken(moderator.Id);
                userManager.ConfirmEmail(moderator.Id, token);
            }

            var user = userManager.FindByName("anton");

            if (user == null)
            {
                user = new User()
                {
                    UserName = "******", Email = "*****@*****.**", FirstName = "Anton", LastName = "Antonio", RegistrationdDate = DateTime.UtcNow
                };

                string pathToDefaultImage = HttpContext.Current.Server.MapPath("~/Content/cube-512.png");
                byte[] defaultImage       = File.ReadAllBytes(pathToDefaultImage);
                user.Image = defaultImage;

                userManager.Create(user, "123456");
                userManager.AddToRole(user.Id, "user");

                var customerProfile = new CustomerProfile()
                {
                    User = user
                };
                context.CustomerProfiles.Add(customerProfile);

                var dataProtectionProvider = new DpapiDataProtectionProvider();
                userManager.UserTokenProvider = new DataProtectorTokenProvider <User>(dataProtectionProvider.Create());

                string token = userManager.GenerateEmailConfirmationToken(user.Id);
                userManager.ConfirmEmail(user.Id, token);
            }


            Section programming = context.Sections.SingleOrDefault(p => p.Title.Equals("Programming"));
            Section design      = context.Sections.SingleOrDefault(p => p.Title.Equals("Design sites"));

            if (programming == null && design == null)
            {
                programming = new Section()
                {
                    Title = "Programming"
                };
                design = new Section()
                {
                    Title = "Design sites"
                };

                context.Sections.Add(programming);
                context.Sections.Add(design);
            }


            Skill skillCs   = context.Skills.FirstOrDefault(p => p.Title.Equals("C#"));
            Skill skillJa   = context.Skills.FirstOrDefault(p => p.Title.Equals("Java"));
            Skill skillCss  = context.Skills.FirstOrDefault(p => p.Title.Equals("Java"));
            Skill skillScss = context.Skills.FirstOrDefault(p => p.Title.Equals("Java"));

            if (skillCs == null && skillJa == null && skillCss == null && skillScss == null)
            {
                skillCs = new Skill()
                {
                    Title = "C#", Section = programming
                };
                skillJa = new Skill()
                {
                    Title = "Java", Section = programming
                };
                skillCss = new Skill()
                {
                    Title = "CSS", Section = design
                };
                skillScss = new Skill()
                {
                    Title = "SCSS", Section = design
                };

                context.Skills.Add(skillCs);
                context.Skills.Add(skillJa);
                context.Skills.Add(skillCss);
                context.Skills.Add(skillScss);
            }


            var websiteJob = new Job()
            {
                Id             = 1,
                CustomerId     = moderator.Id,
                Customer       = moderator.CustomerProfile,
                Title          = "create website",
                Description    = "web site must be beautifull, topic this web site its cars",
                Price          = 1000,
                PriceDiscussed = true,
                DateAdded      = new DateTime(2019, 3, 1)
            };

            var designJob = new Job()
            {
                Id             = 2,
                CustomerId     = moderator.Id,
                Customer       = moderator.CustomerProfile,
                Title          = "create design for my site",
                Description    = "crate beautifully design, i want see my website in gray colors",
                Price          = 3000,
                PriceDiscussed = true,
                DateAdded      = new DateTime(2019, 2, 25)
            };

            websiteJob.Skills.Add(skillCs);
            websiteJob.Skills.Add(skillJa);
            designJob.Skills.Add(skillCss);
            designJob.Skills.Add(skillScss);

            context.Jobs.AddOrUpdate(websiteJob);
            context.Jobs.AddOrUpdate(designJob);

            context.SaveChanges();
        }
Esempio n. 12
0
 public async Task <string> GenerateEmailConfirmationTokenAsync(string userId)
 {
     return(_userManager.GenerateEmailConfirmationToken(userId));
 }
Esempio n. 13
0
        public ActionResult Register(RegisteredUser newUser) {
            var userStore         = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore)
            {
                UserLockoutEnabledByDefault = true,
                DefaultAccountLockoutTimeSpan = new TimeSpan(0, 10, 0),
                MaxFailedAccessAttemptsBeforeLockout = 3
            };

            var identityUser      = new IdentityUser() { UserName = newUser.UserName, 
                                                         Email    = newUser.Email };
            IdentityResult result = manager.Create(identityUser, newUser.Password);

            if (result.Succeeded) {
                CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                var code = manager.GenerateEmailConfirmationToken(identityUser.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account",
                                                new { userId = identityUser.Id, code = code },
                                                    protocol: Request.Url.Scheme);

                string link = "Please confirm your account by clicking this link: <a href=\""
                                + callbackUrl + "\">Confirm Registration</a>";
                newUser.ConfirmLink = link;                
                // sending Email Start
                MailHelper mailer = new MailHelper();
                string response = mailer.EmailFromArvixe(
                                           new RegisteredUser(newUser.Email, newUser.UserName,newUser.ConfirmLink ));
                
                if (response != "Failure sending mail."){
                    ViewBag.Success = response;
                }else{
                    ViewBag.Failure = response;
                }

                // sending Email End
            }
            return View();
            }
Esempio n. 14
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            string message = string.Empty;
            string userid  = string.Empty;

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

            try
            {
                // check is trader is in database
                var existingUser = UserManager.FindByEmail(model.Email);

                if (existingUser == null)
                {
                    // does not exists so create one
                    var newTrader = new ApplicationUser()
                    {
                        UserName = model.Email,
                        Email    = model.Email,
                    };


                    // An account can be created if there no existing one
                    IdentityResult resultCreate = await UserManager.CreateAsync(newTrader, model.Password);

                    if (!resultCreate.Succeeded)
                    {
                        foreach (string err in resultCreate.Errors)
                        {
                            message += err;
                        }
                        ModelState.AddModelError("Message", "Trader Create Error:" + message + " Please contact the application administrator.");
                        return(BadRequest(ModelState));
                    }


                    // add the role
                    IdentityResult roleResultRole = UserManager.AddToRole(newTrader.Id, "Trader");
                    if (!roleResultRole.Succeeded)
                    {
                        foreach (string err in roleResultRole.Errors)
                        {
                            message += err;
                        }
                        ModelState.AddModelError("Message", "Trader Role Error: " + message + " Please contact the application administrator.");
                        return(BadRequest(ModelState));
                    }

                    if (model.Email == "*****@*****.**")
                    {
                        IdentityResult roleResultRoleAdmin = UserManager.AddToRole(newTrader.Id, "Admin");
                        if (!roleResultRoleAdmin.Succeeded)
                        {
                            foreach (string err in roleResultRoleAdmin.Errors)
                            {
                                message += err;
                            }
                            ModelState.AddModelError("Message", "Admin Role Error: " + message + " Please contact the application administrator.");
                            return(BadRequest(ModelState));
                        }
                    }


                    // send an email to the person claiming the tarder account
                    userid = newTrader.Id;
                    string code        = UserManager.GenerateEmailConfirmationToken(newTrader.Id);
                    var    callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = userid, code = code }));
                    string body        = "Please confirm your account by clicking this: <a href=\"" + callbackUrl + "\">Link</a>. Email about your account confirmation will be sent to you.";

                    IdentityMessage messageIdentity = new IdentityMessage();
                    messageIdentity.Body        = body;
                    messageIdentity.Destination = newTrader.Email;
                    messageIdentity.Subject     = "Please confirm your account";

                    UserManager.EmailService = new EmailService(UserManager, newTrader);
                    await UserManager.EmailService.SendAsync(messageIdentity);

                    // if everything return OK
                    return(Ok());
                }
                else
                {
                    // does exists as a trader the ADMIN guys will be added as script
                    if (UserManager.IsInRole(existingUser.Id, "Trader"))
                    {
                        ModelState.AddModelError("Message", "Account with the email account provided already exist!");
                        return(BadRequest(ModelState));
                    }
                    return(Ok());
                }
            }
            catch (Exception exc)
            {
                RollBackDatabaseChanges();

                UserManager.Delete(UserManager.FindById(userid));

                if (exc.GetType() == typeof(SmtpException))
                {
                    ModelState.AddModelError("Message", exc.Message);
                }
                else
                {
                    ModelState.AddModelError("Message", "An unexpected error occured during the creation of the account. Please contact the application administrator.");
                }

                return(BadRequest(ModelState));
            }
        }
Esempio n. 15
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            try
            {
                user.CreatedDate = DateTime.UtcNow;
                user.CreatedBy   = "Register";
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                else
                {
                    ////kiểm tra tạo patient => tạo accounnt cho patient.
                    //DTO_LIST_Patients patient = BS_LIST_Patients.get_LIST_Patients(db, 0, model.PhoneNumber, model.Email);
                    //if (patient == null)
                    //    patient = new DTO_LIST_Patients();

                    ////Todo: Tạo mã thẻ thành viên
                    //patient.FullName = model.FullName;
                    //var names = patient.FullName.Split(' ');
                    //patient.FirstName = names[names.Length - 1];
                    //patient.LastName = patient.FullName.Substring(0, patient.FullName.Length - patient.FirstName.Length).Trim();
                    //patient.PhoneNumber = model.PhoneNumber;
                    //patient.EmailAddress = model.Email;
                    //patient.Username = model.Email;

                    //if (patient.ID == 0)
                    //{
                    //    patient = BS_LIST_Patients.post_LIST_Patients(db, PartnerID, patient, "Register");
                    //}
                    //else
                    //{
                    //    BS_LIST_Patients.put_LIST_Patients(db, PartnerID, patient.ID, patient, "Register");
                    //}

                    ////Update account info
                    //user.FullName = model.FullName;
                    //user.PhoneNumber = model.PhoneNumber;

                    //user.StaffID = model.StaffID;
                    //user.PatientID = patient.ID;

                    //// Associate the role with the new user
                    //await UserManager.AddToRoleAsync(user.Id, "BenhNhan");
                    //UserManager.Update(user);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    string code = UserManager.GenerateEmailConfirmationToken(user.Id);

                    var callbackUrl = string.Format(domain + "Home/ConfirmEmail/?userId={0}&code={1}", user.Id, code);

                    UserManager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException e)
            {
                ClassLibrary.errorLog.logMessage("api/Account/Register", e);
            }



            return(Ok());
        }
            public ActionResult Register(RegisteredUser newUser)
            {

                var userStore = new UserStore<IdentityUser>();
                UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore)
                {
                    UserLockoutEnabledByDefault = true,
                    DefaultAccountLockoutTimeSpan = new TimeSpan(0, 10, 0),
                    MaxFailedAccessAttemptsBeforeLockout = 3
                };
            var identityUser = new IdentityUser()
                {
                    UserName = newUser.UserName,
                    Email = newUser.Email
                };
                IdentityResult result = manager.Create(identityUser, newUser.Password);

                if (result.Succeeded)
                {
                    CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                    var code = manager.GenerateEmailConfirmationToken(identityUser.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                    new { userId = identityUser.Id, code = code },
                                                        protocol: Request.Url.Scheme);

                    string email = "Please confirm your account by clicking this link: <a href=\""
                                    + callbackUrl + "\">Confirm Registration</a>";
                    ViewBag.FakeConfirmation = email;
            }
                return View();
            }
        public ActionResult Register(RegisteredUser newUser)
        {
            //when user registers in checks model requirements to ensure valid input
            if (ModelState.IsValid)
            {
                CaptchaHelper captchaHelper   = new CaptchaHelper();
                string        captchaResponse = captchaHelper.CheckRecaptcha();
                ViewBag.CaptchaResponse = captchaResponse;

                // add user to database, lock account until email confirmation
                var userStore = new UserStore <IdentityUser>();
                UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore)
                {
                    //set account to lock after consecutive failed login attempts
                    UserLockoutEnabledByDefault          = true,
                    DefaultAccountLockoutTimeSpan        = new TimeSpan(0, 10, 0),
                    MaxFailedAccessAttemptsBeforeLockout = 3
                };

                var identityUser = new IdentityUser()
                {
                    UserName = newUser.UserName,
                    Email    = newUser.Email
                };
                IdentityResult result = manager.Create(identityUser, newUser.Password);

                if (result.Succeeded)
                {
                    samUserRegEntities context = new samUserRegEntities();
                    AspNetUser         user    = context.AspNetUsers
                                                 .Where(u => u.UserName == newUser.UserName).FirstOrDefault();
                    AspNetRole role = context.AspNetRoles
                                      .Where(r => r.Name == "registered").FirstOrDefault();

                    user.AspNetRoles.Add(role);
                    context.SaveChanges();

                    //creates token to be passed to mail helper to allow email confirmation
                    CreateToken ct = new CreateToken();
                    CreateTokenProvider(manager, EMAIL_CONFIRMATION);


                    var code        = manager.GenerateEmailConfirmationToken(identityUser.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                 new { userId = identityUser.Id, code = code },
                                                 protocol: Request.Url.Scheme);
                    //send callbackURL to email helper
                    MailHelper mailer = new MailHelper();
                    string     email  = "Please confirm your account by clicking this link: <a href=\""
                                        + callbackUrl + "\">Confirm Registration</a>";
                    string subject = "Please confirm your email";
                    //try
                    //{
                    mailer.EmailFromArvixe(email, identityUser.Email, subject);
                    ViewBag.FakeConfirmation =
                        "An account confirmation has been sent to your email, please confirm before attempting to login";
                    //}
                    //catch (System.Exception ex)
                    //{
                    //    ViewBag.FakeConfirmation = ex.Message;
                    //}
                }
            }
            return(View());
        }