Пример #1
0
        public IHttpActionResult Login(LoginModel loginModel)
        {
            var redirect = false;

            if (loginModel == null || !ModelState.IsValid || !ShouldSignIn(loginModel.Email, loginModel.Password))
            {
                VerboseReporter.ReportError("The email or password is invalid", "login");
                return(RespondFailure());
            }

            //sign in the current user
            var loginStatus = ApplicationContext.Current.SignIn(loginModel.Email, loginModel.Persist);

            if (loginStatus == LoginStatus.Success)
            {
                //update the last login date & ip address
                var currentUser = ApplicationContext.Current.CurrentUser;
                currentUser.LastLoginDate      = DateTime.UtcNow;
                currentUser.LastLoginIpAddress = WebHelper.GetClientIpAddress();
                _userService.Update(currentUser);

                VerboseReporter.ReportSuccess("Your login was successful", "login");
                return(RespondSuccess(new {
                    ReturnUrl = loginModel.ReturnUrl,
                    User = ApplicationContext.Current.CurrentUser.ToModel(_mediaService, _mediaSettings, _followService, _friendService, _notificationService)
                }));
            }
            VerboseReporter.ReportError("The login attempt failed due to unknown error", "login");
            return(RespondFailure());
        }
        public async Task <IActionResult> GetById([FromQuery] NewsItemRequestModel requestModel)
        {
            #region predicate


            Expression <Func <NewsItem, bool> > where = x => true;

            where = ExpressionHelpers.CombineAnd(where, x => x.Id == requestModel.Id);

            #endregion

            var article = await _newsItemService.FirstOrDefaultAsync(
                where,
                x => x.NewsItemCategories,
                x => x.NewsItemTags);

            if (article == null)
            {
                VerboseReporter.ReportError("Không tìm thấy tin tức này", "get");
                return(RespondFailure());
            }

            var model = article.ToModel(requestModel.LanguageId);

            //GetLocales(article, model);

            return(RespondSuccess(model));
        }
        public IHttpActionResult UploadVideo()
        {
            var files = HttpContext.Current.Request.Files;

            if (files.Count == 0)
            {
                VerboseReporter.ReportError("No file uploaded", "upload_videos");
                return(RespondFailure());
            }

            var file = files[0];
            //and it's name
            var fileName = file.FileName;


            //file extension and it's type
            var fileExtension = Path.GetExtension(fileName);

            if (!string.IsNullOrEmpty(fileExtension))
            {
                fileExtension = fileExtension.ToLowerInvariant();
            }

            var contentType = file.ContentType;

            if (string.IsNullOrEmpty(contentType))
            {
                contentType = VideoUtility.GetContentType(fileExtension);
            }

            if (contentType == string.Empty)
            {
                VerboseReporter.ReportError("Invalid file type", "upload_videos");
                return(RespondFailure());
            }

            var bytes = new byte[file.ContentLength];

            file.InputStream.Read(bytes, 0, bytes.Length);

            //create a new media
            var media = new Media()
            {
                MediaType   = MediaType.Video,
                Binary      = bytes,
                MimeType    = contentType,
                Name        = fileName,
                UserId      = ApplicationContext.Current.CurrentUser.Id,
                DateCreated = DateTime.UtcNow
            };

            _mediaService.WriteVideoBytes(media);
            //insert now
            _mediaService.Insert(media);
            return(RespondSuccess(new
            {
                Media = media.ToModel(_mediaService, _mediaSettings)
            }));
        }
Пример #4
0
        public IHttpActionResult UploadVideo()
        {
            var files = HttpContext.Current.Request.Files;

            if (files.Count == 0)
            {
                VerboseReporter.ReportError("No file uploaded", "upload_videos");
                return(RespondFailure());
            }

            var file = files[0];
            //and it's name
            var fileName = file.FileName;


            //file extension and it's type
            var fileExtension = Path.GetExtension(fileName);

            if (!string.IsNullOrEmpty(fileExtension))
            {
                fileExtension = fileExtension.ToLowerInvariant();
            }

            var contentType = file.ContentType;

            if (string.IsNullOrEmpty(contentType))
            {
                contentType = VideoUtility.GetContentType(fileExtension);
            }

            if (contentType == string.Empty)
            {
                VerboseReporter.ReportError("Invalid file type", "upload_videos");
                return(RespondFailure());
            }

            var bytes = new byte[file.ContentLength];

            file.InputStream.Write(bytes, 0, file.ContentLength);

            //create a new media
            var media = new Media()
            {
                MediaType = MediaType.Video,
                Binary    = bytes,
                MimeType  = contentType,
                Name      = fileName
            };

            _mediaService.WriteVideoBytes(media);

            return(RespondSuccess(new {
                VideoId = media.Id,
                VideoUrl = WebHelper.GetUrlFromPath(media.LocalPath, _generalSettings.VideoServerDomain),
                ThumbnailUrl = WebHelper.GetUrlFromPath(media.ThumbnailPath, _generalSettings.ImageServerDomain),
                MimeType = file.ContentType
            }));
        }
Пример #5
0
        public IHttpActionResult UploadPictures()
        {
            var files = HttpContext.Current.Request.Files;

            if (files.Count == 0)
            {
                VerboseReporter.ReportError("No file uploaded", "upload_pictures");
                return(RespondFailure());
            }
            var newImages = new List <object>();

            for (var index = 0; index < files.Count; index++)
            {
                //the file
                var file = files[index];

                //and it's name
                var fileName = file.FileName;
                //stream to read the bytes
                var stream       = file.InputStream;
                var pictureBytes = new byte[stream.Length];
                stream.Read(pictureBytes, 0, pictureBytes.Length);

                //file extension and it's type
                var fileExtension = Path.GetExtension(fileName);
                if (!string.IsNullOrEmpty(fileExtension))
                {
                    fileExtension = fileExtension.ToLowerInvariant();
                }

                var contentType = file.ContentType;

                if (string.IsNullOrEmpty(contentType))
                {
                    contentType = PictureUtility.GetContentType(fileExtension);
                }

                var picture = new Media()
                {
                    Binary   = pictureBytes,
                    MimeType = contentType,
                    Name     = fileName
                };

                _mediaService.WritePictureBytes(picture, _mediaSettings.PictureSaveLocation);
                //save it
                _mediaService.Insert(picture);
                newImages.Add(new {
                    ImageUrl     = _mediaService.GetPictureUrl(picture.Id),
                    ThumbnailUrl = _mediaService.GetPictureUrl(picture.Id, PictureSizeNames.ThumbnailImage),
                    ImageId      = picture.Id,
                    MimeType     = contentType
                });
            }

            return(RespondSuccess(new { Images = newImages }));
        }
