public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await UserManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }

            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Section106");

            UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("ResetPassword"));

            var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            return(View());
        }
Beispiel #2
0
 public AccountController()
     : this(new UserManager<VoatUser>(new UserStore<VoatUser>(new ApplicationDbContext())))
 {
     var provider = new DpapiDataProtectionProvider("VoatUI");
     UserManager.UserValidator = new UserValidator<VoatUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
     UserManager.UserTokenProvider = new DataProtectorTokenProvider<VoatUser>(provider.Create("VoatTokenProvider"));
 }
        public static IAppBuilder UseIdentityServerCore(this IAppBuilder app, IdentityServerCoreOptions options)
        {
            if (options == null) throw new ArgumentNullException("options");

            var internalConfig = new InternalConfiguration();

            var settings = options.Factory.CoreSettings();
            if (settings.DataProtector == null)
            {
                var provider = app.GetDataProtectionProvider();
                if (provider == null)
                {
                    provider = new DpapiDataProtectionProvider("idsrv3");
                }

                internalConfig.DataProtector = new HostDataProtector(provider);
            }
            else
            {
                internalConfig.DataProtector = settings.DataProtector;
            }

            // thank you Microsoft for the clean syntax
            JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None;
            JwtSecurityTokenHandler.OutboundClaimTypeMap = ClaimMappings.None;

            app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = Constants.PrimaryAuthenticationType });
            app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = Constants.ExternalAuthenticationType, AuthenticationMode = AuthenticationMode.Passive });
            app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = Constants.PartialSignInAuthenticationType, AuthenticationMode = AuthenticationMode.Passive });

            if (options.AdditionalIdentityProviderConfiguration != null)
            {
                options.AdditionalIdentityProviderConfiguration(app, Constants.ExternalAuthenticationType);
            }

            if (options.PluginConfiguration != null)
            {
                options.PluginConfiguration(app, internalConfig.PluginConfiguration);
            }

            app.UseFileServer(new FileServerOptions
            {
                RequestPath = new PathString("/assets"),
                FileSystem = new EmbeddedResourceFileSystem(typeof(Constants).Assembly, "Thinktecture.IdentityServer.Core.Assets")
            });
            app.UseStageMarker(PipelineStage.MapHandler);

            app.UseFileServer(new FileServerOptions
            {
                RequestPath = new PathString("/assets/libs/fonts"),
                FileSystem = new EmbeddedResourceFileSystem(typeof(Constants).Assembly, "Thinktecture.IdentityServer.Core.Assets.libs.bootstrap.fonts")
            });
            app.UseStageMarker(PipelineStage.MapHandler);

            app.Use<AutofacContainerMiddleware>(AutofacConfig.Configure(options, internalConfig));
            Microsoft.Owin.Infrastructure.SignatureConversions.AddConversions(app);
            app.UseWebApi(WebApiConfig.Configure(options));

            return app;
        }
Beispiel #4
0
        public ApiUserManager(IUserStore <User, Guid> store)
            : base(store)
        {
            // Configure validation logic for usernames
            UserValidator = new UserValidator <User, Guid>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            var dataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Acutela.Frasset.Web");

            UserTokenProvider = new DataProtectorTokenProvider <User, Guid>(dataProtectionProvider.Create("Email Confirmation"));

            EmailService = new IdentityEmailService();
        }
