public async Task RemoveUserFromProjectAsync(int userId, int projectId) { var project = await this.projectRepo.All() .Where(x => x.Id == projectId) .Include(x => x.Team) .ThenInclude(x => x.TeamsUsers) .FirstOrDefaultAsync(); var teamUsersToRemove = project.Team.TeamsUsers .FirstOrDefault(x => x.UserId == userId && x.TeamId == project.Team.Id); this.teamUsersRepo.Delete(teamUsersToRemove); await teamUsersRepo.SaveChangesAsync(); var message = EmailConstants.RemoveFromProject + project.Name; await this.notificationsService.AddNotificationToUserAsync(userId, message); // Send email to user to inform them about being added to a project. var user = await userManager.FindByIdAsync(userId.ToString()); var emailSender = new SendGridEmailSender(this.config["SendGrid:Key"]); await emailSender.SendEmailAsync(this.config["SendGrid:Email"], EmailConstants.FromMailingName, user.Email, EmailConstants.RemoveFromProjectSubject, message); }
public async Task <object> Register(RegisterDto model) { var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber, Name = model.FullName }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); SendGridEmailSender emailService = new SendGridEmailSender(); await emailService.SendEmailAsync(model.Email, "Confirm your account", $"Confirm Registration : <a href='http://localhost:4200/user/login'>link</a>"); await _signInManager.SignInAsync(user, false); return(Content("Confirm Registration by email")); } throw new ApplicationException("UNKNOWN_ERROR"); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return(RedirectToPage("./ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ResetPassword", pageHandler: null, values: new { area = "Identity", code }, protocol: Request.Scheme); var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]); await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email, EmailConstants.ConfirmationEmailSubject, string.Format(EmailConstants.ConfirmResetPassword, HtmlEncoder.Default.Encode(callbackUrl))); return(RedirectToPage("./ForgotPasswordConfirmation")); } return(Page()); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(Input.Email); if (user != null && user.EmailConfirmed == false) { _logger.LogInformation($"User with id {user.Id} got reset of the email confirmation token."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code }, protocol: Request.Scheme); var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]); await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email, EmailConstants.ConfirmationEmailSubject, string.Format(EmailConstants.ResetEmailConfirmation, HtmlEncoder.Default.Encode(callbackUrl))); } } return(RedirectToPage("./EmailConfirmationTokenReset")); }
public void SendGridEmailSenderShouldTrowExceptionWhenSubjectOrHtmlContentIsEmpty(string key) { var sengrid = new SendGridEmailSender(key); var result = sengrid.SendEmailAsync("FromMe", "Ivan", "ToYou", null, null, null).IsFaulted; Assert.True(result); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ApplicationDbContext>( options => options.UseSqlServer(this.configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <ApplicationUser>(IdentityOptionsProvider.GetIdentityOptions) .AddRoles <ApplicationRole>().AddEntityFrameworkStores <ApplicationDbContext>(); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddControllersWithViews( options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }).AddRazorRuntimeCompilation(); services.AddRazorPages(); services.AddDatabaseDeveloperPageExceptionFilter(); services.AddSingleton(this.configuration); // Cloudinary Account account = new Account( this.configuration["Cloudinary:CloudName"], this.configuration["Cloudinary:APIKey"], this.configuration["Cloudinary:APISecret"]); Cloudinary cloudinary = new Cloudinary(account); services.AddSingleton(cloudinary); // SendGrid SendGridEmailSender sendgrid = new SendGridEmailSender(this.configuration["SendGrid:API"]); services.AddSingleton(sendgrid); // Data repositories services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>)); services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>)); services.AddScoped <IDbQueryRunner, DbQueryRunner>(); // Application services services.AddTransient <IEmailSender, NullMessageSender>(); services.AddTransient <ISettingsService, SettingsService>(); services.AddTransient <ICarService, CarService>(); services.AddTransient <IMakesService, MakesService>(); services.AddTransient <IModelsService, ModelService>(); services.AddTransient <ICarImageService, CarImageService>(); services.AddTransient <IRepairService, RepairService>(); services.AddTransient <ICommentsService, CommentsService>(); services.AddTransient <IVoteService, VoteService>(); services.AddTransient <IRepairImageService, RepairImageService>(); services.AddTransient <IRequestRepairService, RequestRepairService>(); }
public RequestRepairController( IRequestRepairService requestRepairService, UserManager <ApplicationUser> userManager, SendGridEmailSender emailSender) { this.requestRepairService = requestRepairService; this.userManager = userManager; this.emailSender = emailSender; }
public async Task SendForgotPasswordEmailSuccessfully() { IEmailSender sender = new SendGridEmailSender(_fixture.Configuration); var emailService = new EmailNotificationService(sender); await emailService.SendAsync(new TestEmailNotification( "*****@*****.**", "Softeq Unit Test", new TestEmailModel("google.com", "Softeq Unit Test"))); }
public HomeController(ILogger <HomeController> logger, SendGridEmailSender sendGridEmailSender, IUserService userService, IContactsChatService contactsChatService, UserManager <User> userManager, IProductService productService) { _logger = logger; this.sendGridEmailSender = sendGridEmailSender; this.userService = userService; this.contactsChatService = contactsChatService; this.userManager = userManager; this.productService = productService; }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new User { UserName = Input.Email, Email = Input.Email, }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, ApplicationRolesConstatnts.User); _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]); await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email, EmailConstants.ConfirmationEmailSubject, string.Format(EmailConstants.ConfirmEmail, HtmlEncoder.Default.Encode(callbackUrl))); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public ProductsCommentsController (IProductService productService, IMapper mapper, IProductCommentService productCommentService, IUserService userService, JavaScriptEncoder javaScriptEncoder, UserManager <User> userManager, SendGridEmailSender sendGridEmailSender, HtmlEncoder htmlEncoder) { this.productService = productService; this.mapper = mapper; this.productCommentService = productCommentService; this.userService = userService; this.javaScriptEncoder = javaScriptEncoder; this.userManager = userManager; this.sendGridEmailSender = sendGridEmailSender; this.htmlEncoder = htmlEncoder; }
public ProductsController (IProductService productService, IMapper mapper, IProductCommentService productCommentService, IUserService userService, JavaScriptEncoder javaScriptEncoder, UserManager <User> userManager, SendGridEmailSender sendGridEmailSender, HtmlEncoder htmlEncoder, ICategoryService categoryService, IProductImageService productImageService, BlobServiceClient blobServiceClient, IAzureBlobService azureBlobService) { this.productService = productService; this.mapper = mapper; this.productCommentService = productCommentService; this.userService = userService; this.javaScriptEncoder = javaScriptEncoder; this.userManager = userManager; this.sendGridEmailSender = sendGridEmailSender; this.htmlEncoder = htmlEncoder; this.categoryService = categoryService; this.productImageService = productImageService; this.blobServiceClient = blobServiceClient; this.azureBlobService = azureBlobService; }
public static async Task <SendEmailResponse> SendUserVerificationEmail(string displayName, string email, string verificationURL, string body) { IEmailSender _sender = new SendGridEmailSender(ConfigExtension._config); var response = await Task.Run(() => { return(_sender.SendEmailAsync(new SendEmailDetails { IsHtml = true, FromEmail = ConfigExtension._config["SendGrid:FromEmail"], FromName = ConfigExtension._config["SendGrid:FromName"], ToEmail = email, ToName = displayName, Subject = "Mail de Verificación", BodyContent = body })); }); return(response); }
public async Task AddUserToProject(int userId, int projectId) { var project = await this.projectRepo.All() .Where(x => x.Id == projectId) .Include(x => x.Team) .FirstOrDefaultAsync(); project.Team.TeamsUsers.Add(new TeamsUsers { UserId = userId, TeamId = project.Team.Id }); await this.projectRepo.SaveChangesAsync(); var message = EmailConstants.AddedToProject + project.Name; await this.notificationsService.AddNotificationToUserAsync(userId, message); // Send email to user to inform them about being added to a project. var user = await userManager.FindByIdAsync(userId.ToString()); var emailSender = new SendGridEmailSender(this.config["SendGrid:Key"]); await emailSender.SendEmailAsync(this.config["SendGrid:Email"], EmailConstants.FromMailingName, user.Email, EmailConstants.AddedToProjectSubject, message); }
public async Task <IActionResult> OnGetAsync(string email, string returnUrl = null) { if (email == null) { return(RedirectToPage("/Index")); } var user = await _userManager.FindByEmailAsync(email); if (user == null) { return(NotFound($"Unable to load user with email '{email}'.")); } Email = email; // Once you add a real email sender, you should remove this code that lets you confirm the account DisplayConfirmAccountLink = false; if (DisplayConfirmAccountLink) { var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); EmailConfirmationUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); } var emailSender = new SendGridEmailSender(_config["SendGrid:Key"]); await emailSender.SendEmailAsync(_config["SendGrid:Key"], EmailConstants.FromMailingName, user.Email, EmailConstants.RegisterConfirmation, string.Format(EmailConstants.ConfirmEmail, HtmlEncoder.Default.Encode(EmailConfirmationUrl))); return(Page()); }
private static void Main(string[] args) { /* * try * { * var adminManager = new AdministratorManager(new AdministratorRepository()); * var studentManager = new StudentManager(new StudentRepository()); * var instructorManager = new InstructorManager(new InstructorRepository()); * var departmentRepository = new DepartmentRepository(); * var courseRepository = new CourseRepository(); * var courseOfferingRepository = new CourseOfferingRepository(); * var studentCourseOfferingRepository = new StudentCourseOfferingRepository(); * * var admin = new Administrator * { * User = new User * { * Name = "Admin", * Surname = "Admin", * UserName = "******", * Email = "*****@*****.**", * PhotoUrl = @"https://res.cloudinary.com/ahmetkoprulu/image/upload/v1551362706/ProfilePhotos/mehmetb.png" * } * }; * adminManager.Register(admin, "admin"); * * var department = new Department { Name = "Computer Engineering" }; * departmentRepository.Add(department); * * var course = new Course * { * Name = "Introduction To Programming II", * Code = "ENGR 102", * DepartmentId = 1 * }; * var course2 = new Course * { * Name = "Computer Systems", * Code = "CS 340", * DepartmentId = 1 * }; * courseRepository.Add(course); * courseRepository.Add(course2); * * var instructor = new Instructor * { * DepartmentId = department.Id, * User = new User * { * Name = "Ali", * Surname = "Çakmak", * UserName = "******", * Email = "*****@*****.**", * PhotoUrl = @"https://res.cloudinary.com/ahmetkoprulu/image/upload/v1551362706/ProfilePhotos/mehmetb.png" * }, * }; * var instructor2 = new Instructor * { * DepartmentId = 1, * User = new User * { * Name = "Ahmet", * Surname = "Bulut", * UserName = "******", * Email = "*****@*****.**", * PhotoUrl = @"https://res.cloudinary.com/ahmetkoprulu/image/upload/v1551362706/ProfilePhotos/mehmetb.png" * } * }; * instructorManager.Register(instructor, "123456"); * instructorManager.Register(instructor2, "123456"); * * var courseOffering = new CourseOffering * { * Semester = "Spring", * Year = "2019", * IsActive = true, * CourseId = course.Id, * InstructorId = instructor.Id * }; * var courseOffering2 = new CourseOffering * { * Semester = "Spring", * Year = "2019", * IsActive = true, * CourseId = course2.Id, * InstructorId = instructor2.Id * }; * courseOfferingRepository.Add(courseOffering); * courseOfferingRepository.Add(courseOffering2); * * var student = new Student * { * DepartmentId = department.Id, * User = new User * { * Name = "İlayda", * Surname = "Turan", * UserName = "******", * Email = "*****@*****.**", * PhotoUrl = @"https://res.cloudinary.com/ahmetkoprulu/image/upload/v1551362706/ProfilePhotos/mehmetb.png" * } * }; * studentManager.Register(student, "123456"); * * var studentCourseOffering = new StudentCourseOffering * { * StudentId = student.Id, * CourseOfferingId = courseOffering.Id * }; * var studentCourseOffering2 = new StudentCourseOffering * { * StudentId = student.Id, * CourseOfferingId = courseOffering2.Id * }; * studentCourseOfferingRepository.Add(studentCourseOffering); * studentCourseOfferingRepository.Add(studentCourseOffering2); * * Console.Write("CompExamV0 Database Created And Admin Inserted."); * Console.Read(); * } * catch (Exception e) * { * Console.WriteLine(e); * throw; * } */ /* * var studentManager = new StudentManager(new StudentRepository()); * var students = new List<Student>(); * students.Add(new Student() * { * User = new User() { Name="İlayda", Surname="Turan", Email="*****@*****.**", UserName="******"}, * DepartmentId = 1 * }); * students.Add(new Student() * { * User = new User() { Name = "İlayda", Surname = "Turan", Email = "*****@*****.**", UserName = "******" }, * DepartmentId = 1 * }); * students.Add(new Student() * { * User = new User() { Name = "İlayda", Surname = "Turan", Email = "*****@*****.**", UserName = "******" }, * DepartmentId = 1 * }); * students.Add(new Student() * { * User = new User() { Name = "İlayda", Surname = "Turan", Email = "*****@*****.**", UserName = "******" }, * DepartmentId = 1 * }); * * foreach (var student in students) * { * var pass = RandomString(10); * student.StudentCourseOfferings.Add(new StudentCourseOffering() { StudentId = student.Id, CourseOfferingId = 2, RegistrationDate = DateTime.Now }); * studentManager.Register(student, pass); * try * { * MailMessage mail = new MailMessage(); * SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587); * SmtpServer.UseDefaultCredentials = false; * SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "ekokobaba1"); * SmtpServer.EnableSsl = true; * SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network; * mail.From = new MailAddress("*****@*****.**", "Comp Exam"); * Console.WriteLine(student.User.Email); * mail.To.Add(new MailAddress(student.User.Email)); * mail.Subject = "Registration"; * mail.Body = "Your Password Is " + pass; * ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; * SmtpServer.Send(mail); * Console.WriteLine("mail Send"); * } * catch (Exception ex) * { * Console.WriteLine(ex.ToString()); * } * Console.WriteLine(pass); * } * Console.WriteLine(RandomString(10)); * Console.ReadKey(); */ /* * using (var context = new ApplicationDbContext()) * { * var students = context.Users.FromSql(@"SELECT Users.Id, Users.Name, Users.Surname, Users.UserName, Users.Email, Users.PasswordHash, Users.PasswordSalt, PhotoId, PhotoUrl * FROM Users, Students, StudentCourseOfferings * WHERE Users.Id = Students.Id * AND Students.Id = StudentId * AND CourseOfferingId=2") * .ToList<User>(); * * foreach (var student in students) * { * Console.WriteLine(student.Name); * } * } */ var emailService = new SendGridEmailSender("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", "*****@*****.**", "Comp"); var studentRepository = new StudentRepository(@"Server=DESKTOP-1QBTB6S;Database=CompExamV1;Trusted_Connection=True;"); var examRepository = new ExamRepository(@"Server=DESKTOP-1QBTB6S;Database=CompExamV1;Trusted_Connection=True;"); var questionRepository = new QuestionRepository(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=CompExamV1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); var studentManager = new StudentManager(studentRepository, emailService); /* * rep.Create(new Student() { * StudentID=121611, * StudentName="Ahmet", * StudentEmail="Something", * StudentPasswordHash=new byte[] { }, * StudentPasswordSalt=new byte[] { }, * }); * * rep.Update(new Student() * { * StudentID = 121611, * StudentName = "Mehmet", * StudentEmail = "Something", * StudentPasswordHash = new byte[] { }, * StudentPasswordSalt = new byte[] { }, * }); * * foreach (var student in rep.SelectAll()) * { * Console.WriteLine(student.StudentName); * } * */ /* * var student = rep.GetStudentWithExams(215241187); * Console.WriteLine(student.StudentID + " " + student.StudentName + " " + student.StudentEmail); * Console.WriteLine(student.Exams.Count()); * foreach (var exam in student.Exams) * { * Console.WriteLine(exam.ExamTitle); * } * * var exams = examRepository.GetActiveExams(215241187); * Console.WriteLine(exams.Count()); */ /* * var students = studentRepository.ListStudentsByExamId(1); * Console.WriteLine(students.Count()); * foreach (var student in students) * { * Console.WriteLine(student.StudentID + " " + student.StudentName); * foreach (var q in student.Questions) * { * Console.WriteLine(q.QuestionText); * Console.WriteLine("\t"+q.AnswerText); * } * } * * var exam = examRepository.SelectQuestions(1); * Console.WriteLine(exam.ExamTitle+' '+exam.ExamDate); * foreach (var q in exam.Questions) * { * Console.WriteLine(q.QuestionText); * } * * var e = examRepository.SelectQuestions(25); * Console.WriteLine("sa"); * Console.WriteLine(e.ExamTitle); * Console.WriteLine(e.Questions.Count); * foreach (var question in e.Questions) * { * Console.WriteLine(question.QuestionText); * } * * * string a = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "/Assests/ResetPassword.html")); * Console.WriteLine(a); * var dirPath = Assembly.GetExecutingAssembly().Location; * dirPath = Path.GetDirectoryName(dirPath); * Console.WriteLine(dirPath); * Console.WriteLine(File.ReadAllText(@"C:\Users\aensa\Documents\GitHub\CET-API-Refactor\CetV0DatabaseGenerator\Assets")); * * var studentManager = new StudentManager(studentRepository, * new SendGridEmailSender("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", "*****@*****.**", "ekrembaba", "ekokobaba1")); * studentManager.TrialEmail(); */ Console.WriteLine(studentManager.SendPasswordResetMail("*****@*****.**")); Console.ReadLine(); }
/// <summary> /// Initializes a new instance of the <see cref="EmailController"/> class. /// </summary> /// <param name="sender">The sender.</param> /// <exception cref="ArgumentNullException">sender</exception> public EmailController(SendGridEmailSender sender) { _sender = sender ?? throw new ArgumentNullException(nameof(sender)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Add Database services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection") )); services.AddDatabaseDeveloperPageExceptionFilter(); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //Add Identity services.AddDefaultIdentity <User>(IdentityOptionsProvider.GetIdentityOptions) .AddRoles <Role>().AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); //Add sessions services.AddSession(options => { options.IdleTimeout = TimeSpan.FromHours(1); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); //Add Razor and views services.AddControllersWithViews(option => { option.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); services.AddRazorPages(); //Authorization policies services.AddAuthorization(options => { options.AddPolicy("AuthorizeAsAdminHandler", policy => policy.Requirements.Add(new AuthorizeAsAdminRequirement())); }); services.AddSingleton <IAuthorizationHandler, AuthorizeAsAdminHandler>(); // Add sendgrid var sendGrid = new SendGridEmailSender(this.Configuration["SendGrid:ApiKey"]); services.AddSingleton(sendGrid); //Add Stripe StripeConfiguration.ApiKey = this.Configuration["Stripe:ApiKey"]; services.AddTransient <SessionService>(); //Add Automapper services.AddAutoMapper(typeof(UserProfile)); //Services for working with the database services.AddTransient <IGenderService, GenderService>(); services.AddTransient <IRoleService, RoleService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IProductService, Services.ServicesFolder.ProductService.ProductService>(); services.AddTransient <ICartService, CartService>(); services.AddTransient <IProductCommentService, ProductCommentService>(); services.AddTransient <ICategoryService, CategoryService>(); services.AddTransient <ISaleService, SaleService>(); services.AddTransient <IPaymentMethodService, Services.ServicesFolder.PaymentMethodService.PaymentMethodService>(); services.AddTransient <ICountryService, CountryService>(); services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { _logger.LogInformation("Initializing services."); int validMinutes = Convert.ToInt32(Configuration["Tokens:ValidMinutes"]); var keyString = Configuration["Tokens:Key"]; var issuer = Configuration["Tokens:Issuer"]; var audience = Configuration["Tokens:Audience"]; IClock clock = SystemClock.Instance; var rdsInstanceName = Configuration["AWS:rdsInstanceName"]; // Add application services. var tokenService = new TokenService(keyString, issuer, audience, validMinutes); SendGridEmailSender sendGridEmailSender = new SendGridEmailSender(); services.AddHttpClient(); //Repository Setup. Uncomment either the MySQL section OR the fake repo section. Not both. //MySQL Repos string connectionString = Configuration.GetConnectionString("DefaultConnection"); var userStore = new MySQLFantasyCriticUserStore(connectionString, clock); var roleStore = new MySQLFantasyCriticRoleStore(connectionString); services.AddScoped <IFantasyCriticUserStore>(factory => userStore); services.AddScoped <IFantasyCriticRoleStore>(factory => roleStore); services.AddScoped <IMasterGameRepo>(factory => new MySQLMasterGameRepo(connectionString, userStore)); services.AddScoped <IFantasyCriticRepo>(factory => new MySQLFantasyCriticRepo(connectionString, userStore, new MySQLMasterGameRepo(connectionString, userStore))); services.AddScoped <IRoyaleRepo>(factory => new MySQLRoyaleRepo(connectionString, userStore, new MySQLMasterGameRepo(connectionString, userStore), new MySQLFantasyCriticRepo(connectionString, userStore, new MySQLMasterGameRepo(connectionString, userStore)))); services.AddScoped <IUserStore <FantasyCriticUser> >(factory => userStore); services.AddScoped <IRoleStore <FantasyCriticRole> >(factory => roleStore); //Fake Repos (for testing without a database) //var userStore = new FakeFantasyCriticUserStore(clock); //var roleStore = new FakeFantasyCriticRoleStore(); //services.AddScoped<IFantasyCriticUserStore>(factory => userStore); //services.AddScoped<IFantasyCriticRoleStore>(factory => roleStore); //services.AddScoped<IMasterGameRepo>(factory => new FakeMasterGameRepo(userStore)); //services.AddScoped<IFantasyCriticRepo>(factory => new FakeFantasyCriticRepo(userStore, new FakeMasterGameRepo(userStore))); //services.AddScoped<IRoyaleRepo>(factory => new FakeRoyaleRepo(userStore, new FakeMasterGameRepo(userStore))); //services.AddScoped<IUserStore<FantasyCriticUser>>(factory => userStore); //services.AddScoped<IRoleStore<FantasyCriticRole>>(factory => roleStore); services.AddScoped <IRDSManager>(factory => new RDSManager(rdsInstanceName)); services.AddScoped <FantasyCriticUserManager>(); services.AddScoped <FantasyCriticRoleManager>(); services.AddScoped <GameAcquisitionService>(); services.AddScoped <LeagueMemberService>(); services.AddScoped <PublisherService>(); services.AddScoped <InterLeagueService>(); services.AddScoped <DraftService>(); services.AddScoped <GameSearchingService>(); services.AddScoped <ActionProcessingService>(); services.AddScoped <FantasyCriticService>(); services.AddScoped <RoyaleService>(); services.AddTransient <IEmailSender>(factory => sendGridEmailSender); services.AddTransient <ISMSSender, SMSSender>(); services.AddTransient <ITokenService>(factory => tokenService); services.AddTransient <IClock>(factory => clock); services.AddHttpClient <IOpenCriticService, OpenCriticService>(); services.AddHttpClient <IOpenCriticService, OpenCriticService>(client => { client.BaseAddress = new Uri("https://api.opencritic.com/api/"); }); services.AddScoped <AdminService>(); //Add scheduled tasks & scheduler services.AddSingleton <IScheduledTask, RefreshDataTask>(); services.AddScheduler((sender, args) => { _logger.LogError(args.Exception.Message); args.SetObserved(); }); services.AddIdentity <FantasyCriticUser, FantasyCriticRole>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 8; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }) .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(opt => { opt.ExpireTimeSpan = TimeSpan.FromMinutes(validMinutes); opt.Events.OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden, opt.Events.OnRedirectToAccessDenied); opt.Events.OnRedirectToLogin = ReplaceRedirector(HttpStatusCode.Unauthorized, opt.Events.OnRedirectToLogin); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(cfg => { cfg.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = issuer, ValidAudience = audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString)) }; // We have to hook the OnMessageReceived event in order to // allow the JWT authentication handler to read the access // token from the query string when a WebSocket or // Server-Sent Events request comes in. cfg.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/updatehub"))) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); } }; }); services.AddHsts(options => { options.Preload = true; options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(60); }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 443; }); // Add framework services. services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(options => { options.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); }); services.AddSignalR(); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new User { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); var emailSender = new SendGridEmailSender(this._config["SendGrid:Key"]); await emailSender.SendEmailAsync(_config["SendGrid:Email"], EmailConstants.FromMailingName, Input.Email, EmailConstants.ConfirmationEmailSubject, string.Format(EmailConstants.ExternalLogin, HtmlEncoder.Default.Encode(callbackUrl))); //var emailToSend = new Email(_config["EmailSenderInformation:Email"], Input.Email, //$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.", //EmailConstants.ConfirmationEmailSubject); //await _emailSender.SendAsync(emailToSend, _config["EmailSenderInformation:Password"], // _config["EmailSenderOptions:SmtpServer"], int.Parse(_config["EmailSenderOptions:Port"])); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ProviderDisplayName = info.ProviderDisplayName; ReturnUrl = returnUrl; return(Page()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Add Database services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection") )); services.AddDatabaseDeveloperPageExceptionFilter(); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //Add Identity services.AddDefaultIdentity <User>(IdentityOptionsProvider.GetIdentityOptions) .AddRoles <Role>().AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); //Add sessions services.AddSession(options => { options.IdleTimeout = TimeSpan.FromHours(1); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); //Add Razor and views services.AddControllersWithViews(option => { option.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); services.AddRazorPages(); //Authorization policies services.AddAuthorization(options => { options.AddPolicy("AuthorizeAsAdminHandler", policy => policy.Requirements.Add(new AuthorizeAsAdminRequirement())); }); services.AddSingleton <IAuthorizationHandler, AuthorizeAsAdminHandler>(); // Add Hangfire services.AddHangfire(config => { config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage( this.Configuration.GetConnectionString("DefaultConnection"), new SqlServerStorageOptions { PrepareSchemaIfNecessary = true, QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true, }); }); // Add sendgrid var sendGrid = new SendGridEmailSender(this.Configuration["SendGrid:ApiKey"]); services.AddSingleton(sendGrid); //Add Azure blob storage services.AddSingleton(x => new BlobServiceClient(this.Configuration["ConnectionStrings:AzureBlobConnectionString"])); services.AddTransient <IAzureBlobService, AzureBlobService>(); //Configure stripe services Stripe StripeConfiguration.ApiKey = this.Configuration["Stripe:ApiKey"]; services.AddTransient <SessionService>(); services.AddTransient <PaymentIntentService>(); services.AddTransient <RefundService>(); //Add signalR services.AddSignalR(); //Add Automapper services.AddAutoMapper(typeof(UserProfile)); //Services for working with the database services.AddTransient <IGenderService, GenderService>(); services.AddTransient <IRoleService, RoleService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IProductService, Services.ServicesFolder.ProductService.ProductService>(); services.AddTransient <IProductImageService, ProductImageService>(); services.AddTransient <ICartService, CartService>(); services.AddTransient <IProductCommentService, ProductCommentService>(); services.AddTransient <ICategoryService, CategoryService>(); services.AddTransient <ISaleService, SaleService>(); services.AddTransient <IPaymentMethodService, Services.ServicesFolder.PaymentMethodService.PaymentMethodService>(); services.AddTransient <ICountryService, CountryService>(); services.AddTransient <IContactsChatService, ContactsChatService>(); //Add cron job services.AddTransient <DeleteProductsImagesBlobs>(); services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]); services.AddAzureClients(builder => { builder.AddBlobServiceClient(Configuration["ConnectionStrings:gymhubstorage:blob"], preferMsi: true); builder.AddQueueServiceClient(Configuration["ConnectionStrings:gymhubstorage:queue"], preferMsi: true); }); }
public SendGridEmailSenderTests(ITestOutputHelper output) { _mockCreator = new MockCreator(output); _sendgridClient = Substitute.For <ISendGridClient>(); _sender = new SendGridEmailSender(_sendgridClient); }
public ReserveringenFacade(IReserveringenRepository reserveringRepository) { this._reserveringRepository = reserveringRepository; this.emailSender = new SendGridEmailSender(); }
public RestaurantFacade(IRestaurantRepository restaurantRepository) { this._restaurantRepository = restaurantRepository; this.emailSender = new SendGridEmailSender(); }