Пример #6
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignIn([FromBody] LoginViewModel model, [FromRoute] string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(RespondFailure(model));
            }

            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

            if (result.RequiresTwoFactor)
            {
                return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }));
            }
            if (result.Succeeded)
            {
                string anonymousBasketId = Request.Cookies[Constants.BASKET_COOKIENAME];
                if (!String.IsNullOrEmpty(anonymousBasketId))
                {
                    await _basketService.TransferBasketAsync(anonymousBasketId, model.Email);

                    Response.Cookies.Delete(Constants.BASKET_COOKIENAME);
                }
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, model.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                var token = new JwtSecurityToken
                            (
                    issuer: _configuration["Token:Issuer"],
                    audience: _configuration["Token:Audience"],
                    claims: claims,
                    expires: DateTime.UtcNow.AddDays(60),
                    notBefore: DateTime.UtcNow,
                    signingCredentials: new SigningCredentials(new SymmetricSecurityKey
                                                                   (Encoding.UTF8.GetBytes(_configuration["Token:Key"])),
                                                               SecurityAlgorithms.HmacSha256)
                            );

                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    throw new ApplicationException($"Unable to load user with email '{model.Email}'.");
                }

                return(RespondSuccess(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    result,
                    user
                }));
            }
            VerboseReporter.ReportError(string.Empty, "Invalid login attempt.");
            return(RespondFailure(model));
        }
        public IHttpActionResult Put(UserEntityPublicModel entityModel)
        {
            var user = _userService.Get(entityModel.Id);

            if (user == null)
            {
                return(NotFound());
            }

            //check if the email has already been registered
            var emailUser = _userService.Get(x => x.Email == entityModel.Email, null).FirstOrDefault();

            if (emailUser != null && emailUser.Id != user.Id)
            {
                VerboseReporter.ReportError("The email is already registered with another user", "post_user");
                return(RespondFailure());
            }

            //same for user name
            if (_userSettings.AreUserNamesEnabled)
            {
                var userNameUser = _userService.Get(x => x.UserName == entityModel.UserName, null).FirstOrDefault();
                if (userNameUser != null && userNameUser.Id != user.Id)
                {
                    VerboseReporter.ReportError("The username is already taken by another user", "post_user");
                    return(RespondFailure());
                }
            }

            user.FirstName   = entityModel.FirstName;
            user.LastName    = entityModel.LastName;
            user.Email       = entityModel.Email;
            user.DateUpdated = DateTime.UtcNow;
            user.Name        = string.Concat(user.FirstName, " ", user.LastName);
            user.UserName    = entityModel.UserName;

            _userService.Update(user);

            //any images to assign
            if (entityModel.CoverImageId != 0)
            {
                user.SetPropertyValue(PropertyNames.DefaultCoverId, entityModel.CoverImageId);
            }
            if (entityModel.ProfileImageId != 0)
            {
                user.SetPropertyValue(PropertyNames.DefaultPictureId, entityModel.ProfileImageId);
            }

            VerboseReporter.ReportSuccess("Successfully saved profile", "post_user");
            return(RespondSuccess(new {
                User = user.ToEntityPublicModel(_mediaService, _mediaSettings)
            }));
        }
Пример #8
0
        public IHttpActionResult Delete(int id)
        {
            var setting = _settingService.Get(id);

            if (setting == null)
            {
                VerboseReporter.ReportError("Setting not found", "delete_setting");
                return(RespondFailure());
            }
            _settingService.Delete(setting);
            VerboseReporter.ReportSuccess("Setting deleted successfully", "delete_setting");
            return(RespondSuccess());
        }
        public IHttpActionResult Login(LoginModel loginModel)
        {
            var redirect = false;

            if (loginModel == null || !ModelState.IsValid)
            {
                if (!ModelState.IsValid && loginModel != null)
                {
                    redirect = loginModel.Redirect;
                }

                if (!redirect)
                {
                    VerboseReporter.ReportError("The email or password is invalid", "login");
                    return(RespondFailure());
                }
                return(RespondRedirect(Request.RequestUri));
            }

            redirect = loginModel.Redirect;
            if (!ShouldSignIn(loginModel.Email, loginModel.Password))
            {
                if (!redirect)
                {
                    VerboseReporter.ReportError("The email or password is invalid", "login");
                    return(RespondFailure());
                }
                return(RespondRedirect(Request.RequestUri));
            }

            //sign in the current user
            var loginStatus = ApplicationContext.Current.SignIn(loginModel.Email, loginModel.Persist);

            if (loginStatus == LoginStatus.Success)
            {
                if (!redirect)
                {
                    VerboseReporter.ReportSuccess("Your login was successful", "login");
                    return(RespondSuccess(new {
                        ReturnUrl = loginModel.ReturnUrl
                    }));
                }
                return(RespondRedirect(loginModel.ReturnUrl));
            }
            if (!redirect)
            {
                VerboseReporter.ReportError("The login attempt failed due to unknown error", "login");
                return(RespondFailure());
            }
            return(RespondRedirect(Request.RequestUri));
        }