Beispiel #5
0
        public OAuthInstaller(IDataProtectionProvider dataProtectionProvider)
        {
            if (dataProtectionProvider == null)
                dataProtectionProvider = new DpapiDataProtectionProvider();

            _dataProtectionProvider = dataProtectionProvider;
        }
 public static async Task<string> GenerateToken(ApplicationUser appUser, ApplicationUserManager userManager)
 {
     var provider = new DpapiDataProtectionProvider(appUser.Id);
     userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));
     string code = await userManager.GenerateEmailConfirmationTokenAsync(appUser.Id);
     return code;
 }
 public EmployeeDetailsController()
     : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
 {
     UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
     var provider = new DpapiDataProtectionProvider("HospitalManagement");
     UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, string>(provider.Create("UserToken")) as IUserTokenProvider<ApplicationUser, string>;
 }
 public MyIdentityManager(ApplicationSignInManager signmanager)
 {
     _dbContext = new ApplicationDbContext();
     _signInManager = signmanager;
     _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_dbContext));
     _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_dbContext));
     protectionProvider = new DpapiDataProtectionProvider("Demo");
     _userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(protectionProvider.Create("ResetTokens"));
 }
 public MyIdentityManager()
 {
     _dbContext = new ApplicationDbContext();
     _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_dbContext));
     _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_dbContext));
     //idk why they are used..
     protectionProvider = new DpapiDataProtectionProvider("Demo");
     _userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(protectionProvider.Create("ResetTokens"));
 }
        public static IAppBuilder UseWsFederationPlugin(this IAppBuilder app, WsFederationPluginOptions options)
        {
            if (options == null) throw new ArgumentNullException("options");
            options.Validate();

            var internalConfig = new InternalConfiguration();

            // todo hacky!
            internalConfig.LoginPageUrl = options.LoginPageUrl;

            var settings = options.Factory.CoreSettings();
            // todo - need a better solution for data protection
            if (settings.DataProtector == null)
            {
                var provider = app.GetDataProtectionProvider();
                if (provider == null)
                {
                    provider = new DpapiDataProtectionProvider("idsrv3");
                }

                var funcProtector = new FuncDataProtector(
                    (data, entropy) =>
                    {
                        var protector = provider.Create(entropy);
                        return protector.Protect(data);
                    },
                    (data, entropy) =>
                    {
                        var protector = provider.Create(entropy);
                        return protector.Unprotect(data);
                    });

                internalConfig.DataProtector = funcProtector;
            }
            else
            {
                internalConfig.DataProtector = settings.DataProtector;
            }

            app.Map(options.MapPath, wsfedApp =>
                {
                    wsfedApp.UseCookieAuthentication(new CookieAuthenticationOptions
                    {
                        AuthenticationType = WsFederationPluginOptions.CookieName,
                        AuthenticationMode = AuthenticationMode.Passive
                    });

                    wsfedApp.Use<AutofacContainerMiddleware>(AutofacConfig.Configure(options, internalConfig));
                    Microsoft.Owin.Infrastructure.SignatureConversions.AddConversions(app);
                    wsfedApp.UseWebApi(WebApiConfig.Configure());
                });

            // todo
            //options.Configuration.AddSignOutCallbackUrl("/wsfed/signout");

            return app;
        }
Beispiel #11
0
        public UsersService(DbContext context)
        {
            this.context = context;
            var userStore = new UserStore<User>(context);
            userManager = new UserManager<User>(userStore);

            var provider = new DpapiDataProtectionProvider("BoardGames");

            userManager.UserTokenProvider = new DataProtectorTokenProvider<User>(
                provider.Create("UserToken"));
        }
Beispiel #12
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                // If want reset password with email confirmation
                //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                //{
                //    // Don't reveal that the user does not exist or is not confirmed
                //    return View("ForgotPasswordConfirmation");
                //}

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Section106");
                UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("ResetPassword"));
                // 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

                //var provider = new DpapiDataProtectionProvider("Section106");

                //var userManager = new UserManager<ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>());

                //userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
                //    provider.Create("ResetPassword"));

                //error when upladed on 253*(IIS)
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

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



                //await UserManager.SendEmailAsync(user.Email, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                string body    = "Please reset your password by clicking <a href='" + callbackUrl + "'>here</a>";
                string subject = "Reset Password";
                string to      = user.Email;

                string emailStatus = await _commonService.SendEmail(body, subject, to);

                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public static IAppBuilder ConfigureDataProtectionProvider(this IAppBuilder app, IdentityServerOptions options)
        {
            if (options.DataProtector == null)
            {
                var provider = app.GetDataProtectionProvider();
                if (provider == null)
                {
                    provider = new DpapiDataProtectionProvider(Constants.PrimaryAuthenticationType);
                }

                options.DataProtector = new HostDataProtector(provider);
            } 
            return app;
        }
 public AuthRepository()
 {
     var provider = new DpapiDataProtectionProvider("Microbrew.it");
     _ctx = new AuthContext();
     //_userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx))
     {
         EmailService = new EmailService()
     };
     _userManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(provider.Create("ASP.NET Identity"))
     {
         //Sets the lifespan of the confirm email token and the reset password token.
         TokenLifespan = TimeSpan.FromMinutes(1),
     };
 }
