Esempio n. 1
0
        public async Task <IActionResult> OnPostCreateOpinionAsync([Bind] CreateOpinionDto createOpinionModel)
        {
            string offerId = createOpinionModel.OfferId;

            if (!ModelState.IsValid)
            {
                return(await this.OnGetAsync(offerId));
            }

            var opinionCreated = await opinionService.CreateOpinion(createOpinionModel.Text, offerId);

            if (opinionCreated == null)
            {
                return(await this.OnGetAsync(offerId));
            }

            var offerRateAdded = await ratingManager.AddOfferRate(createOpinionModel.Rating, opinionCreated.Id, opinionCreated.UserId);

            if (!offerRateAdded)
            {
                await opinionService.DeleteOpinion(opinionCreated.Id, opinionCreated.UserId);

                Alertify.Push("Creating opinion failed", AlertType.Error);
                return(await this.OnGetAsync(offerId));
            }

            return(RedirectToPage("/OfferDetails", new { area = "Offers", id = offerId }));
        }
Esempio n. 2
0
        public async Task <User> Login(string email, string password)
        {
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                Alertify.Push("Invalid email address or password", AlertType.Error);
                return(null);
            }

            var user = await database.UserRepository.FindUserToLogin(email);

            if (user == null)
            {
                Alertify.Push("Invalid email address or password", AlertType.Error);
                return(null);
            }

            if ((await signInManager.PasswordSignInAsync(user, password, true, false)).Succeeded)
            {
                if (!user.EmailConfirmed)
                {
                    Alertify.Push("Account is not confirmed", AlertType.Warning);
                    return(null);
                }

                return(user);
            }

            Alertify.Push("Invalid email address or password", AlertType.Error);
            return(null);
        }
Esempio n. 3
0
        public async Task <User> Register(string email, string username, string password)
        {
            var user = User.Create(email, username);

            if (await EmailExists(email))
            {
                Alertify.Push("Email address already exists", AlertType.Error);
                return(null);
            }

            if (await UsernameExists(username))
            {
                Alertify.Push("Username already exists", AlertType.Error);
                return(null);
            }

            if ((await userManager.CreateAsync(user, password)).Succeeded)
            {
                await rolesService.AdmitRole(RoleName.User, user);

                var confirmAccountToken = await userManager.GenerateEmailConfirmationTokenAsync(user);

                confirmAccountToken = cryptoService.Encrypt(confirmAccountToken);

                string callbackUrl =
                    $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}/Auth/ConfirmAccount?email={user.Email}&token={confirmAccountToken}";

                await emailSender.Send(EmailMessages.ActivationAccountEmail(email, callbackUrl));

                return(user);
            }

            Alertify.Push("Creating account failed", AlertType.Error);
            return(null);
        }
Esempio n. 4
0
        public async Task <IActionResult> OnPostBookDateAsync([Bind] BookingDateDto bookingDateModel)
        {
            string offerId = bookingDateModel.OfferId;

            if (!ModelState.IsValid)
            {
                return(await this.OnGetAsync(offerId));
            }

            if (!bookingValidationService.ValidateDates(bookingDateModel.StartDate, bookingDateModel.EndDate))
            {
                Alertify.Push("End date must be greater than start date", AlertType.Error);
                return(await this.OnGetAsync(offerId));
            }

            var bookedDate = await bookingService.BookDate(bookingDateModel.StartDate, bookingDateModel.EndDate, offerId);

            if (bookedDate != null)
            {
                Log.Information($"User #{HttpContext.GetCurrentUserId()} booked offer #{offerId} from {bookingDateModel.StartDate.ToShortDateString()} to {bookingDateModel.EndDate.ToShortDateString()}");

                return((IActionResult)RedirectToPage("/BookingSummary", new { area = "Bookings", id = bookedDate.Id }));
            }

            return(await this.OnGetAsync(offerId));
        }