Пример #10
0
        public async Task <IActionResult> Get([FromRoute] string seName)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var page = await _categoryService.GetBySeNameAsync(seName);

            if (page == null)
            {
                VerboseReporter.ReportError("Không tìm thấy danh mục");
                return(RespondFailure());
            }
            var model = page.ToModel();

            return(RespondSuccess(model));
        }
        public IHttpActionResult Install(PluginInfoModel model)
        {
            //first find the plugin
            var pluginInfo = _pluginFinderService.FindPlugin(model.SystemName);

            if (pluginInfo == null)
            {
                //was it a correct plugin?
                VerboseReporter.ReportError("The plugin doesn't exist", "plugin");
                return(RespondFailure());
            }

            //install the plugin
            _pluginInstallerService.Install(pluginInfo);

            VerboseReporter.ReportSuccess("The plugin has been installed", "plugin");
            return(RespondSuccess());
        }
        public IHttpActionResult SavePageManager(int artistPageId, int customerId)
        {
            //let's perform a few checks before saving the page manager
            //1. does the artist page exist and is the current user eligible to add manager?
            var artistPage = _artistPageService.Get(artistPageId);

            if (artistPage != null && CanDelete(artistPage))
            {
                //2. does the customer really exist?
                var customer = _userService.Get(customerId);
                if (customer != null)
                {
                    //3. is the customer already a page manager
                    if (_artistPageManagerService.IsPageManager(artistPageId, customerId))
                    {
                        VerboseReporter.ReportError("The user is already the page manager for this page", "save_page_manager");
                        return(RespondFailure());
                    }
                    //enough checks...save the new manager now
                    _artistPageManagerService.AddPageManager(new ArtistPageManager()
                    {
                        ArtistPageId = artistPageId,
                        CustomerId   = customerId,
                    });

                    return(RespondSuccess());
                }
                else
                {
                    VerboseReporter.ReportError("The user doesn't exists", "save_page_manager");
                    return(RespondFailure());
                }
            }
            else
            {
                VerboseReporter.ReportError("Unauthorized", "save_page_manager");
                return(RespondFailure());
            }
        }
        public IHttpActionResult ProcessPayment(FormCollection parameters)
        {
            //first get the payment processor
            var paymentMethodName = parameters.Get(PaymentParameterNames.PaymentMethodTypeName);

            if (string.IsNullOrEmpty(paymentMethodName))
            {
                VerboseReporter.ReportError("Invalid payment method", "process_payment");
                return(RespondFailure());
            }

            //the transaction amount
            decimal amount;
            var     amountString = parameters.Get(PaymentParameterNames.Amount) ?? "0";

            decimal.TryParse(amountString, out amount);

            PaymentMethodType methodType;

            if (System.Enum.TryParse(paymentMethodName, out methodType))
            {
                methodType = PaymentMethodType.CreditCard;
            }

            //get the payment processor now
            var paymentProcessor = _paymentProcessingService.GetPaymentProcessorPlugin(amount, methodType);

            if (paymentProcessor == null)
            {
                VerboseReporter.ReportError("Invalid payment method", "process_payment");
                return(RespondFailure());
            }

            //convert form collection to dictionary to check if parameters are valid
            var formCollectionDictionary = parameters.ToDictionary(pair => pair.Key, pair => (object)pair.Value);

            var isValid = paymentProcessor.AreParametersValid(formCollectionDictionary);

            UserPaymentMethod paymentMethod = null;

            if (!isValid)
            {
                //the parameters are not valid. but that may also mean that the user is selecting an already saved payment method
                //and so he wouldn't have sent that data again
                var savedPaymentMethodIdString = parameters.Get(PaymentParameterNames.UserSavedPaymentMethodId);
                int savedPaymentMethodId;
                if (int.TryParse(savedPaymentMethodIdString, out savedPaymentMethodId))
                {
                    var userPaymentMethods =
                        _paymentMethodService.Get(x => x.UserId == ApplicationContext.Current.CurrentUser.Id && x.Id == savedPaymentMethodId, null);

                    if (userPaymentMethods.Any())
                    {
                        paymentMethod = userPaymentMethods.First();
                        isValid       = true;
                    }
                }
                //still invalid? something is not right then.
                if (!isValid)
                {
                    VerboseReporter.ReportError("Invalid parameters to process payment", "process_payment");
                    return(RespondFailure());
                }
            }

            //we save the payment method in our database if it's CreditCard
            if (paymentProcessor.Supports(PaymentMethodType.CreditCard))
            {
                if (paymentMethod == null)
                {
                    #region saving payment method to database
                    var creditCardNumber = parameters.Get(PaymentParameterNames.CardNumber);
                    //let's validate the card for level 1 check (luhn's test) first before storing
                    var isCardValid = PaymentCardHelper.IsCardNumberValid(creditCardNumber);
                    //card number
                    if (!isCardValid)
                    {
                        VerboseReporter.ReportError("Invalid card number", "process_payment");
                        return(RespondFailure());
                    }
                    //expiration date
                    var expireMonth = parameters.Get(PaymentParameterNames.ExpireMonth);
                    var expireYear  = parameters.Get(PaymentParameterNames.ExpireYear);
                    if (!expireYear.IsInteger() || !expireMonth.IsInteger())
                    {
                        VerboseReporter.ReportError("Invalid expiration month or year", "process_payment");
                        return(RespondFailure());
                    }
                    //card issuer
                    var cardIssuer = PaymentCardHelper.GetCardTypeFromNumber(creditCardNumber);
                    if (!cardIssuer.HasValue)
                    {
                        VerboseReporter.ReportError("Unsupported card provider", "process_payment");
                        return(RespondFailure());
                    }


                    var nameOnCard = parameters.Get(PaymentParameterNames.NameOnCard);
                    //encrypt credit card info to store in db
                    var key  = ConfigurationManager.AppSettings.Get("EncryptionKey");
                    var salt = ConfigurationManager.AppSettings.Get("Salt");

                    var cardNumber = _cryptographyService.Encrypt(creditCardNumber, key, salt); //encrypt the card info
                    //fine if the card is valid, but is the card number already in our record, then not possible to save the same again
                    if (_paymentMethodService.DoesCardNumberExist(cardNumber))
                    {
                        VerboseReporter.ReportError("The card number is already saved in records", "process_payment");
                        return(RespondFailure());
                    }

                    paymentMethod = new UserPaymentMethod()
                    {
                        UserId            = ApplicationContext.Current.CurrentUser.Id,
                        IsVerified        = false,
                        PaymentMethodType = PaymentMethodType.CreditCard,
                        CardIssuerType    = cardIssuer.ToString().ToLowerInvariant(),
                        CardNumber        = creditCardNumber,
                        CardNumberMasked  = PaymentCardHelper.MaskCardNumber(creditCardNumber),
                        NameOnCard        = nameOnCard,
                    };
                    //save this payment method
                    _paymentMethodService.Insert(paymentMethod);
                    #endregion
                }
            }


            //we need to see if we should only authorize or capture as well
            //the idea is if it's a sponsorship context, it's better to authorize the payment transaction and capture later when
            //the sponsorship is accepted //we thought of initially only authorizing sponsorship transactions and capture when it's accepted.
            //but that flow doesn't seem to work quite well, thoughts?
            var authorizeOnly = false; // (parameters.Get(PaymentParameterNames.PaymentContext) ?? string.Empty) == "sponsor";

            //so we are ready for payment processing, let's create a paymenttrasaction for storing in our db
            var paymentTransaction = new PaymentTransaction()
            {
                IsLocalTransaction = true,
                PaymentStatus      = PaymentStatus.Pending,
                TransactionAmount  = amount,
                TransactionGuid    = Guid.NewGuid(),
                CreatedOn          = DateTime.UtcNow,
                UserIpAddress      = WebHelper.GetClientIpAddress()
            };
            _paymentTransactionService.Insert(paymentTransaction);

            //now proceed further with the payment
            //create the transaction request
            var transactionRequest = new TransactionRequest()
            {
                Amount                     = amount,
                CurrencyIsoCode            = "USD",//TODO: SET CURRENCY AS SELECTED BY USER
                PaymentProcessorSystemName = paymentProcessor.PluginInfo.SystemName,
                UserId                     = ApplicationContext.Current.CurrentUser.Id,
                Parameters                 = formCollectionDictionary,
                TransactionUniqueId        = paymentTransaction.TransactionGuid.ToString()
            };


            var response = paymentProcessor.Process(transactionRequest, authorizeOnly);
            //update values of transaction parameters for future reference
            paymentTransaction.TransactionCodes = response.ResponseParameters;
            //update payment transaction
            _paymentTransactionService.Update(paymentTransaction);

            if (response.Success)
            {
                //let's verify the payment method first if it's not
                if (paymentMethod != null && !paymentMethod.IsVerified)
                {
                    paymentMethod.IsVerified = true;
                    _paymentMethodService.Update(paymentMethod);
                }

                //now since the response was success, we can actually assign some credits to the user
                var creditCount = amount * (1 / _paymentSettings.CreditExchangeRate);
                var credit      = new Credit()
                {
                    PaymentTransactionId = paymentTransaction.Id,
                    CreatedOnUtc         = DateTime.UtcNow,
                    CreditCount          = creditCount,
                    CreditExchangeRate   = _paymentSettings.CreditExchangeRate,
                    //if it's authorize only transaction, we assign the credits, but they won't be usable before they are approved by capture
                    CreditTransactionType = CreditTransactionType.Issued,
                    CreditType            = CreditType.Transactional,
                    IsExpired             = false
                };

                //save credit
                _creditService.Insert(credit);

                //get total available credits of user
                var usableCreditCount = _creditService.GetUsableCreditsCount(ApplicationContext.Current.CurrentUser.Id);
                return(RespondSuccess(new {
                    UsableCreditCount = usableCreditCount
                }));
            }
            VerboseReporter.ReportError("An error occured while processing payment", "process_payment");
            return(RespondFailure());
        }
        public IHttpActionResult Post(UserEntityModel entityModel)
        {
            User user;

            user = entityModel.Id == 0 ? new User() : _userService.Get(entityModel.Id);

            if (user == null)
            {
                return(NotFound());
            }

            //check if the email has already been registered
            var emailUser = _userService.Get(x => x.Email == entityModel.Email, earlyLoad: x => x.UserRoles.Select(y => y.Role)).FirstOrDefault();

            if (emailUser != null && emailUser.Id != user.Id)
            {
                VerboseReporter.ReportError("The email is already registered with another user", "post_user");
                return(RespondFailure());
            }

            //same for user name
            if (_userSettings.AreUserNamesEnabled)
            {
                var userNameUser = _userService.Get(x => x.UserName == entityModel.UserName, null).FirstOrDefault();
                if (userNameUser != null && userNameUser.Id != user.Id)
                {
                    VerboseReporter.ReportError("The username is already taken by another user", "post_user");
                    return(RespondFailure());
                }
            }

            //we should have at least one role
            if (entityModel.RoleIds.Count == 0)
            {
                VerboseReporter.ReportError("At least one role must be assigned to the user", "post_user");
                return(RespondFailure());
            }
            //is this a new user, we'll require password
            if (string.IsNullOrEmpty(entityModel.Password) && entityModel.Id == 0)
            {
                VerboseReporter.ReportError("You must specify the password for the user", "post_user");
                return(RespondFailure());
            }
            //are passwords same?
            if (!string.IsNullOrEmpty(entityModel.Password) && string.Compare(entityModel.Password, entityModel.ConfirmPassword, StringComparison.Ordinal) != 0)
            {
                VerboseReporter.ReportError("The passwords do not match", "post_user");
                return(RespondFailure());
            }

            user.FirstName   = entityModel.FirstName;
            user.LastName    = entityModel.LastName;
            user.Email       = entityModel.Email;
            user.Remarks     = entityModel.Remarks;
            user.Active      = entityModel.Active;
            user.DateUpdated = DateTime.UtcNow;
            user.Name        = string.Concat(user.FirstName, " ", user.LastName);
            user.UserName    = entityModel.UserName;

            if (!string.IsNullOrEmpty(entityModel.Password)) // update password if provided
            {
                if (string.IsNullOrEmpty(user.PasswordSalt))
                {
                    user.PasswordSalt = _cryptographyService.CreateSalt(8);
                }
                user.Password = _cryptographyService.GetHashedPassword(entityModel.Password, user.PasswordSalt,
                                                                       _securitySettings.DefaultPasswordStorageFormat);
            }

            _userService.Update(user);

            //assign the roles now
            var roles = _roleService.Get(x => x.IsActive);
            //current roles
            var currentRoleIds = user.UserRoles.Select(x => x.RoleId).ToList();
            //roles to unassign
            var rolesToUnassign = currentRoleIds.Except(entityModel.RoleIds);

            foreach (var roleId in rolesToUnassign)
            {
                var role = roles.FirstOrDefault(x => x.Id == roleId);
                if (role == null)
                {
                    continue;
                }

                _roleService.UnassignRoleToUser(role, user);
            }

            //roles to assign
            var rolesToAssign = entityModel.RoleIds.Except(currentRoleIds);

            foreach (var roleId in rolesToAssign)
            {
                var role = roles.FirstOrDefault(x => x.Id == roleId);
                if (role == null)
                {
                    continue;
                }

                _roleService.AssignRoleToUser(role, user);
            }

            //any images to assign
            if (entityModel.CoverImageId != 0)
            {
                user.SetPropertyValue(PropertyNames.DefaultCoverId, entityModel.CoverImageId);
            }
            if (entityModel.ProfileImageId != 0)
            {
                user.SetPropertyValue(PropertyNames.DefaultPictureId, entityModel.ProfileImageId);
            }

            VerboseReporter.ReportSuccess("User saved successfully", "post_user");
            return(RespondSuccess(new {
                User = user.ToEntityModel(_mediaService, _mediaSettings)
            }));
        }