Beispiel #15
0
        public void Configuration(IAppBuilder app)
        {
            //  Create new config
            HttpConfiguration config = new HttpConfiguration();

            
            //  Configure Machine Data Protection Provider
            IDataProtectionProvider dataProtectionProvider = app.GetDataProtectionProvider();
            if (dataProtectionProvider == null)
            {
                dataProtectionProvider = new DpapiDataProtectionProvider("ISM");
                app.SetDataProtectionProvider(dataProtectionProvider);
            }


            // Configure OAuth
            AuthConfig.ConfigureOAuthTokenGeneration(app);
            

            //  Configure Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional}    
            );


            //  Configure data serialization
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();


            //  Set CORS options
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);


            //  Set config
            app.UseWebApi(config);
            
        }
Beispiel #16
0
    protected void Recovery_Return(object sender, EventArgs e)
    {
        try
        {
            var IsValid = false;

            var sp_email    = (tbResetUserName.Text.Length > 0) ? tbResetUserName.Text.Trim() : null;
            var sp_password = (tbResetPassword.Text.Length > 0) ? tbResetPassword.Text.Trim() : null;
            var sp_token    = (Request["token"].ToString().Length > 0) ? Request["token"].ToString() : null;
            lblMessage.Text = "";

            if (sp_password != null && sp_password.Length > 0)
            {
                IsValid = true;
            }

            if (IsValid)
            {
                UserManager manager  = new UserManager();
                var         provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("CIPApplication");
                manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, int>(provider.Create("CIPApplicationToken"));

                ApplicationUser user = manager.FindByEmail(sp_email);
                if (user != null)
                {
                    var result = manager.ResetPassword(user.Id, sp_token, sp_password);
                    if (result.Succeeded)
                    {
                        lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Password successfully reset. Login?");
                        pnlReset.Visible = false;
                        pnlLogin.Visible = true;
                    }
                    else
                    {
                        lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Failed to reset password");
                        foreach (var error in result.Errors)
                        {
                            lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), error);
                        }
                    }
                }
                else
                {
                    lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Failed to get a username from email address");
                }
            }
            else
            {
                lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Failed validation");
            }
            // lblMessage.Text += String.Format("<li>{0}: {1}: {2}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "sp_token", HttpUtility.UrlDecode(sp_token));
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error sending email";

            lblMessage.Text += String.Format("<table class='table_error'>"
                                             + "<tr><td>Error<td/><td>{0}</td></tr>"
                                             + "<tr><td>Message<td/><td>{1}</td></tr>"
                                             + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                             + "<tr><td>Source<td/><td>{3}</td></tr>"
                                             + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                             + "<tr><td>Data<td/><td>{5}</td></tr>"
                                             + "</table>"
                                             , "Email Sender"    //0
                                             , ex.Message        //1
                                             , ex.StackTrace     //2
                                             , ex.Source         //3
                                             , ex.InnerException //4
                                             , ex.Data           //5
                                             , ex.HelpLink
                                             , ex.TargetSite
                                             );
        }
    }
