Exemplo n.º 1
0
        public static string CreateEmailBody(EmailBodyDefaultParams emailBodyDefaultParams)
        {
            string body = string.Empty;

            //using streamreader for reading my htmltemplate

            using (StreamReader reader = new StreamReader(Path.Combine(_hostingEnvironment.WebRootPath, emailBodyDefaultParams.TemplateUrl)))
            {
                body = reader.ReadToEnd();
            }

            body = body.Replace("{sitelink}", emailBodyDefaultParams.SiteUrl);
            body = body.Replace("{title1}", emailBodyDefaultParams.Title1);
            body = body.Replace("{title2}", emailBodyDefaultParams.Title2);
            body = body.Replace("{banner}", emailBodyDefaultParams.Banner);
            body = body.Replace("{title3}", emailBodyDefaultParams.Title3);
            body = body.Replace("{contactemail}", emailBodyDefaultParams.ContactEmail);
            body = body.Replace("{cardcolor}", emailBodyDefaultParams.CardColor);
            body = body.Replace("{backgroundcolor}", emailBodyDefaultParams.BackgroundColor);
            body = body.Replace("{fontcolor}", emailBodyDefaultParams.FontColor);

            if (emailBodyDefaultParams.EmailTypeName == Constants.CONFIRMATION_EMAIL_TYPE ||
                emailBodyDefaultParams.EmailTypeName == Constants.RESET_PASSWORD_EMAIL_TYPE ||
                emailBodyDefaultParams.EmailTypeName == Constants.SUPPLLIER_REQUEST_NOTIFICATION
                )
            {
                body = body.Replace("{callbackdisplaytext}", emailBodyDefaultParams.CallbackDisplayText);
                body = body.Replace("{sitelogo}", emailBodyDefaultParams.Logo);
                body = body.Replace("{footer}", emailBodyDefaultParams.EmailCaption);
            }

            return(body);
        }