Пример #15
0
        public IHttpActionResult Get(string settingType = "all")
        {
            GeneralSettings    generalSettings;
            MediaSettings      mediaSettings;
            UserSettings       userSettings;
            ThirdPartySettings thirdPartySettings;
            SecuritySettings   securitySettings;
            DateTimeSettings   dateTimeSettings;
            PaymentSettings    paymentSettings;
            BattleSettings     battleSettings;
            UrlSettings        urlSettings;

            switch (settingType)
            {
            case "general":
                generalSettings = _settingService.GetSettings <GeneralSettings>();
                return(RespondSuccess(new
                {
                    GeneralSettings = generalSettings.ToModel()
                }));

            case "media":
                mediaSettings = _settingService.GetSettings <MediaSettings>();
                return(RespondSuccess(new {
                    MediaSettings = mediaSettings.ToModel()
                }));

            case "user":
                userSettings = _settingService.GetSettings <UserSettings>();
                return(RespondSuccess(new {
                    UserSettings = userSettings.ToModel()
                }));

            case "security":
                securitySettings = _settingService.GetSettings <SecuritySettings>();
                return(RespondSuccess(new {
                    SecuritySettings = securitySettings.ToModel()
                }));

            case "battle":
                battleSettings = _settingService.GetSettings <BattleSettings>();
                return(RespondSuccess(new {
                    BattleSettings = battleSettings.ToModel()
                }));

            case "datetime":
                dateTimeSettings = _settingService.GetSettings <DateTimeSettings>();
                return(RespondSuccess(new {
                    DateTimeSettings = dateTimeSettings.ToModel()
                }));

            case "payment":
                paymentSettings = _settingService.GetSettings <PaymentSettings>();
                return(RespondSuccess(new {
                    PaymentSettings = paymentSettings.ToModel()
                }));

            case "thirdparty":
                thirdPartySettings = _settingService.GetSettings <ThirdPartySettings>();
                return(RespondSuccess(new {
                    ThirdPartySettings = thirdPartySettings.ToModel()
                }));

            case "url":
                urlSettings = _settingService.GetSettings <UrlSettings>();
                return(RespondSuccess(new {
                    UrlSettings = urlSettings.ToModel()
                }));

            case "all":
                generalSettings    = _settingService.GetSettings <GeneralSettings>();
                mediaSettings      = _settingService.GetSettings <MediaSettings>();
                userSettings       = _settingService.GetSettings <UserSettings>();
                securitySettings   = _settingService.GetSettings <SecuritySettings>();
                battleSettings     = _settingService.GetSettings <BattleSettings>();
                dateTimeSettings   = _settingService.GetSettings <DateTimeSettings>();
                paymentSettings    = _settingService.GetSettings <PaymentSettings>();
                thirdPartySettings = _settingService.GetSettings <ThirdPartySettings>();
                urlSettings        = _settingService.GetSettings <UrlSettings>();
                return(RespondSuccess(new
                {
                    GeneralSettings = generalSettings?.ToModel(),
                    MediaSettings = mediaSettings.ToModel(),
                    UserSettings = userSettings.ToModel(),
                    SecuritySettings = securitySettings.ToModel(),
                    BattleSettings = battleSettings.ToModel(),
                    DateTimeSettings = dateTimeSettings.ToModel(),
                    PaymentSettings = paymentSettings.ToModel(),
                    ThirdPartySettings = thirdPartySettings.ToModel(),
                    UrlSettings = urlSettings.ToModel()
                }));

            default:
                VerboseReporter.ReportError("Invalid type name", "get_setting");
                return(RespondFailure());
            }
        }
        public IHttpActionResult SaveArtist(ArtistPageModel model)
        {
            if (!ModelState.IsValid)
            {
                VerboseReporter.ReportError("Invalid data submitted. Please check all fields and try again.", "save_artist");
                return(RespondFailure());
            }

            if (!ApplicationContext.Current.CurrentUser.IsRegistered())
            {
                VerboseReporter.ReportError("Unauthorized access", "save_artist");
                return(RespondFailure());
            }

            //check to see if artist name already exists
            string artistJson;

            if (IsArtistPageNameAvailable(model.Name, out artistJson))
            {
                var artistPage = new ArtistPage()
                {
                    PageOwnerId      = ApplicationContext.Current.CurrentUser.Id,
                    Biography        = model.Description,
                    Name             = model.Name,
                    DateOfBirth      = model.DateOfBirth,
                    Gender           = model.Gender,
                    HomeTown         = model.HomeTown,
                    RemoteEntityId   = model.RemoteEntityId,
                    RemoteSourceName = model.RemoteSourceName,
                    ShortDescription = model.ShortDescription
                };

                _artistPageService.Insert(artistPage);

                if (artistJson != "")
                {
                    //we can now download the image from the server and store it on our own server
                    //use the json we retrieved earlier
                    var jObject = (JObject)JsonConvert.DeserializeObject(artistJson);

                    if (!string.IsNullOrEmpty(jObject["ImageUrl"].ToString()))
                    {
                        var imageUrl      = jObject["ImageUrl"].ToString();
                        var imageBytes    = HttpHelper.ExecuteGet(imageUrl);
                        var fileExtension = Path.GetExtension(imageUrl);
                        if (!string.IsNullOrEmpty(fileExtension))
                        {
                            fileExtension = fileExtension.ToLowerInvariant();
                        }

                        var contentType = PictureUtility.GetContentType(fileExtension);
                        var picture     = new Media()
                        {
                            Binary   = imageBytes,
                            Name     = model.Name,
                            MimeType = contentType
                        };
                        _pictureService.WritePictureBytes(picture, _mediaSettings.PictureSaveLocation);
                        //relate both page and picture
                        _pictureService.AttachMediaToEntity(artistPage, picture);
                    }
                }

                return(Response(new {
                    Success = true,
                    RedirectTo = Url.Route("ArtistPageUrl", new RouteValueDictionary()
                    {
                        { "SeName", artistPage.GetPermalink() }
                    })
                }));
            }
            else
            {
                return(Response(new {
                    Success = false,
                    Message = "DuplicateName"
                }));
            }
        }
        public IHttpActionResult SaveSponsor(SponsorModel requestModel)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { Success = false, Message = "Invalid Data" }));
            }

            var battle = _videoBattleService.Get(requestModel.BattleId); //todo: query picture battles when ready

            if (battle == null)
            {
                return(Json(new { Success = false, Message = "Invalid Battle" }));
            }

            var isProductOnlySponsorship = requestModel.SponsorshipType == SponsorshipType.OnlyProducts;

            var userId = ApplicationContext.Current.CurrentUser.Id;

            //there is a possibility that a sponsor is increasing the sponsorship amount. In that case, the new sponsorship status will automatically
            //be of same status as that of previous one for the same battle
            //lets find if the sponsor already exist for this battle?
            var existingSponsors = _sponsorService.GetSponsors(userId, requestModel.BattleId, requestModel.BattleType, null);

            var newSponsorStatus = SponsorshipStatus.Pending;

            //so is the current customer already an sponsor for this battle?
            if (existingSponsors.Any())
            {
                newSponsorStatus = existingSponsors.First().SponsorshipStatus;
            }

            if (!isProductOnlySponsorship)
            {
                //are issued credits sufficient?
                var issuedCreditsCount = _creditService.GetUsableCreditsCount(userId);
                if ((issuedCreditsCount < battle.MinimumSponsorshipAmount && newSponsorStatus != SponsorshipStatus.Accepted) || requestModel.SponsorshipCredits > issuedCreditsCount)
                {
                    VerboseReporter.ReportError("Insufficient credits to become sponsor", "save_sponsor");
                    return(RespondFailure());
                }
            }

            //mark the credits as spent credits
            var spentCredit = new Credit()
            {
                CreditContextKey      = string.Format(CreditContextKeyNames.BattleSponsor, battle.Id),
                CreditCount           = requestModel.SponsorshipCredits,
                CreditTransactionType = CreditTransactionType.Spent,
                CreditType            = CreditType.Transactional,
                PaymentTransactionId  = 0,
                CreatedOnUtc          = DateTime.UtcNow,
                UserId = userId
            };

            _creditService.Insert(spentCredit);

            //create the sponsor and set the status to pending or an existing status as determined above. (the status will be marked accepted or rejected or cancelled by battle owner)
            var sponsor = new Sponsor()
            {
                BattleId          = requestModel.BattleId,
                BattleType        = requestModel.BattleType,
                SponsorshipAmount = isProductOnlySponsorship ? 0 : requestModel.SponsorshipCredits,
                UserId            = userId,
                SponsorshipStatus = newSponsorStatus,
                DateCreated       = DateTime.UtcNow,
                DateUpdated       = DateTime.UtcNow
            };

            //save the sponsor
            _sponsorService.Insert(sponsor);

            if (!isProductOnlySponsorship)
            {
                //save the prizes only sponsorship prizes
                SaveSponsorProductPrizes(requestModel.Prizes);
            }


            var battleOwner = _userService.Get(battle.ChallengerId);

            var sponsorCustomer = _userService.Get(userId);

            //send notification to battle owner
            _emailSender.SendSponsorAppliedNotificationToBattleOwner(battleOwner, sponsorCustomer, battle);

            return(Json(new { Success = true }));
        }
        public IHttpActionResult UpdateSponsor(UpdateSponsorModel requestModel)
        {
            //here we update or reject the status of battle
            if (!ModelState.IsValid)
            {
                return(Json(new { Success = false, Message = "Invalid Data" }));
            }

            //because a sponsor may have performed multiple transactions for a battle, we'd update all of them at once

            //first get the battle
            //TODO: Remove comment when picture battles are ready
            var battle = _videoBattleService.Get(requestModel.BattleId); // Model.BattleType == BattleType.Video ? _videoBattleService.GetById(Model.BattleId) : null;

            //only battle owner should be able to accept or reject the sponsorship
            if (battle.ChallengerId != ApplicationContext.Current.CurrentUser.Id && requestModel.SponsorshipStatus != SponsorshipStatus.Cancelled)
            {
                return(Json(new { Success = false, Message = "Unauthorized" }));
            }

            //similarly only the sponsor should be able to withdraw it
            if (requestModel.SponsorCustomerId != ApplicationContext.Current.CurrentUser.Id && requestModel.SponsorshipStatus == SponsorshipStatus.Cancelled)
            {
                return(Json(new { Success = false, Message = "Unauthorized" }));
            }

            var sponsorCustomer = _userService.Get(requestModel.SponsorCustomerId);

            if (sponsorCustomer == null)
            {
                VerboseReporter.ReportError("Invalid customer Id", "update_sponsor");
                return(RespondFailure());
            }

            if (requestModel.SponsorshipStatus == SponsorshipStatus.Accepted)
            {
                //update sponsorship status
                _sponsorService.UpdateSponsorStatus(sponsorCustomer.Id, battle.Id, BattleType.Video, SponsorshipStatus.Accepted);
            }
            else if (requestModel.SponsorshipStatus == SponsorshipStatus.Cancelled || requestModel.SponsorshipStatus == SponsorshipStatus.Rejected)
            {
                //update sponsorship status
                _sponsorService.UpdateSponsorStatus(sponsorCustomer.Id, battle.Id, BattleType.Video, requestModel.SponsorshipStatus);

                //in case the sponsorship is cancelled or rejected, the appropriate number of credits should be refunded to the sponsor user
                //to get the total sponsorship credits, let's first query
                var sponsorships = _sponsorService.GetSponsors(sponsorCustomer.Id, battle.Id, BattleType.Video, null);
                //sum all the sponsorships to get total credits
                var totalCredits = sponsorships.Sum(x => x.SponsorshipAmount);

                var refundCredit = new Credit()
                {
                    CreatedOnUtc          = DateTime.UtcNow,
                    CreditTransactionType = CreditTransactionType.Refund,
                    CreditContextKey      = string.Format(CreditContextKeyNames.BattleSponsor, battle.Id),
                    CreditCount           = totalCredits,
                    CreditType            = CreditType.Transactional,
                    Remarks = $"Refund towards cancellation of sponsorship for video battle '{battle.Name}'",
                    UserId  = sponsorCustomer.Id
                };

                //save the credit
                _creditService.Insert(refundCredit);

                //send sponsorship update status to battle owner and admin
                var user = _userService.Get(requestModel.SponsorshipStatus == SponsorshipStatus.Cancelled ? battle.ChallengerId : requestModel.SponsorCustomerId);

                //send notification
                _emailSender.SendSponsorshipStatusChangeNotification(user, requestModel.SponsorshipStatus, battle);
            }
            return(RespondSuccess());
        }
        public IActionResult Put(NewsItemModel entityModel)
        {
            #region validate
            //if (!ModelState.IsValid)
            //    return BadRequest();
            if (entityModel == null)
            {
                VerboseReporter.ReportError("Dữ liệu không hợp lệ.");
                return(RespondFailure());
            }
            DateTime publishDt = entityModel.StartDateStr.ToDateTime();

            //get
            var article = _newsItemService.Get(entityModel.Id,
                                               x => x.NewsItemCategories,
                                               x => x.NewsItemTags);
            if (article == null)
            {
                VerboseReporter.ReportError("Không tìm thấy tin này", "post");
                return(RespondFailure());
            }
            #endregion

            #region NewsItem
            article.Name  = entityModel.Name;
            article.Short = entityModel.Short.GetSubString(ConstantKey.SummaryMaxLength);

            article.Full = HttpUtility.HtmlDecode(entityModel.Full);

            article.StartDateUtc = publishDt;
            article.EndDateUtc   = entityModel.EndDateUtc ?? publishDt.AddDays(7);
            article.DisplayOrder = entityModel.DisplayOrder;
            article.Published    = entityModel.Published;
            article.UpdatedOnUtc = DateTime.Now;
            article.Version      = article.Version + 1;

            article.MetaTitle       = entityModel.MetaTitle ?? article.Name;
            article.MetaDescription = entityModel.MetaDescription ?? article.Short;
            article.MetaKeywords    = entityModel.MetaKeywords ?? article.Name;
            //save it
            _newsItemService.Update(article);

            VerboseReporter.ReportSuccess("Sửa tin tức thành công", "put");
            #endregion


            #region newsCategory
            if (entityModel.newsCategoryIds != null && entityModel.newsCategoryIds.Length > 0)
            {
                foreach (int newsCategoryId in entityModel.newsCategoryIds)
                {
                    // tim chuyen muc
                    var foundNewsCategory = article.NewsItemCategories.FirstOrDefault(x => x.NewsCategoryId == newsCategoryId);
                    // neu khong tim thay chuyen muc trong bang quan he thi them moi
                    if (foundNewsCategory == null)
                    {
                        NewsItemCategory newsItemCategory = new NewsItemCategory()
                        {
                            NewsItemId     = article.Id,
                            NewsCategoryId = newsCategoryId,
                        };
                        _newsPubsService.Insert(newsItemCategory);
                    }
                    //    foreach (var newsPub in article.NewsPubs)
                    //    {
                    //        if (Array.IndexOf(entityModel.newsCategoryIds, newsPub.cat_id) == -1)
                    //        {
                    //            NewsPubs newsPubs = new NewsPubs()
                    //            {
                    //                article_id = article.id,
                    //                cat_id = newsCategoryId,
                    //            };
                    //            if (article.news_status != (int) NewsItemStatus.Unpublish)
                    //            {
                    //                newsPubs.approve_date = DateTime.Now;
                    //                newsPubs.approver = CurrentUser.full_name;
                    //            }
                    //            article.NewsPubs.Add(newsPubs);
                    //        }
                    //    }
                }
                //_NewsItemService.Update(article);
                // find list newsPubs by article_id
                var newsItemCategories = _newsPubsService.Get(x => x.NewsCategoryId == entityModel.Id).ToList();
                foreach (var newsItemCategory in newsItemCategories)
                {
                    // tim chuyen muc
                    var foundNewsCategory = entityModel.newsCategoryIds.FirstOrDefault(x => x == newsItemCategory.NewsCategoryId);
                    // neu khong tim thay chuyen muc trong mang danh muc gui len thi xoa di
                    if (foundNewsCategory == 0)
                    {
                        _newsPubsService.Delete(newsItemCategory);
                    }
                }
            }
            #endregion

            #region TagIds

            if (entityModel.TagIds != null && entityModel.TagIds.Length > 0)
            {
                foreach (var entityModelTagId in entityModel.TagIds)
                {
                    var foundNewsItemTag =
                        article.NewsItemTags.FirstOrDefault(x => x.TagId == entityModelTagId);
                    if (foundNewsItemTag == null)
                    {
                        NewsItemTag tag = new NewsItemTag()
                        {
                            TagId      = entityModelTagId,
                            NewsItemId = article.Id
                        };
                        _newsItemTagService.Insert(tag);
                    }
                }

                var newsItemTags = _newsItemTagService.Get(x => x.NewsItemId == entityModel.Id).ToList();
                foreach (var newsItemTag in newsItemTags)
                {
                    var foundNewsItemTag = entityModel.TagIds.FirstOrDefault(x => x == newsItemTag.TagId);
                    if (foundNewsItemTag == 0)
                    {
                        _newsItemTagService.Delete(newsItemTag);
                    }
                }
            }
            else
            {
                var newsItemTags = _newsItemTagService.Get(x => x.NewsItemId == entityModel.Id).ToList();
                foreach (var newsItemTag in newsItemTags)
                {
                    _newsItemTagService.Delete(newsItemTag);
                }
            }

            #endregion

            #region SaveLocalizedValue
            UpdateLocales(article, entityModel);
            #endregion

            return(RespondSuccess(article));
        }
        public IActionResult Post(NewsItemModel entityModel)
        {
            //if (!ModelState.IsValid)
            //    return BadRequest();
            if (entityModel == null)
            {
                VerboseReporter.ReportError("Dữ liệu không hợp lệ.");
                return(RespondFailure());
            }
            DateTime publishDt = entityModel.StartDateStr.ToDateTime();

            #region save NewsItem
            var article = new NewsItem
            {
                Name      = entityModel.Name,
                Short     = entityModel.Short.GetSubString(ConstantKey.SummaryMaxLength),
                Full      = HttpUtility.HtmlDecode(entityModel.Full),
                Published = entityModel.Published,

                CreatedOnUtc = publishDt, // DateTime.Now,

                StartDateUtc = publishDt,
                EndDateUtc   = entityModel.EndDateUtc,

                MetaTitle    = entityModel.MetaTitle ?? entityModel.Name,
                MetaKeywords = entityModel.MetaKeywords ?? entityModel.Name,
            };

            article.MetaDescription = entityModel.MetaDescription ?? article.Short;

            //save it
            _newsItemService.Insert(article);

            VerboseReporter.ReportSuccess("Tạo tin tức thành công", "post");
            #endregion

            #region newsCategoryIds
            if (entityModel.newsCategoryIds != null && entityModel.newsCategoryIds.Length > 0)
            {
                article.NewsItemCategories = new List <NewsItemCategory>();

                foreach (int newsCategoryId in entityModel.newsCategoryIds)
                {
                    NewsItemCategory newsPubs = new NewsItemCategory()
                    {
                        NewsItemId     = article.Id,
                        NewsCategoryId = newsCategoryId,
                    };
                    article.NewsItemCategories.Add(newsPubs);
                }
                _newsItemService.Update(article);
            }
            #endregion

            #region TagIds

            if (entityModel.TagIds != null && entityModel.TagIds.Length > 0)
            {
                article.NewsItemTags = new List <NewsItemTag>();
                foreach (var entityModelTagId in entityModel.TagIds)
                {
                    NewsItemTag newsItemTag = new NewsItemTag()
                    {
                        NewsItemId = article.Id,
                        TagId      = entityModelTagId
                    };
                    article.NewsItemTags.Add(newsItemTag);
                }
                _newsItemService.Update(article);
            }

            #endregion


            InsertLocales(article, entityModel);


            return(RespondSuccess(article));
        }