Beispiel #17
0
    protected void RecoveryRequest(object sender, EventArgs e)
    {
        try
        {
            // https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset
            // manager.UserTokenProvider = new DataProtectorTokenProvider<User>(dataProtectionProvider.Create("ASP.NET Identity"));
            UserManager manager  = new UserManager();
            var         provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("CIPApplication");
            manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, int>(provider.Create("CIPApplicationToken"));

            ApplicationUser user = manager.FindByEmail(RecoveryEmail.Text);
            if (user != null)
            {
                // Found a user - generate and send token
                var sp_token = manager.GeneratePasswordResetToken(user.Id);
                if (sp_token.Length > 0)
                {
                    sp_token = HttpUtility.UrlEncode(sp_token);

                    if (Send_Email_Client(sp_token, RecoveryEmail.Text, user.FirstName, user.LastName))
                    {
                        lblMessage.Text   += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Password recovery link sent to your email address.");
                        RecoveryEmail.Text = "";
                    }
                    else
                    {
                        lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "We were not able to send a password recovery link. Please contact your account manager for assistance.");
                    }

                    /// ... now reset the password
                    ///
                    //manager = new UserManager();
                    //provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("CIPApplication");
                    //manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(provider.Create("CIPApplicationToken"));

                    //var sp_password = "******";
                    //var result = manager.ResetPassword(user.Id, HttpUtility.UrlDecode(sp_token), sp_password);
                    //if (result.Succeeded)
                    //{
                    //    lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Password successfully reset. Login?");

                    //}
                    //else
                    //{
                    //    lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "Failed to reset password");
                    //    foreach (var error in result.Errors)
                    //    {
                    //        lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), error);
                    //    }
                    //}
                }
                else
                {
                    lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "* * We were not able to send a password recovery link. Please contact your account manager for assistance.");
                }
            }
            else
            {
                lblMessage.Text += String.Format("<li>{0}: {1}</li>", DateTime.UtcNow.ToString("hh:mm:ss"), "*** User does not exist ***");
                // No user found, email not in system
                // Respond with "If email exists, recovery was sent
                // or
                // Respond with "Email does not exists in our system"
                // if 2nd method - limit # of attempts per hour to 5
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error sending email";

            lblMessage.Text += String.Format("<table class='table_error'>"
                                             + "<tr><td>Error<td/><td>{0}</td></tr>"
                                             + "<tr><td>Message<td/><td>{1}</td></tr>"
                                             + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                             + "<tr><td>Source<td/><td>{3}</td></tr>"
                                             + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                             + "<tr><td>Data<td/><td>{5}</td></tr>"
                                             + "</table>"
                                             , "Email Sender"    //0
                                             , ex.Message        //1
                                             , ex.StackTrace     //2
                                             , ex.Source         //3
                                             , ex.InnerException //4
                                             , ex.Data           //5
                                             , ex.HelpLink
                                             , ex.TargetSite
                                             );
        }
    }