Exemplo n.º 2
0
        public async Task <object> ForgotPassword(string Email)
        {
            try
            {
                if (Email == null)
                {
                    return(new Response <bool>(Constants.NOT_FOUND_CODE, false, Constants.NOT_FOUND));
                }

                var user = await UserManager.FindByEmailAsync(Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(new Response <bool>(Constants.NOT_FOUND_CODE, false, Constants.NOT_FOUND));
                }
                var rand = new RandomGenerator();
                var code = rand.RandomToken();

                EmailBodyDefaultParams emailBodyDefaultParams = db.EmailBodyDefaultParams
                                                                .Where(e => e.EmailTypeName == "reset_password_api").FirstOrDefault();
                string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                body = body.Replace("{callbackurl}", "#");
                body = body.Replace("{callbackdisplaytext}", code);

                var contentAppName = db.ContentManagement.Where(cm => cm.Name == "app_name")
                                     .FirstOrDefault();
                string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                var simpleResponse = EmailSender.SendEmail(Email, AppName, body);

                ResetPasswordToken resetPasswordToken = new ResetPasswordToken()
                {
                    ResetPasswordCode = code,
                    UserId            = user.Id,
                    ResetPasswordCodeValidityEndDate = DateTime.Now.AddMinutes(ResetPasswordConstants.Validity),
                };
                var prevAttempts = db.ResetPasswordTokens.Where(x => x.UserId == user.Id && x.Status == ResetPasswordTokenStatus.PendingValidation)
                                   .ToList();
                prevAttempts.ForEach((x) => {
                    x.Status = ResetPasswordTokenStatus.Expired;
                });
                db.ResetPasswordTokens.UpdateRange(prevAttempts);
                db.ResetPasswordTokens.Add(resetPasswordToken);
                await db.SaveChangesAsync();

                return(new Response <bool>(Constants.SUCCESS_CODE, true, Constants.SUCCESS));
            }
            catch (Exception e)
            {
                Serilog.Log.Error(e, Constants.LogTemplates.RESET_PASSWORD_EX, Email);
                return(new Response <bool>(Constants.SOMETHING_WRONG_CODE, false, GetExceptionMessage(e)));
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    Customer customer = new Customer();
                    customer.UserId = user.Id;
                    _context.Customer.Add(customer);
                    _context.SaveChanges();
                    await _userManager.AddToRoleAsync(user, "Customer");

                    var contentAppName = _context.ContentManagement.Where(cm => cm.Name == "app_name")
                                         .FirstOrDefault();
                    string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

                    EmailBodyDefaultParams emailBodyDefaultParams = _context.EmailBodyDefaultParams
                                                                    .Where(e => e.EmailTypeName == "confirm_mail").FirstOrDefault();
                    string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                    body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));
                    var simpleResponse = EmailSender.SendEmail(Input.Email, AppName, body);
                    TempData.Set("Toast", simpleResponse);
                    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());
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                Serilog.Log.Error("Model state is not valid", "Model state is not valid", _userManager.GetUserId(User));
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                Serilog.Log.Error($"Unable to load user with ID '{_userManager.GetUserId(User)}'.",
                                  $"Unable to load user with ID '{_userManager.GetUserId(User)}'.", _userManager.GetUserId(User));
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var contentAppName = _context.ContentManagement.Where(cm => cm.Name == "app_name")
                                 .FirstOrDefault();
            string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

            var userId = await _userManager.GetUserIdAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

            EmailBodyDefaultParams emailBodyDefaultParams = _context.EmailBodyDefaultParams
                                                            .Where(e => e.EmailTypeName == "confirm_mail").FirstOrDefault();
            string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);

            body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));

            SimpleResponse jsonResult = EmailSender.SendEmail(Input.Email, AppName, body);

            StatusMessage = jsonResult.Message;
            Serilog.Log.Information(jsonResult.Message, jsonResult.Message, user.Email);
            return(RedirectToPage());
        }
        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"));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

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

                EmailBodyDefaultParams emailBodyDefaultParams = _context.EmailBodyDefaultParams
                                                                .Where(e => e.EmailTypeName == "reset_password").FirstOrDefault();
                string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));

                var contentAppName = _context.ContentManagement.Where(cm => cm.Name == "app_name")
                                     .FirstOrDefault();
                string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                var simpleResponse = EmailSender.SendEmail(Input.Email, AppName, body);
                TempData.Set("Toast", simpleResponse);

                if (simpleResponse.Code != Constants.SUCCESS_CODE)
                {
                    ModelState.AddModelError(string.Empty, simpleResponse.Message);
                }
                Serilog.Log.Information(simpleResponse.Message, simpleResponse.Message, Input.Email);
                return(LocalRedirect(Url.Content("~/")));
            }
            Serilog.Log.Error(Constants.SOMETHING_WRONG, Constants.SOMETHING_WRONG, Input.Email);
            return(Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            RequirePassword = await _userManager.HasPasswordAsync(user);

            if (RequirePassword)
            {
                if (!await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    ModelState.AddModelError(string.Empty, "Password not correct.");
                    return(Page());
                }
            }
            var strategy = _context.Database.CreateExecutionStrategy();

            await strategy.ExecuteAsync(async() =>
            {
                using (var transaction = await _context.Database.BeginTransactionAsync())
                {
                    try
                    {
                        string UserEmail = user.Email;
                        var result       = await _userManager.DeleteAsync(user);
                        var userId       = await _userManager.GetUserIdAsync(user);
                        if (!result.Succeeded)
                        {
                            _logger.LogInformation(new InvalidOperationException($"Unexpected error " +
                                                                                 $"occurred deleteing user with ID '{userId}'."), "User with ID '{UserId}'" +
                                                   " deleted themselves.", userId);
                        }
                        var contentAppName = _context.ContentManagement.Where(cm => cm.Name == "app_name")
                                             .FirstOrDefault();
                        string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                        EmailBodyDefaultParams emailBodyDefaultParams = _context.EmailBodyDefaultParams
                                                                        .Where(e => e.EmailTypeName == "delete_account").FirstOrDefault();
                        string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                        EmailSender.SendEmail(UserEmail, AppName, body);

                        await _signInManager.SignOutAsync();
                        transaction.Commit();
                        _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            });

            var simpleResponse = new SimpleResponse(Constants.INFO_CODE, "Account deleted successfully");

            TempData.Set("Toast", simpleResponse);
            return(Redirect("~/"));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> OnPostAsync()
        {
            ReturnUrl = Url.Content("~/");
            if (ModelState.IsValid)
            {
                if (User.Identity.IsAuthenticated)
                {
                    await _signInManager.SignOutAsync();

                    _logger.LogInformation("User logged out.");
                }
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    var UserManager = _serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                    var RoleManager = _serviceProvider.GetRequiredService <RoleManager <ApplicationRole> >();

                    var roleResult = await RoleManager.FindByNameAsync("Supplier");

                    if (roleResult == null)
                    {
                        roleResult = new ApplicationRole("Supplier");
                        await RoleManager.CreateAsync(roleResult);
                    }
                    await UserManager.AddToRoleAsync(user, "Supplier");

                    FuelSupplier fuelSupplier = new FuelSupplier();
                    fuelSupplier.UserId    = user.Id;
                    fuelSupplier.Name      = Input.Name;
                    fuelSupplier.CountryId = Input.CountryId;
                    fuelSupplier.IsMiddler = Input.IsMiddler;

                    if (Input.file != null)
                    {
                        FileInfo fi          = new FileInfo(Input.file.FileName);
                        var      newFilename = "P" + fuelSupplier.Id + "_" + string.Format("{0:d}",
                                                                                           (DateTime.Now.Ticks / 10) % 100000000) + fi.Extension;
                        var webPath = _hostingEnvironment.WebRootPath;
                        var path    = Path.Combine("", webPath + @"\uploads\suppliers\" + newFilename);

                        var pathToSave = @"/uploads/suppliers/" + newFilename;

                        using (var stream = new FileStream(path, FileMode.Create))
                        {
                            await Input.file.CopyToAsync(stream);
                        }
                        fuelSupplier.ImageUrl = pathToSave;
                    }

                    SupplierContact supplierContact1 = new SupplierContact();
                    supplierContact1.ContactId = 3;
                    supplierContact1.Value     = Input.CompanyWebSite;

                    SupplierContact supplierContact2 = new SupplierContact();
                    supplierContact2.ContactId = 18;
                    supplierContact2.Value     = _context.Country.Find(Input.CountryId) != null?
                                                 _context.Country.Find(Input.CountryId).Name : "";

                    fuelSupplier.SupplierContact = new List <SupplierContact>();
                    fuelSupplier.SupplierContact.Add(supplierContact1);
                    fuelSupplier.SupplierContact.Add(supplierContact2);

                    SupplierContactPerson supplierContactPerson = new SupplierContactPerson();
                    supplierContactPerson.JobTitle = Input.Position;
                    supplierContactPerson.Name     = Input.Name;
                    SupplierContactPersonContact supplierContactPersonContact = new SupplierContactPersonContact();
                    supplierContactPersonContact.ContactId             = 7;
                    supplierContactPersonContact.Value                 = Input.Email;
                    supplierContactPerson.SupplierContactPersonContact = new List <SupplierContactPersonContact>();
                    supplierContactPerson.SupplierContactPersonContact.Add(supplierContactPersonContact);

                    fuelSupplier.SupplierContactPerson = new List <SupplierContactPerson>();
                    fuelSupplier.SupplierContactPerson.Add(supplierContactPerson);

                    _context.FuelSupplier.Add(fuelSupplier);
                    _context.SaveChanges();

                    var contentAppName = _context.ContentManagement.Where(cm => cm.Name == "app_name")
                                         .FirstOrDefault();
                    string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

                    EmailBodyDefaultParams emailBodyDefaultParams = _context.EmailBodyDefaultParams
                                                                    .Where(e => e.EmailTypeName == "confirm_mail").FirstOrDefault();
                    string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                    body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));
                    var simpleResponse = EmailSender.SendEmail(Input.Email, AppName, body);
                    TempData.Set("Toast", simpleResponse);
                    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());
        }
Exemplo n.º 8
0
        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 ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    Customer customer = new Customer();
                    customer.UserId = user.Id;
                    _context.Customer.Add(customer);
                    _context.SaveChanges();
                    var contentAppName = _context.ContentManagement.Where(cm => cm.Name == "app_name")
                                         .FirstOrDefault();
                    string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

                    EmailBodyDefaultParams emailBodyDefaultParams = _context.EmailBodyDefaultParams
                                                                    .Where(e => e.EmailTypeName == "confirm_mail").FirstOrDefault();
                    string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                    body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));
                    var simpleResponse = EmailSender.SendEmail(Input.Email, AppName, body);
                    TempData.Set("Toast", simpleResponse);

                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Create(RequestViewModel model)
        {
            var user = (await GetCurrentUserAsync());

            try
            {
                model.Req.SendDate = DateTime.UtcNow;

                if (user.Customer.Id != model.Req.CustomerId)
                {
                    return(BadRequest());
                }

                if (ModelState.IsValid)
                {
                    // set up email notification
                    var contentAppName = db.ContentManagement.Where(cm => cm.Name == "app_name")
                                         .FirstOrDefault();
                    string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;
                    EmailBodyDefaultParams emailBodyDefaultParams = db.EmailBodyDefaultParams
                                                                    .Where(e => e.EmailTypeName == "supplier_request_notification").FirstOrDefault();
                    string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                    //

                    db.Request.Add(model.Req);
                    model.SelectedOffers.ForEach(offerId =>
                    {
                        var selectedOffer      = db.Offer.Find(offerId);
                        var selectedOfferParty = selectedOffer.AirportOffers.Where(x => x.AirportId == model.Req.AirportId).FirstOrDefault();

                        RequestOffers requestOffers = new RequestOffers()
                        {
                            OfferId        = offerId,
                            RequestId      = model.Req.Id,
                            AirportOfferId = selectedOfferParty.Id,
                            RStatus        = ReplyStatus.Pending,
                        };
                        db.Add(requestOffers);
                        db.SaveChanges();

                        #region send email
                        //get supllier

                        var supplierEmail = selectedOffer.FuelSupplier.User.Email;
                        var callbackUrl   = Url.AbsoluteAction("Details", "Requests", new { Area = "Supplier", id = model.Req.Id });
                        body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));
                        var simpleResponse = EmailSender.SendEmailNotification(supplierEmail, AppName, body);
                        #endregion
                    });
                    //model.Req.


                    return(RedirectToAction(nameof(Details), new { id = model.Req.Id }));
                }
            }
            catch (Exception e)
            {
                Serilog.Log.Error(GetExceptionMessage(e));
                ModelState.AddModelError("", GetExceptionMessage(e));
                //throw;
            }


            model.Req.Airport = db.Airport.Find(model.Req.AirportId);
            model.Req.Airport.AirportOffer = db.AirportOffers.Where(x => !x.IsDeleted).Where(x => x.AirportId == model.Req.AirportId).ToList();
            ViewBag.CustomerId             = db.Customer.Where(c => c.UserId == user.Id).FirstOrDefault().Id;
            ViewBag.OfferFuelTypes         = new SelectList(db.FuelType.ToList(), "Id", "Name");

            var AirportOffer = db.AirportOffers.Where(x => !x.IsDeleted).Where(x => x.AirportId == model.Req.AirportId).ToList();
            var offers       = AirportOffer.Where(x => !x.Offer.IsDeleted)
                               .Where(q => q.Offer.EndDate > DateTime.Now)
                               .Select(q => new Select2ResultDTO()
            {
                id = q?.OfferId?.ToString(), text = q?.Offer?.FuelSupplier?.Name
            })
                               .ToList();
            ViewBag.Offers = offers;

            return(View(model));
        }