Esempio n. 5
0
        public BaseViewModel WithAlert(string message, AlertType type = AlertType.Info)
        {
            Alert = new Alert(type, message);
            Alertify.Clear();

            return(this);
        }
Esempio n. 6
0
        public async Task <IActionResult> OnPostCheckoutAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var order = await orderService.PurchaseOrder(HttpContext.Session.GetString(Constants.CartId));

            if (order != null)
            {
                if (await emailSender.Send(Constants.OrderCompletedEmail
                                           (
                                               HttpContext.IsAuthenticated() ? order.OrderDetails.CustomerEmail : CheckoutOrderModel.AnonymousEmail,
                                               order.Id, order.OrderDetails.BookingId, order.OrderDetails.OfferTitle,
                                               order.TotalPrice, order.OrderDetails.StartDate, order.OrderDetails.EndDate, order.OrderDetails.Phone,
                                               order.OrderDetails.ContactEmail, order.OrderDetails.Location
                                           )))
                {
                    Log.Information($"User #{HttpContext.GetCurrentUserId()} completed order for offer {order.OrderDetails.OfferTitle} [Order #{order.Id}]");
                    return((IActionResult)RedirectToPage("/MyBookings", new { area = "Bookings" }));
                }

                Alertify.Push("Order has been completed but email cannot be sent. Please contact MyBooking team", AlertType.Warning);
                return(await this.OnGetAsync());
            }

            return(this.ErrorPage());
        }
Esempio n. 7
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var sendResetPasswordResult = await resetPasswordManager.GenerateResetPasswordToken(Input.Email);

            if (sendResetPasswordResult == null)
            {
                Alertify.Push("Account does not exist", AlertType.Error);
                return(Page());
            }

            var emailSent = await emailSender.Send(Constants.ResetPasswordEmail(sendResetPasswordResult.Email, sendResetPasswordResult.Username,
                                                                                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}Auth/ResetPassword?userId={sendResetPasswordResult.UserId}&code={sendResetPasswordResult.Code}"));

            if (emailSent)
            {
                Alertify.Push($"Reset password token was sent to: {sendResetPasswordResult.Email}");
                return(Page());
            }

            Alertify.Push("There was a problem during sending reset password token");
            return(Page());
        }
Esempio n. 8
0
        public BaseViewModel WithAlert()
        {
            Alert = Alertify.Alert;

            Alertify.Clear();

            return(this);
        }
Esempio n. 9
0
        public async Task <IActionResult> OnPostDeleteOfferAsync(string id)
        {
            if (!await offerService.DeleteOffer(id))
            {
                Alertify.Push("Deleting offer failed", AlertType.Error);
            }

            return(await this.OnGetAsync(FilterParams));
        }
Esempio n. 10
0
        public virtual ErrorBaseViewModel WithError()
        {
            Error = ErrorWriter.Error;
            Alert = Alertify.Alert;

            ErrorWriter.Clear();
            Alertify.Clear();

            return(this);
        }