Beispiel #18
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, IdGuilda = long.Parse(model.Guildas.SelectedOption)
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    try
                    {
                        //Liga Usuario x Player

                        GPCLib.DataAccess.Player          daPlayer      = new GPCLib.DataAccess.Player();
                        GPCLib.Models.PlayerUsuarioModels playerUsuario = daPlayer.ObterPlayerUsuario(int.Parse(Request.Form[5]));

                        playerUsuario.UsuarioCombo = new GPCLib.Models.UsuarioCombo();
                        playerUsuario.UsuarioCombo.SelectedOption = user.Id;

                        GPCLib.DataAccess.Guilda daGuilda = new GPCLib.DataAccess.Guilda();
                        daGuilda.AtualizarPlayerUsuario(playerUsuario);
                    }
                    catch (Exception)
                    {
                        //nao é para dar pau nesta etapa. Se nao der certo, segue a vida.
                    }


                    /*
                     * EMAIL CONFIRMAÇÂO
                     *
                     * */

                    ApplicationDbContext context = new ApplicationDbContext();
                    var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

                    UserManager.AddToRole(user.Id, "Membros");


                    //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

                    var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("GPC");
                    UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
                    var token = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = token }, protocol: Request.Url.Scheme);
                    UserManager.EmailService = new EmailService();

                    //StringBuilder Mensagem = new StringBuilder();
                    //Mensagem.AppendLine("Ólá! ");
                    //Mensagem.AppendLine("Recebemos uma requisição de cadastro no GPC - Guilda Painel de Controle. ");
                    //Mensagem.AppendLine("Para confirmar seu cadastro acesse o link abaixo.  ");
                    string emailc = "<head></head><body> <div style=\"background-color:#fff;margin:0 auto 0 auto;padding:30px 0 30px 0;color:#4f565d;font-size:13px;line-height:20px;font-family:'Helvetica Neue'," +
                                    "Arial,sans-serif;text-align:left;\"> <center> <table style=\"width:550px;text-align:center\"> <tbody> <tr> <td style=\"padding:0 0 20px 0;border-bottom:1px solid #e9edee;\">" +
                                    "<h1> <a href=\"http://www.demonorange.party\" style=\"display:block; margin:0 auto;\" target=\"_blank\"> GPC - Guilda Painel de Controle </a></h1> </td> </tr> <tr> " +
                                    "<td colspan=\"2\" style=\"padding:30px 0;\"> <p style=\"color:#1d2227;line-height:28px;font-size:22px;margin:12px 10px 20px 10px;font-weight:400;\">" +
                                    "Olá Recebemos uma requisição de cadastro no GPC - Guilda Painel de Controle.</p> <p style=\"margin:0 10px 10px 10px;padding:0;\">Para confirmar seu cadastro acesse o link abaixo." +
                                    "</p> <p> <a style=\"display:inline-block;text-decoration:none;padding:15px 20px;background-color:#2baaed;border:1px solid #2baaed;border-radius:3px;color:#FFF;font-weight:bold;\" " +
                                    "href=\"" + callbackUrl + "\" target=\"_blank\">Confirmar Cadastro</a> </p> </td> </tr> <tr> <td colspan=\"2\" style=\"padding:30px 0 0 0;border-top:1px solid #e9edee;color:#9b9fa5\"> " +
                                    "Se tiver dúvidas por favor entrar em contato com <a style=\"color:#666d74;text-decoration:none;\" href=\"mailto:[email protected]\" target=\"_blank\">[email protected]</a> " +
                                    "</td> </tr> </tbody> </table> </center> </div> </body>";


                    await UserManager.SendEmailAsync(user.Id, "GPC - Confirmação de Cadastro", emailc);

                    // Uncomment to debug locally
                    // TempData["ViewBagLink"] = callbackUrl;

                    ViewBag.Message = "Um email de confirmação foi enviado a seu email de cadastro. Por favor acesse o link recebido para validação do seu cadastro. ";

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<ICacheService>().To<HttpCacheService>().InSingletonScope();
            kernel.Bind<ITaskRegister>().To<NoopTaskRegister>().InRequestScope();

            kernel.Bind<IFolderCreator>().To<GoogleDriveFolderCreator>().InRequestScope();

            kernel.Bind<IUrlConstructor>().To<UrlConstructor>();
            kernel.Bind<INotifier>().To<MandrillNotifierEmailer>().InRequestScope();
            kernel.Bind<IEmailer>().To<MandrillNotifierEmailer>().InRequestScope();
            kernel.Bind<ITaskStepEmployeeStrategy>().To<TaskStepEmployeeStrategy>().InRequestScope();

            kernel.Bind<IUserTokenProvider<User, string>>().ToMethod((x) =>
            {
                var provider = new DpapiDataProtectionProvider("Sample");
                return new DataProtectorTokenProvider<User>(provider.Create("EmailConfirmation"));
            }).InRequestScope();
            kernel.Bind<IAuth>().To<BLAuth>().InRequestScope();
            kernel.Bind<IUnitOfWork, Context>().To<Context>().InRequestScope();
            kernel.Bind<UserManager<User>>().To<UserManager>().InRequestScope();
            kernel.Bind<RoleManager<UserRole>>().To<RoleManager>().InRequestScope();
            kernel.Bind<IAccountService>().To<AccountService>().InRequestScope();
            kernel.Bind<ICustomerService>().To<CustomerService>().InRequestScope();
            kernel.Bind<IProjectService>().To<ProjectService>().InRequestScope();
            kernel.Bind<ITaskService>().To<TaskService>().InRequestScope();
            kernel.Bind<IEmployeeService>().To<EmployeeService>().InRequestScope();
            kernel.Bind<IDocumentationService>().To<DocumentationService>().InRequestScope();
            kernel.Bind<IUserService>().To<UserService>().InRequestScope();
            kernel.Bind<ISpentTimeService>().To<SpentTimeService>().InRequestScope();
            kernel.Bind<IQuizService>().To<QuizService>().InRequestScope();
            kernel.Bind<ICommentService>().To<CommentService>().InRequestScope();
            kernel.Bind<IQuestionService>().To<QuestionService>().InRequestScope();
            kernel.Bind<IAnswerService>().To<AnswerService>().InRequestScope();
            kernel.Bind<ISettingService>().To<SettingService>().InRequestScope();
        }