Пример #21
0
        public IActionResult UploadPictures()
        {
            var httpPostedFiles = Request.Form.Files;

            if (httpPostedFiles.Count == 0)
            {
                VerboseReporter.ReportError("No file uploaded", "upload_pictures");
                return(RespondFailure());
            }


            var newImages = new List <object>();

            for (var index = 0; index < httpPostedFiles.Count; index++)
            {
                //the file
                var file = httpPostedFiles[index];

                //and it's name
                //var fileName = file.FileName;

                var httpPostedFile = httpPostedFiles.FirstOrDefault();

                if (httpPostedFile == null)
                {
                    return(Json(new
                    {
                        success = false,
                        message = "No file uploaded",
                        downloadGuid = Guid.Empty
                    }));
                }

                var fileBinary = _downloadService.GetDownloadBits(httpPostedFile);

                const string qqFileNameParameter = "qqfilename";
                var          fileName            = httpPostedFile.FileName;
                if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter))
                {
                    fileName = Request.Form[qqFileNameParameter].ToString();
                }
                //remove path (passed in IE)
                fileName = _fileProvider.GetFileName(fileName);

                var contentType = httpPostedFile.ContentType;

                var fileExtension = _fileProvider.GetFileExtension(fileName);
                if (!string.IsNullOrEmpty(fileExtension))
                {
                    fileExtension = fileExtension.ToLowerInvariant();
                }

                //stream to read the bytes
                //var stream = file.InputStream;
                //var pictureBytes = new byte[stream.Length];
                //stream.Read(pictureBytes, 0, pictureBytes.Length);



                if (string.IsNullOrEmpty(contentType))
                {
                    contentType = PictureUtility.GetContentType(fileExtension);
                }

                var media = new Media()
                {
                    Binary      = fileBinary,
                    MimeType    = contentType,
                    Name        = fileName,
                    UserId      = CurrentUser.Id,
                    DateCreated = DateTime.UtcNow,
                    MediaType   = MediaType.Image
                };

                _mediaService.WritePictureBytes(media, _generalSettings, _mediaSettings);
                //save it
                _mediaService.Insert(media);
                //newImages.Add(picture.ToModel(_mediaService, _mediaSettings));

                newImages.Add(media);
            }

            return(RespondSuccess(new { Images = newImages }));
        }