Esempio n. 11
0
        public async Task <bool> CanExecute(string item)
        {
            if (await authService.EmailExists(item))
            {
                Alertify.Push("Email address already exists", AlertType.Error);
                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        public static IServiceCollection ConfigureSingletonServices(this IServiceCollection services)
        {
            services.AddSingleton <IEmailSender, EmailSender>();
            services.AddSingleton <IFileWriter, FileWriter>();
            services.AddSingleton <IFileReader, FileReader>();
            services.AddSingleton <ICookieClaimsPrincipalManager, CookieClaimsPrincipalManager>();
            services.AddSingleton <ICryptoService, CryptoService>();
            services.AddSingleton <IMimeMappingService>(new MimeMappingService(new FileExtensionContentTypeProvider()));

            services.AddSingleton <Alertify>(a => Alertify.Build());

            return(services);
        }
Esempio n. 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(opt =>
            {
                opt.UseNpgsql(Configuration.GetConnectionString(AppSettingsKeys.ConnectionString));
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath      = Routes.LoginPath;
                options.LogoutPath     = Routes.LogoutPath;
                options.ExpireTimeSpan = TimeSpan.FromDays(Constants.TokenExpireTimeInDays);
            });


            services.AddControllersWithViews();

            services.AddHttpContextAccessor();
            services.AddSession();

            #region services
            services.AddSingleton <ITokenClaimsManager, TokenClaimsManager>();

            services.AddScoped <IDatabase, Database>();
            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));

            services.AddScoped <IAuthService, AuthService>();
            services.AddScoped <IResetPasswordService, ResetPasswordService>();
            services.AddScoped <IProfileService, ProfileService>();
            services.AddScoped <IPostService, PostService>();
            services.AddScoped <IAnswerService, AnswerService>();
            services.AddScoped <IDatabaseManager, DatabaseManager>();
            services.AddScoped <ICategoryService, CategoryService>();
            services.AddScoped <ICryptoService, CryptoService>();
            services.AddScoped <IEmailSender, EmailSender>();

            services.AddSingleton <Alertify>(a => Alertify.Build());
            #endregion

            #region settings

            services.Configure <EmailSettings>(Configuration.GetSection(nameof(EmailSettings)));
            #endregion

            services.AddScoped <OnlyAnonymousFilter>();

            services.AddAutoMapper(typeof(Startup));
        }
Esempio n. 14
0
        public async Task <bool> DeleteFile(string fileId)
        {
            var file = await GetFile(fileId);

            if (file != null)
            {
                fileWriter.Delete(file.Path);

                database.FileRepository.Delete(file);

                return(await database.Complete());
            }

            Alertify.Push("File cannot be found", AlertType.Error);
            return(false);
        }
Esempio n. 15
0
        public async Task <string> DeleteDirectory(string directoryId)
        {
            var directory = await GetDirectory(directoryId);

            if (directory != null)
            {
                fileWriter.DeleteDirectory(directory.Path);

                database.DirectoryRepository.Delete(directory);

                return(await database.Complete() ? directory.ParentDirectoryId ?? string.Empty : null);
            }

            Alertify.Push("Directory cannot be found", AlertType.Error);
            return(null);
        }
        public static IServiceCollection ConfigureSingletonServices(this IServiceCollection services)
        {
            services.AddSingleton <IEmailSender, EmailSender>();
            services.AddSingleton <IFilesManager, FilesManager>();
            services.AddSingleton <IHashGenerator, HashGenerator>();
            services.AddSingleton <ICookieClaimsPrincipalGenerator, CookieClaimsPrincipalGenerator>();
            services.AddSingleton <IHttpContextService, HttpContextService>();
            services.AddSingleton <IHttpContextWriter, HttpContextService>();
            services.AddSingleton <IHttpContextReader, HttpContextService>();

            services.AddSingleton <IReadOnlyFilesManager, FilesManager>();

            services.AddSingleton <Alertify>(a => Alertify.Build());

            return(services);
        }
Esempio n. 17
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (!await resetPasswordManager.ResetPassword(UserId, Code, Input.NewPassword))
            {
                Alertify.Push("Reset password failed", AlertType.Error);
                return(Page());
            }

            PasswordChanged = true;

            return(Page());
        }
Esempio n. 18
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var offerToCreate = mapper.Map <Offer>(CreateOfferInput);

            if (await offerService.CreateOffer(offerToCreate, CreateOfferInput.OfferPhotos))
            {
                return(RedirectToPage("/Index"));
            }

            Alertify.Push("Offer creating failed", AlertType.Error);
            return(Page());
        }