Beispiel #20
0
 public UserManager(BikeMatesDbContext context)
 {
     userManager = new UserManager<User>(new UserStore<User>(context));
     var provider = new DpapiDataProtectionProvider("BikeMates");
     userManager.UserTokenProvider = new DataProtectorTokenProvider<User>(provider.Create("ResetPassword"));
 }
Beispiel #21
0
        public async Task<IHttpActionResult> ChangeLogin(ChangeLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var repo = _UOW.GetRepository<IUserRepository>();

            var user = await repo.AppUserManager.FindByEmailAsync(model.OldEmail);
            if (user == null || user.Id != GetUserId()) return BadRequest(Resources.Language.IncorrectEmail);

            var userWithNewMail = await repo.AppUserManager.FindByEmailAsync(model.NewEmail);
            if (userWithNewMail != null) return BadRequest(Resources.Language.EmailAlreadyInUse);

            var result = await repo.AppUserManager.UpdateSecurityStampAsync(user.Id);

            var provider = new DpapiDataProtectionProvider("Sample");
            repo.AppUserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(provider.Create("EmailConfirmation"));
            string code = repo.AppUserManager.GenerateEmailConfirmationToken(user.Id);
            code = System.Web.HttpUtility.UrlEncode(code);

            var callbackUrl = new Uri(Url.Link("ConfirmChangeLogin", new { userId = user.Id, email = model.NewEmail.ToLower(), code = code }));
            string message = string.Format("Пожалуйста, подтвердите ваш новый E-mail ( {0} ) перейдя по <a href=\"{1}\">ссылке</a>.", model.NewEmail, callbackUrl);
        
            await repo.AppUserManager.SendEmailAsync(user.Id, "Подтверждение смены E-mail.", message);
            
            return Json(new { message = "Письмо смены E-mail отправлено на " + model.OldEmail });


        }
Beispiel #22
0
        public async Task<IHttpActionResult> ConfirmEmail(string userId, string code)
        {
            var repo = _UOW.GetRepository<IUserRepository>();
            var user = await repo.AppUserManager.FindByIdAsync(userId);
            if (user == null) return BadRequest(Resources.Language.UserNotExist);



            var provider = new DpapiDataProtectionProvider("InoDrive");
            repo.AppUserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(provider.Create("EmailConfirmation"));

            var result = await repo.AppUserManager.ConfirmEmailAsync(user.Id, code);
            if (!result.Succeeded) return BadRequest(Resources.Language.EmailConfirmError);
            

            return Json(new { message = Resources.Language.EmailConfirmSuccess });
        }
Beispiel #23
0
        public async Task<IHttpActionResult> ConfirmChangeLogin(string userId, string code, string email)
        {
            code = System.Web.HttpUtility.UrlDecode(code);

            var repo = _UOW.GetRepository<IUserRepository>();
            var user = await repo.AppUserManager.FindByIdAsync(userId);
            if (user == null) return BadRequest(Resources.Language.UserNotExist);
          
            var provider = new DpapiDataProtectionProvider("Sample");
            repo.AppUserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(provider.Create("EmailConfirmation"));

            var result = await repo.AppUserManager.ConfirmEmailAsync(user.Id, code);
            if (!result.Succeeded) return BadRequest(Resources.Language.EmailConfirmError);

            user.Email = email;
            user.UserName = email;
            result = await repo.AppUserManager.UpdateAsync(user);
            if (!result.Succeeded) return BadRequest(Resources.Language.EmailConfirmError);

            await repo.AppUserManager.SendEmailAsync(user.Id, "Смена E-mail.", "E-mail успешно изменен на текущий.");

            await repo.AppUserManager.UpdateSecurityStampAsync(user.Id);
           
            return Json(new { message = Resources.Language.EmailConfirmSuccess });
        }