Exemplo n.º 10
0
        public async Task <JsonResult> SupplierRegister([FromBody] SupplierRegisterModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (User.Identity.IsAuthenticated)
                    {
                        await SignInManager.SignOutAsync();

                        Serilog.Log.Information("User logged out.");
                    }
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        Serilog.Log.Information("User created a new account with password.");


                        var roleResult = await RoleManager.FindByNameAsync("Supplier");

                        if (roleResult == null)
                        {
                            roleResult = new ApplicationRole()
                            {
                                Name = "Supplier"
                            };
                            await RoleManager.CreateAsync(roleResult);
                        }
                        await UserManager.AddToRoleAsync(user, "Supplier");

                        FuelSupplier fuelSupplier = new FuelSupplier();
                        fuelSupplier.UserId    = user.Id;
                        fuelSupplier.Name      = model.Name;
                        fuelSupplier.CountryId = model.CountryId;
                        fuelSupplier.IsMiddler = model.IsMiddler;

                        if (model.file != null)
                        {
                            FileInfo fi          = new FileInfo(model.file.FileName);
                            var      newFilename = "P" + fuelSupplier.Id + "_" + string.Format("{0:d}",
                                                                                               (DateTime.Now.Ticks / 10) % 100000000) + fi.Extension;
                            var webPath = _hostingEnvironment.WebRootPath;
                            var path    = Path.Combine("", webPath + @"\uploads\suppliers\" + newFilename);

                            var pathToSave = @"/uploads/suppliers/" + newFilename;

                            using (var stream = new FileStream(path, FileMode.Create))
                            {
                                await model.file.CopyToAsync(stream);
                            }
                            fuelSupplier.ImageUrl = pathToSave;
                        }

                        SupplierContact supplierContact1 = new SupplierContact();
                        supplierContact1.ContactId = 3;
                        supplierContact1.Value     = model.CompanyWebSite;

                        SupplierContact supplierContact2 = new SupplierContact();
                        supplierContact2.ContactId = 18;
                        supplierContact2.Value     = db.Country.Find(model.CountryId) != null?
                                                     db.Country.Find(model.CountryId).Name : "";

                        fuelSupplier.SupplierContact = new List <SupplierContact>();
                        fuelSupplier.SupplierContact.Add(supplierContact1);
                        fuelSupplier.SupplierContact.Add(supplierContact2);

                        SupplierContactPerson supplierContactPerson = new SupplierContactPerson();
                        supplierContactPerson.JobTitle = model.Position;
                        supplierContactPerson.Name     = model.Name;
                        SupplierContactPersonContact supplierContactPersonContact = new SupplierContactPersonContact();
                        supplierContactPersonContact.ContactId             = 7;
                        supplierContactPersonContact.Value                 = model.Email;
                        supplierContactPerson.SupplierContactPersonContact = new List <SupplierContactPersonContact>();
                        supplierContactPerson.SupplierContactPersonContact.Add(supplierContactPersonContact);

                        fuelSupplier.SupplierContactPerson = new List <SupplierContactPerson>();
                        fuelSupplier.SupplierContactPerson.Add(supplierContactPerson);

                        db.FuelSupplier.Add(fuelSupplier);
                        db.SaveChanges();

                        var contentAppName = db.ContentManagement.Where(cm => cm.Name == "app_name")
                                             .FirstOrDefault();
                        string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                        var token = await UserManager.GenerateEmailConfirmationTokenAsync(user);

                        byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(token);
                        var    code = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);

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

                        EmailBodyDefaultParams emailBodyDefaultParams = db.EmailBodyDefaultParams
                                                                        .Where(e => e.EmailTypeName == "confirm_mail").FirstOrDefault();
                        string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                        body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));
                        var simpleResponse = EmailSender.SendEmail(model.Email, AppName, body);
                        //var token = GetTokenForUser(user);
                        return(new JsonResult(new Response <bool>(Constants.SUCCESS_CODE, true, simpleResponse.Message)));
                    }
                    else
                    {
                        string errors = "";
                        foreach (var error in result.Errors)
                        {
                            errors += error;
                        }
                        Serilog.Log.Error("Register Supplier", model.Email, errors);
                    }
                }

                else
                {
                    return(new JsonResult(new Response <bool>(Constants.INVALID_INPUT_CODE, false, Constants.INVALID_INPUT)));
                }
            }
            catch (Exception e)
            {
                Serilog.Log.Error(e, Constants.LogTemplates.LOGIN_ERROR_EX, model.Email);
                return(new JsonResult(new Response <bool>(Constants.SOMETHING_WRONG_CODE, false, GetExceptionMessage(e))));
            }

            return(new JsonResult(new Response <bool>(Constants.SOMETHING_WRONG_CODE, false, Constants.SOMETHING_WRONG)));
        }