Esempio n. 19
0
        public async Task <bool> UploadFile(IFormFile file, string directoryId = null, bool isPrivate = false)
        {
            if (file == null)
            {
                ErrorWriter.Append("You have to choose file to upload");
                return(false);
            }

            if (await storageSizeManager.CountStorageSize(isPrivateStorage: isPrivate) + (uint)file.Length / StorageSizeManager.UnitConversionMultiplier
                > (!isPrivate ? storageSizeManager.MaxPublicStorageSizeInGb : storageSizeManager.MaxPrivateStorageSizeInGb) * Math.Pow(StorageSizeManager.UnitConversionMultiplier, 2))
            {
                Alertify.Push("Storage is full", AlertType.Warning);
                return(false);
            }

            string filePath = !isPrivate ? @"public/" : $@"private/{currentUserId}/";

            if (!string.IsNullOrEmpty(directoryId))
            {
                var directory = await database.DirectoryRepository.FindDirectoryWithParent(directoryId);

                filePath = await filePathBuilder.BuildFilePath(directory, filePath);
            }

            var uploadedFile = await fileWriter.Upload(file, filePath);

            if (uploadedFile != null)
            {
                var fileToStore = new FileBuilder()
                                  .SetName(file.FileName)
                                  .SetPath(uploadedFile.Path)
                                  .WithSize(uploadedFile.Size)
                                  .InDirectory(directoryId)
                                  .AssignedTo(userId: !isPrivate ? null : currentUserId)
                                  .Build();

                database.FileRepository.Add(fileToStore);

                return(await database.Complete());
            }

            Alertify.Push("File cannot be uploaded", AlertType.Error);
            return(false);
        }
Esempio n. 20
0
        public async Task <IActionResult> OnPostUpdateOfferAsync()
        {
            if (!ModelState.IsValid)
            {
                Alertify.Push("Offer updating failed", AlertType.Error);
                return(await this.OnGetAsync(EditOfferInput.Id));
            }

            var offer = await offerService.GetOffer(EditOfferInput.Id);

            var offerToUpdate = mapper.Map <EditOfferDto, Offer>(EditOfferInput, offer);

            if (await offerService.UpdateOffer(offerToUpdate, EditOfferInput.OfferPhotos))
            {
                return(RedirectToPage("/MyOffers", new { area = "Offers" }));
            }

            Alertify.Push("Offer updating failed", AlertType.Error);
            return(await this.OnGetAsync(EditOfferInput.Id));
        }
Esempio n. 21
0
        public async Task <IActionResult> OnGetAsync([FromQuery] string userId, string code, string newEmail)
        {
            if (await authValidationService.EmailExists(newEmail))
            {
                Alertify.Push("Email address already exists", AlertType.Error);
                return(Page());
            }

            var emailChanged = await profileService.ChangeEmail(userId, newEmail, code);

            if (emailChanged)
            {
                Alertify.Push("Email changed", AlertType.Primary);
            }
            else
            {
                Alertify.Push("Email changing failed", AlertType.Error);
            }

            return(RedirectToPage("/Profile", new { area = "Profile", emailChanged = emailChanged }));
        }
Esempio n. 22
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (await authValidationService.EmailExists(UserRegister.Email))
            {
                ModelState.TryAddModelError(ErrorCodes.EmailExists, "Email address already exists");
                return(Page());
            }

            if (await authValidationService.UsernameExists(UserRegister.Username))
            {
                ModelState.TryAddModelError(ErrorCodes.UsernameExists, "Username already exists");
                return(Page());
            }

            var authResult = await authService.SignUp(UserRegister.Email, UserRegister.Password, UserRegister.Username);

            if (authResult != null)
            {
                var emailSent = await emailSender.Send(Constants.ActivationAccountEmail(UserRegister.Email,
                                                                                        $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}Auth/ConfirmAccount?userId={authResult.User.Id}&code={authResult.Token}"));

                if (emailSent)
                {
                    Alertify.Push($"Activation email was sent to: {UserRegister.Email}", AlertType.Info);
                    return(Page());
                }

                Alertify.Push("There was a problem during sending activation email", AlertType.Error);
            }

            return(Page());
        }
Esempio n. 23
0
 public void Dispose()
 {
     Alertify.Clear();
 }
Esempio n. 24
0
 public static IActionResult PushAlert(this IActionResult view, string message, AlertType type = AlertType.Info)
 {
     Alertify.Push(message, type);
     return(view);
 }