Beispiel #24
0
        public async Task<IHttpActionResult> RestorePasswordSendEmail(PasswordRestoreModel model)
        {
            var repo = _UOW.GetRepository<IUserRepository>();

            var user = await repo.AppUserManager.FindByEmailAsync(model.UserName);
            if (user == null ) return BadRequest(Resources.Language.EmailNotExist);

            var result = await repo.AppUserManager.UpdateSecurityStampAsync(user.Id);

            var provider = new DpapiDataProtectionProvider("Sample");
            repo.AppUserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(provider.Create("PasswordConfirmation"));
            string code = await repo.AppUserManager.GeneratePasswordResetTokenAsync(user.Id);
            code = System.Web.HttpUtility.UrlEncode(code);

            string password = System.Web.Security.Membership.GeneratePassword(10, 0);
            var regex = new System.Text.RegularExpressions.Regex(@"[^A-Za-z0-9]+");
            password = regex.Replace(password, "");

            var callbackUrl = new Uri(Url.Link("Restore", new { username = model.UserName, code = code, password = password }));
            string message = string.Format("Пожалуйста, подтвердите ваш новый пароль ( {0} ) перейдя по <a href=\"{1}\">ссылке</a>.", password, callbackUrl);


            await repo.AppUserManager.SendEmailAsync(user.Id, "Восстановление пароля от системы.", message);

            return Json(new { message = String.Format("Письмо с паролем отправлено на {0}.", model.UserName) });


        }
Beispiel #25
0
        public async Task<IHttpActionResult> PasswordConfirm([FromUri] PasswordRestoreModel model)
        {
            model.Code = System.Web.HttpUtility.UrlDecode(model.Code);
            var repo = _UOW.GetRepository<IUserRepository>();

            var user = await repo.AppUserManager.FindByEmailAsync(model.UserName);
            if (user == null) return BadRequest(Resources.Language.EmailNotExist);

            var provider = new DpapiDataProtectionProvider("Sample");
            repo.AppUserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(provider.Create("PasswordConfirmation"));

            var result = await repo.AppUserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
            if (result.Succeeded) await repo.AppUserManager.UpdateSecurityStampAsync(user.Id);
           


            return Json(new { message = "Пароль изменен." });
        }
        public async Task<ActionResult> ResetPassword(string userId = "")
        {
            if (userId != string.Empty)
            {
                var provider = new DpapiDataProtectionProvider("Website");
                userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("Website")) { TokenLifespan = TimeSpan.FromHours(4) };

                var user = userManager.FindById(userId);
                var token = await userManager.GeneratePasswordResetTokenAsync(userId);

                string useName;

                if (User.Identity.Name.IndexOf(" ") != -1)
                {
                    useName = user.UserName.Substring(0, User.Identity.Name.IndexOf(" "));
                }
                else
                {
                    useName = user.UserName;
                }

                var result = await userManager.ResetPasswordAsync(userId, token, string.Concat("R3MUSUser_", useName));

                if(result.Succeeded)
                {
                    TempData.Add("Message", string.Format("Password reset confirmed: new password is {0}", string.Concat("R3MUSUser_", useName)));
                }
                else
                {
                    TempData.Add("Message", string.Format("Password reset failed: {0}", result.Errors.ToList()[0]));
                }

                await userManager.UpdateAsync(user);
            }

            return RedirectToAction("ViewProfile", new { id = userId });
        }
 public static void SetUserTokenProvider(this ApplicationUserManager userManager, params string[] userManagerPurposes)
 {
     IDataProtectionProvider dataProtectorProvider = new DpapiDataProtectionProvider("PoshBoutique");
     IDataProtector dataProtector = dataProtectorProvider.Create(userManagerPurposes);
     userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
 }