Exemplo n.º 11
0
        public async Task <JsonResult> Register([FromBody] CustomerResgisterModel model)
        {
            try
            {//"*****@*****.**"
                //var ree = EmailSender.SendEmail(model.Email, "sub", "mess");
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        Serilog.Log.Information("User created a new account with password.");

                        Customer customer = new Customer();
                        customer.UserId = user.Id;
                        db.Customer.Add(customer);
                        db.SaveChanges();
                        await UserManager.AddToRoleAsync(user, "Customer");

                        var contentAppName = db.ContentManagement.Where(cm => cm.Name == "app_name")
                                             .FirstOrDefault();
                        string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                        var token = await UserManager.GenerateEmailConfirmationTokenAsync(user);

                        byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(token);
                        var    code = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);


                        // generate callback url
                        string sc         = this.Request.Scheme;
                        string host       = this.Request.Host.ToString();
                        string controller = "Identity";
                        string action     = "ConfirmEmail";


                        var callbackUrl = $"{sc}://{host}/{controller}/{action}?userId={user.Id}&code={code}";
                        //

                        EmailBodyDefaultParams emailBodyDefaultParams = db.EmailBodyDefaultParams
                                                                        .Where(e => e.EmailTypeName == "confirm_mail").FirstOrDefault();
                        string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                        body = body.Replace("{callbackurl}", HtmlEncoder.Default.Encode(callbackUrl));
                        var simpleResponse = EmailSender.SendEmail(model.Email, AppName, body);
                        return(new JsonResult(new Response <bool>(Constants.SUCCESS_CODE, true, "Please Confirm Your Email.")));
                    }
                    else
                    {
                        string message = result.Errors.Select(x => x.Description).ToList().Aggregate((x, y) =>
                        {
                            return(x + "," + y);
                        });
                        return(new JsonResult(new Response <bool>(Constants.SOMETHING_WRONG_CODE, false, message)));
                    }
                }
                else
                {
                    Serilog.Log.Error("Register Customer", model.Email);
                    return(new JsonResult(new Response <bool>(Constants.INVALID_INPUT_CODE, false, Constants.INVALID_INPUT)));
                }
            }
            catch (Exception e)
            {
                Serilog.Log.Error(e, Constants.LogTemplates.LOGIN_ERROR_EX, model.Email);
                return(new JsonResult(new Response <bool>(Constants.SOMETHING_WRONG_CODE, false, GetExceptionMessage(e))));
            }
        }