Esempio n. 1
0
        public async Task <ActionResult> updateavator()
        {
            var json  = new StreamReader(Request.Body).ReadToEnd();
            var model = JsonConvert.DeserializeObject <ApplicationUser>(json);

            if (model.Id == "")
            {
                return(Ok(new { status = "error", message = SiteConfig.generalLocalizer["_no_records"].Value }));
            }

            byte[] image         = Convert.FromBase64String(model.picturename.Replace("data:image/png;base64,", ""));
            string thumbFileName = model.Id.ToString() + ".png";

            // if cloud enabled
            try
            {
                var path = SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, model.Id.ToString());
                if (!Directory.Exists(path))
                {
                    Directory_Process.CreateRequiredDirectories(path);
                }

                var filepath = path + "/" + thumbFileName;
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                }

                // local storage
                System.IO.File.WriteAllBytes(filepath, image);

                model.picturename = await Jugnoon.Helper.Aws.UploadPhoto(_context, thumbFileName, path, Configs.AwsSettings.user_photos_directory);

                // cleanup from local if cloud enabled and saved
                if (model.picturename.Contains("http"))
                {
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLgBLL.Add(_context, "Error: User Picture Failed to Upload", "", ex.Message);
                model.picturename = "";
            }

            UserBLL.Update_Field_Id(_context, model.Id, "picturename", model.picturename);
            model.img_url = UserUrlConfig.ProfilePhoto(model.Id, model.picturename, 0);

            return(Ok(new { status = "success", record = model, message = SiteConfig.generalLocalizer["_record_updated"].Value }));
        }
Esempio n. 2
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
        {
            ViewData["Page"] = "external-login-confirmation";
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    throw new ApplicationException(SiteConfig.generalLocalizer["_error_external_login_information"].Value);
                }
                var user = new ApplicationUser
                {
                    UserName   = model.UserName,
                    Email      = model.Email,
                    created_at = DateTime.Now,
                    isenabled  = 1
                };
                var result = await SiteConfig.userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    // Init User Profile
                    await UserProfileBLL.InitializeUserProfile(_context, user);

                    // Create Required Directories
                    Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, user.Id.ToString()));

                    result = await SiteConfig.userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View("~/Views/Home/index.cshtml", model));
        }
        /// <summary>
        /// Create Default Users
        /// </summary>
        /// <param name="_context"></param>
        public static async Task CreateUser(ApplicationDbContext _context, ApplicationUser user, string password, string roleName, short controlPanel_RoleID)
        {
            var admin_result = await SiteConfig.userManager.CreateAsync(user, password);

            if (admin_result.Succeeded)
            {
                await SiteConfig.userManager.AddToRoleAsync(user, roleName);

                // Init User Profile
                await UserProfileBLL.InitializeUserProfile(_context, user);

                Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, user.Id.ToString()));

                // enable account directly
                await UserBLL.Update_Field_IdAsync(_context, user.Id, "EmailConfirmed", true);

                // update controlpanel role
                await UserBLL.Update_Field_IdAsync(_context, user.Id, "roleid", controlPanel_RoleID);
            }
        }
Esempio n. 4
0
        public async Task <IActionResult> register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["Page"] = "signup";
            if (Configs.RegistrationSettings.uniqueFieldOption == 1)
            {
                ModelState.Remove("UserName");
            }
            if (ModelState.IsValid)
            {
                // Rechapcha Validation
                if (Configs.RegistrationSettings.enableChapcha)
                {
                    var recaptcha = await _recaptcha.Validate(Request);

                    if (!recaptcha.success)
                    {
                        ModelState.AddModelError("Recaptcha", SiteConfig.generalLocalizer["_invalid_chapcha"].Value);
                        return(View("~/Views/Home/index.cshtml", model));
                    }
                }


                if (Configs.RegistrationSettings.enablePrivacyCheck)
                {
                    if (!model.Agreement)
                    {
                        ModelState.AddModelError(string.Empty, SiteConfig.generalLocalizer["_accept_aggrement"].Value);
                        return(View("~/Views/Home/index.cshtml", model));
                    }
                }

                var UserName = model.UserName;
                if (Configs.RegistrationSettings.uniqueFieldOption == 1)
                {
                    UserName = model.Email;
                }

                var user = new ApplicationUser
                {
                    UserName   = UserName,
                    Email      = model.Email,
                    created_at = DateTime.Now,
                    firstname  = model.FirstName,
                    lastname   = model.LastName,
                    isenabled  = 1,
                    type       = (byte)UserBLL.Types.NormalUser
                };
                var result = await SiteConfig.userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Init User Profile
                    await UserProfileBLL.InitializeUserProfile(_context, user);

                    // Create Required Directories
                    Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, user.Id.ToString()));

                    var code = await SiteConfig.userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);

                    await _emailSender.SendEmailConfirmationAsync(_context, model.Email, UserName, callbackUrl, model.Password);

                    await _emailSender.SendEmailNotificationAsync(_context, model.Email, UserName);

                    var redirect_url = "/activate";
                    if (returnUrl != null && returnUrl != "")
                    {
                        redirect_url = returnUrl;
                    }
                    return(Redirect(redirect_url));
                }
                AddErrors(result);
            }

            return(View("~/Views/Home/index.cshtml", model));
        }
Esempio n. 5
0
        public async Task <IActionResult> login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            ViewData["Page"]      = "signin";
            if (Configs.RegistrationSettings.enableChapcha)
            {
                var recaptcha = await _recaptcha.Validate(Request);

                if (!recaptcha.success)
                {
                    ModelState.AddModelError("Recaptcha", "Invalid Chapcha. Please try again!");
                    return(View("~/Views/Home/index.cshtml", model));
                }
            }
            if (ModelState.IsValid)
            {
                // IP Address tracking and processing
                string ipaddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                if (BlockIPBLL.Validate(_context, ipaddress))
                {
                    model.Message = SiteConfig.generalLocalizer["_ip_blocked"].Value;
                    return(View("~/Views/Home/index.cshtml", model));
                }

                ApplicationUser user;
                if (model.Email.Contains("@"))
                {
                    user = await SiteConfig.userManager.FindByEmailAsync(model.Email);

                    if (user == null)
                    {
                        ModelState.AddModelError(string.Empty, SiteConfig.generalLocalizer["_invalid_login_attempt"].Value);
                        return(View("~/Views/Home/index.cshtml", model));
                    }
                    else
                    {
                        if (user.isenabled == 0)
                        {
                            // user account is suspeneded
                            ModelState.AddModelError(string.Empty, SiteConfig.generalLocalizer["_account_suspended"].Value);
                            return(View("~/Views/Home/index.cshtml", model));
                        }
                        model.Email = user.UserName;
                    }
                }
                else
                {
                    user = await SiteConfig.userManager.FindByNameAsync(model.Email);

                    if (user != null)
                    {
                        if (user.isenabled == 0)
                        {
                            // user account is suspeneded
                            ModelState.AddModelError(string.Empty, SiteConfig.generalLocalizer["_account_suspended"].Value);
                            return(View("~/Views/Home/index.cshtml", model));
                        }
                    }
                }

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

                if (result.Succeeded)
                {
                    // Store IP Address Log
                    if (Configs.GeneralSettings.store_ipaddress)
                    {
                        UserLogBLL.Add(_context, user.Id, SiteConfig.HttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
                    }


                    // Update Last Login Activity
                    UserBLL.Update_Field_Email(_context, model.Email, "last_login", DateTime.Now);

                    // Create User Directory for Media Storage
                    var dirPath = SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, model.Email.ToLower().ToString());
                    if (!System.IO.Directory.Exists(dirPath))
                    {
                        Directory_Process.CreateRequiredDirectories(dirPath);
                    }

                    if (returnUrl == null || returnUrl == "")
                    {
                        returnUrl = "/account/";
                    }
                    return(Redirect(returnUrl)); // LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    ViewData["Page"] = "lockout";
                    return(RedirectToAction(nameof(HomeController.Index), "Home"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, SiteConfig.generalLocalizer["_invalid_login_attempt"].Value);
                    return(View("~/Views/Home/index.cshtml", model));
                }
            }

            return(View(model));
        }
        public async Task <IActionResult> upload()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            StringValues UserName;

            SiteConfig.HttpContextAccessor.HttpContext.Request.Headers.TryGetValue("UName", out UserName);

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var formAccumulator = new KeyValueAccumulator();
            // string targetFilePath = null;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);

            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            var uploadPath = SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(DirectoryPaths.UserVideosDefaultDirectoryPath, UserName.ToString());

            if (!Directory.Exists(uploadPath))
            {
                Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, UserName.ToString()));
            }

            /*if (!Directory.Exists(uploadPath))
             * {
             *  return Ok(new { jsonrpc = "2.0", result = "Error", fname = uploadPath, message = "Main Directory Not Exist" });
             * }
             *
             * if (!Directory.Exists(uploadPath + "default/"))
             * {
             *  return Ok(new { jsonrpc = "2.0", result = "Error", fname = uploadPath + "default/", message = "Default Directory Not Exist" });
             * }*/

            var fileName = "";

            try
            {
                while (section != null)
                {
                    ContentDispositionHeaderValue contentDisposition;
                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
                                                                                             out contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {
                            var output = formAccumulator.GetResults();
                            var chunk  = "0";
                            foreach (var item in output)
                            {
                                if (item.Key == "name")
                                {
                                    fileName = item.Value;
                                }
                                else if (item.Key == "chunk")
                                {
                                    chunk = item.Value;
                                }
                            }

                            var Path = uploadPath + "" + fileName;
                            using (var fs = new FileStream(Path, chunk == "0" ? FileMode.Create : FileMode.Append))
                            {
                                await section.Body.CopyToAsync(fs);

                                fs.Flush();
                            }
                        }
                        else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            var encoding = GetEncoding(section);
                            using (var streamReader = new StreamReader(
                                       section.Body,
                                       encoding,
                                       detectEncodingFromByteOrderMarks: true,
                                       bufferSize: 1024,
                                       leaveOpen: true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await streamReader.ReadToEndAsync();

                                if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                {
                                    value = String.Empty;
                                }
                                formAccumulator.Append(key.ToString(), value);

                                if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                                {
                                    throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                                }
                            }
                        }
                    }

                    var result = formAccumulator.GetResults();

                    // Drains any remaining section body that has not been consumed and
                    // reads the headers for the next section.
                    section = await reader.ReadNextSectionAsync();
                }
            }
            catch (Exception ex)
            {
                return(Ok(new { jsonrpc = "2.0", result = "Error", fname = uploadPath, message = ex.Message }));
            }


            string url       = VideoUrlConfig.Source_Video_Url(UserName.ToString()) + "/" + fileName;
            string fileType  = System.IO.Path.GetExtension(fileName);
            string fileIndex = fileName.Replace(fileType, "");

            return(Ok(new { jsonrpc = "2.0", result = "OK", fname = fileName, url = url, filetype = fileType, filename = fileName, fileIndex = fileIndex }));
        }
Esempio n. 7
0
        public async Task <ActionResult> proc()
        {
            var json = new StreamReader(Request.Body).ReadToEnd();
            var data = JsonConvert.DeserializeObject <ApplicationUser>(json);

            if (data.Id != null && data.Id != "")
            {
                // Update Profile
                var record = await UserBLL.Update_User_Profile(_context, data, data.isadmin);

                /* attribute processing */
                foreach (var attr in data.attr_values)
                {
                    attr.userid    = data.Id;
                    attr.attr_type = (byte)Attr_Type.UserProfile;
                    if (attr.id > 0)
                    {
                        /* update record */
                        await AttrValueBLL.Update(_context, attr);
                    }
                    else
                    {
                        /* add attribute */
                        if (attr.value != "")
                        {
                            await AttrValueBLL.Add(_context, attr);
                        }
                    }
                }

                record.img_url = UserUrlConfig.ProfilePhoto(record.UserName, record.picturename, 0);
                return(Ok(new { status = "success", record = record, message = SiteConfig.generalLocalizer["_record_updated"].Value }));
            }
            else
            {
                // Create New Account
                var user = new ApplicationUser
                {
                    UserName   = data.UserName,
                    Email      = data.Email,
                    created_at = DateTime.Now,
                    isenabled  = 1, // internal use only (to suspend user account and all posted data at once)
                    firstname  = data.firstname,
                    lastname   = data.lastname
                };

                var result = await SiteConfig.userManager.CreateAsync(user, data.password);

                if (result.Succeeded)
                {
                    // role process
                    if (data.role_name != null && data.role_name != "")
                    {
                        var roleExist = await SiteConfig.roleManager.RoleExistsAsync(data.role_name);

                        if (!roleExist)
                        {
                            ApplicationRole role = new ApplicationRole();
                            role.Name        = data.role_name;
                            role.CreatedDate = DateTime.Now;
                            await SiteConfig.roleManager.CreateAsync(role);
                        }

                        await SiteConfig.userManager.AddToRoleAsync(user, data.role_name);
                    }

                    // Init User Profile
                    await UserProfileBLL.InitializeUserProfile(_context, user);

                    Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, user.Id.ToString()));

                    // enable account directly
                    UserBLL.Update_Field_Id(_context, user.Id, "EmailConfirmed", true);

                    // setup url / picture url for app use only
                    data.Id             = user.Id;
                    data.picturename    = "none";
                    data.LockoutEnabled = false;
                    data.EmailConfirmed = true;
                    data.img_url        = UserUrlConfig.ProfilePhoto(data.UserName, data.picturename, 0); // default set
                    data.url            = UserUrlConfig.ProfileUrl(data, Configs.RegistrationSettings.uniqueFieldOption);

                    return(Ok(new { status = "success", record = data, message = SiteConfig.generalLocalizer["_account_created"].Value }));
                }
                else
                {
                    return(Ok(new { status = "error", record = data, message = SiteConfig.generalLocalizer["_account_failed"].Value }));
                }
            }
        }
Esempio n. 8
0
    protected void btn_register_Click1(object sender, EventArgs e)
    {
        if (!chk_agree.Checked)
        {
            Config.ShowMessageV2(msg, Resources.vsk.message_reg_01, "Error!", 0); // "Accept terms of use &amp; privacy policy before continue."
            return;
        }
        // birth date processing
        //string _birth_date = drp_birthday_month.SelectedValue + "/" + drp_birthday_day.SelectedValue + "/" + drp_year.SelectedValue;
        //DateTime birth_day = Convert.ToDateTime(_birth_date);
        //int date_diff = DateTime.Now.Year - birth_day.Year;
        //if (date_diff < 10)
        //{
        //    Config.ShowMessage(msg, Resources.vsk.message_reg_02, 0, 0); // Age must be greater than 10 years before registering on this website.
        //    return;
        //}
        // check for restricted usernames
        string res_values = DictionaryBLL.Return_RestrictedUserNames();

        if (res_values != "")
        {
            if (DictionaryBLL.isMatch(lUserName.Text, res_values))
            {
                Config.ShowMessageV2(msg, Resources.vsk.message_reg_03, "Error!", 0); // User name not available, please choose another one.
                return;
            }
        }

        // IP Address tracking and processing
        string ipaddress = Request.ServerVariables["REMOTE_ADDR"].ToString();

        if (BlockIPBLL.Validate_IP(ipaddress))
        {
            Response.Redirect(Config.GetUrl("IPBlocked.aspx"));
            return;
        }


        if (_memberprocess.Check_UserName(lUserName.Text))
        {
            Config.ShowMessageV2(msg, Resources.vsk.message_reg_03, "Error!", 0); // User name not available, please choose another one.
            return;
        }
        if (_memberprocess.Check_Email(Email.Text))
        {
            Config.ShowMessageV2(msg, Resources.vsk.message_reg_04, "Error!", 0); // "Email address is already exist."
            return;
        }

        string gender = "Male";

        if (r_female.Checked)
        {
            gender = "Female";
        }

        // validation key processing
        string val_key   = "none";
        int    isenabled = 1; // user account activated

        if (Config.isRegistrationValidation() && !this.isAdmin)
        {
            val_key   = Guid.NewGuid().ToString().Substring(0, 10);
            isenabled = 0; // user account deactivated
        }
        // Add Member
        int type = 0; // normal member

        if (this.isAdmin)
        {
            type = Convert.ToInt32(drp_acc.SelectedValue);
        }

        int userrole_id = 0;

        // encrypt password
        //int BCRYPT_WORK_FACTOR = 10;
        string encrypted_password = BCrypt.Net.BCrypt.HashPassword(lPassword.Text);

        members.Add(0, lUserName.Text, encrypted_password, Email.Text, drp_country.SelectedValue.ToString(), isenabled, gender, DateTime.Now, val_key, type, userrole_id);
        // Create Required Directories
        Directory_Process.CreateRequiredDirectories(Server.MapPath(Request.ApplicationPath) + "/contents/member/" + lUserName.Text.ToLower());

        if (this.isAdmin)
        {
            Response.Redirect(Config.GetUrl("adm/sc/members/Default.aspx?status=created"));
        }
        else
        {
            // Send Mail
            MailTemplateProcess(Email.Text, lUserName.Text, lPassword.Text, val_key);

            if (Config.isRegistrationValidation())
            {
                Response.Redirect("Validate.aspx?user="******"");
            }
            else
            {
                // authorize user
                FormsAuthentication.SetAuthCookie(lUserName.Text, false);
                // Store IP Address Log
                User_IPLogBLL.Process_Ipaddress_Log(lUserName.Text, ipaddress);
                if (Config.GetMembershipAccountUpgradeRedirect() == 1)
                {
                    Response.Redirect("myaccount/Packages.aspx?status=success");
                }
                else
                {
                    Response.Redirect("myaccount/Default.aspx?status=success");
                }
            }
        }
    }
        public void ProcessRequest(HttpContext context)
        {
            var json        = new StreamReader(context.Request.InputStream).ReadToEnd();
            var responseMsg = new Dictionary <string, string>();

            int    Type     = 0;
            string UserName = "";
            string Email    = "";
            int    Status   = 0;

            int    OldValue       = 0;
            int    NewValue       = 0;
            string Value          = "";
            string FieldName      = "";
            int    Records        = 0;
            string Key            = "";
            bool   isAdmin        = false;
            var    _mem           = new members();
            var    _ld_video_data = new Dictionary <string, MembersObject>();

            if ((context.Request.Params["action"] != null))
            {
                switch (context.Request.Params["action"])
                {
                // url/api/members/process.ashx?action=login
                // data
                case "login":
                    var _login_member = JsonConvert.DeserializeObject <Member_Struct>(json);
                    // validate member
                    // Update Password Validation Script
                    if (_login_member.UserName == "" || _login_member.Password == "")
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Please enter username and password";
                        context.Response.Write(responseMsg);
                        return;
                    }

                    int MemberType            = 0;
                    int Readonly              = 0;
                    List <Member_Struct> _lst = members.Get_Hash_Password(_login_member.UserName);
                    if (_lst.Count == 0)
                    {
                        // No user account found based on username search
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = Resources.vsk.message_06;
                        context.Response.Write(responseMsg);
                        return;
                    }

                    // check encrypted password
                    if (_lst[0].Password.Length < 20)
                    {
                        // backward compatibility
                        // check existing user passwords with old system
                        if (!_mem.Validate_Member(_login_member.UserName, _login_member.Password, false))
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_06;
                            context.Response.Write(responseMsg);
                            return;
                        }
                        MemberType = Convert.ToInt32(members.Return_Value(_login_member.UserName, "type"));
                        Readonly   = Convert.ToInt32(members.Return_Value(_login_member.Password, "readonly"));
                    }
                    else
                    {
                        // check encrypted password with user typed password
                        bool matched = BCrypt.Net.BCrypt.Verify(_login_member.Password, _lst[0].Password);
                        if (!matched)
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_06;
                            context.Response.Write(responseMsg);
                            return;
                        }
                        MemberType = _lst[0].Type;     // type
                        Readonly   = _lst[0].ReadOnly;
                    }

                    string Role = "User";
                    switch (MemberType)
                    {
                    case 0:
                        Role = "User";
                        break;

                    case 1:
                        Role = "Admin";
                        break;

                    case 2:
                        Role = "PaidUser";
                        break;
                    }

                    if (MemberType == 1)
                    {
                        if (Readonly == 1)
                        {
                            Role = "ReadOnlyAdmin";
                        }
                    }
                    // IP Address tracking and processing
                    string ipaddress = context.Request.ServerVariables["REMOTE_ADDR"].ToString();
                    if (BlockIPBLL.Validate_IP(ipaddress))
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "IP Blocked";
                        context.Response.Write(responseMsg);
                        return;
                    }

                    if (Site_Settings.Store_IPAddress)
                    {
                        // Store IP Address Log
                        User_IPLogBLL.Process_Ipaddress_Log(_login_member.UserName, ipaddress);
                    }

                    // Update Last Login Activity of User
                    members.Update_Value(_login_member.UserName, "last_login", DateTime.Now);
                    // member is validated
                    FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(1, _login_member.UserName, DateTime.Now, DateTime.Now.AddMonths(1), true, Role, FormsAuthentication.FormsCookiePath);
                    string     encTicket = FormsAuthentication.Encrypt(_ticket);
                    HttpCookie _cookie   = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    //  if (chk_remember.Checked)
                    //    _cookie.Expires = DateTime.Now.AddMonths(1);
                    // Response.Cookies.Add(_cookie);

                    // check for membership upgrades

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Login Successfull";
                    responseMsg["role"]    = Role;

                    context.Response.Write(responseMsg);
                    return;

                // url/api/members/process.ashx?action=register
                // data
                case "register":
                    var _register_member = JsonConvert.DeserializeObject <Member_Struct>(json);

                    string res_values = DictionaryBLL.Return_RestrictedUserNames();
                    if (res_values != "")
                    {
                        if (DictionaryBLL.isMatch(_register_member.UserName, res_values))
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_reg_03;
                            context.Response.Write(responseMsg);

                            return;
                        }
                    }

                    // IP Address tracking and processing
                    string ip = context.Request.ServerVariables["REMOTE_ADDR"].ToString();
                    if (BlockIPBLL.Validate_IP(ip))
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "IP Blocked";
                        context.Response.Write(responseMsg);
                        return;
                    }


                    if (_mem.Check_UserName(_register_member.UserName))
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = Resources.vsk.message_reg_03;
                        context.Response.Write(responseMsg);
                        return;
                    }
                    if (_mem.Check_Email(_register_member.Email))
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = Resources.vsk.message_reg_04;
                        context.Response.Write(responseMsg);

                        return;
                    }

                    // validation key processing
                    string val_key   = "none";
                    int    isenabled = 1;  // user account activated
                    if (Config.isRegistrationValidation())
                    {
                        val_key   = Guid.NewGuid().ToString().Substring(0, 10);
                        isenabled = 0;     // user account deactivated
                    }
                    // Add Member
                    int type = 0;     // normal member

                    // Credits and Default Space Allocation
                    int    credits          = 0;
                    int    remained_video   = 0;
                    int    remained_audio   = 0;
                    int    remained_gallery = 0;
                    int    remained_photos  = 0;
                    int    remained_blogs   = 0;
                    double space_video      = 0;
                    double space_audio      = 0;
                    double space_photos     = 0;

                    if (Config.GetMembershipAccountUpgradeType() == 0)
                    {
                        if (!User_PackagesBLL.Check_Package_Feature())
                        {
                            // free user have some restricted features and services.
                            // load default free user package settings
                            List <Package_Struct> pck = PackagesBLL.Fetch_Record(Site_Settings.General_Default_Package_ID, false);
                            if (pck.Count > 0)
                            {
                                credits          = pck[0].Credits;
                                remained_video   = pck[0].Num_Videos;
                                remained_audio   = pck[0].Num_Audio;
                                remained_gallery = pck[0].Num_Galleries;
                                remained_photos  = pck[0].Num_Photos;
                                remained_blogs   = pck[0].Num_Blogs;
                                space_audio      = pck[0].Space_Audio;
                                space_video      = pck[0].Space_Video;
                                space_photos     = pck[0].Space_Photo;
                            }
                            else
                            {
                                // default package info not found, either package not exist or package is disabled currently.
                                // in this case users records updated with 0 status.
                            }
                        }
                    }
                    int userrole_id = Site_Settings.Default_UserRoleID;     // assign user default role at time of register

                    // encrypt password
                    //int BCRYPT_WORK_FACTOR = 10;
                    string encrypted_password = BCrypt.Net.BCrypt.HashPassword(_register_member.Password);
                    int    atype = 0;
                    members.Add(atype, _register_member.UserName, encrypted_password, _register_member.Email, _register_member.CountryName, isenabled, _register_member.Gender, DateTime.Now, val_key, type, credits, remained_video, remained_audio, remained_gallery, remained_photos, remained_blogs, space_video, space_audio, space_photos, userrole_id);
                    // Create Required Directories
                    Directory_Process.CreateRequiredDirectories(context.Server.MapPath(context.Request.ApplicationPath) + "/contents/member/" + _register_member.UserName.ToLower());

                    // Send Mail
                    MailTemplateProcess_Register(_register_member.Email, _register_member.UserName, _register_member.Password, val_key);

                    if (Config.isRegistrationValidation())
                    {
                        responseMsg["status"]  = "pending";
                        responseMsg["message"] = "Validation Required";
                        context.Response.Write(responseMsg);
                        return;
                    }
                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Registeration Completed";
                    context.Response.Write(responseMsg);
                    break;

                case "update_profile":
                    // Authentication
                    if (!context.User.Identity.IsAuthenticated)
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Authentication Failed";
                        context.Response.Write(responseMsg);
                        return;
                    }
                    var _upd_mem = JsonConvert.DeserializeObject <Member_Struct>(json);
                    members.Update_User_Profile(_upd_mem.UserName, _upd_mem.FirstName, _upd_mem.LastName, _upd_mem.CountryName, _upd_mem.Gender, _upd_mem.RelationshipStatus, _upd_mem.AboutMe, _upd_mem.Website, _upd_mem.HometTown, _upd_mem.CurrentCity, _upd_mem.Zipcode, _upd_mem.Occupations, _upd_mem.Companies, _upd_mem.Schools, _upd_mem.Interests, _upd_mem.Movies, _upd_mem.Musics, _upd_mem.Books, _upd_mem.isAllowBirthDay);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);
                    break;

                case "email_options":
                    // Authentication
                    if (!context.User.Identity.IsAuthenticated)
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Authentication Failed";
                        context.Response.Write(responseMsg);
                        return;
                    }

                    var _email_options = JsonConvert.DeserializeObject <Member_Struct>(json);

                    // validate email address and password.
                    var options = members.Get_Hash_Password(_email_options.UserName);
                    if (options.Count == 0)
                    {
                        // No user account found based on username search
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = Resources.vsk.message_emailoptions_03;
                        context.Response.Write(responseMsg);
                        return;
                    }
                    // check encrypted password
                    if (options[0].Password.Length < 20)
                    {
                        // backward compatibility
                        if (!members.Validate_Member_Email(_email_options.Email, _email_options.Password))
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_emailoptions_03;
                            context.Response.Write(responseMsg);
                            return;
                        }
                    }
                    else
                    {
                        // check encrypted password with user typed password
                        bool matched = BCrypt.Net.BCrypt.Verify(_email_options.Password, options[0].Password);
                        if (!matched)
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_emailoptions_03;
                            context.Response.Write(responseMsg);
                            return;
                        }
                    }

                    // update user validation key
                    var _key = Guid.NewGuid().ToString().Substring(0, 10);
                    members.Update_Value(_email_options.UserName, "val_key", _key);

                    // send mail validation request on new email address
                    MailTemplateProcess_EmailOptions(_email_options.Email, _email_options.UserName, _key);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Email change request sent on email";
                    context.Response.Write(responseMsg);
                    break;

                case "signout":
                    // Authentication
                    FormsAuthentication.SignOut();

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Success";
                    context.Response.Write(responseMsg);
                    break;

                case "change_password":
                    // Authentication
                    if (!context.User.Identity.IsAuthenticated)
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Authentication Failed";
                        context.Response.Write(responseMsg);
                        return;
                    }

                    var    _change_password = JsonConvert.DeserializeObject <Member_Struct>(json);
                    string _oldPassword     = "";
                    string _newPassword     = "";

                    if (context.Request.Params["op"] != null)
                    {
                        _oldPassword = context.Request.Params["op"].ToString();
                    }
                    if (context.Request.Params["np"] != null)
                    {
                        _newPassword = context.Request.Params["np"].ToString();
                    }
                    var _cPass = members.Get_Hash_Password(_change_password.UserName);
                    if (_cPass.Count == 0)
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = Resources.vsk.message_pass_01;
                        context.Response.Write(responseMsg);
                        return;
                    }
                    // check encrypted password
                    if (_cPass[0].Password.Length < 20)
                    {
                        // backward compatibility
                        // check existing user passwords with old system
                        if (!_mem.Validate_Member(_change_password.UserName, _oldPassword, false))
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_pass_01;
                            context.Response.Write(responseMsg);
                            return;
                        }
                    }
                    else
                    {
                        // check encrypted password with user typed password
                        bool matched = BCrypt.Net.BCrypt.Verify(_oldPassword, _cPass[0].Password);
                        if (!matched)
                        {
                            responseMsg["status"]  = "error";
                            responseMsg["message"] = Resources.vsk.message_pass_01;
                            context.Response.Write(responseMsg);
                            return;
                        }
                    }
                    // change password
                    int    BCRYPT_WORK_FACTOR = 10;
                    string _enc_pass          = BCrypt.Net.BCrypt.HashPassword(_newPassword, BCRYPT_WORK_FACTOR);
                    members.Update_Value(_change_password.UserName, "password", _enc_pass);

                    MailTemplateProcess_ChangePassword(_change_password.UserName);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Email change request sent on email";
                    context.Response.Write(responseMsg);
                    break;



                case "validate_user":
                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    if (members.Validate_Member(UserName))
                    {
                        responseMsg["status"]  = "success";
                        responseMsg["message"] = "Validated";
                    }
                    else
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Not Validated";
                    }
                    context.Response.Write(responseMsg);
                    break;

                /*case "validate_member_email":
                 *
                 *  var _val_email = JsonConvert.DeserializeObject<Member_Struct>(json);
                 *  if (members.Validate_Member_Email(_val_email.Email,_val_email.Password))
                 *  {
                 *      responseMsg["status"] = "success";
                 *      responseMsg["message"] = "Validated";
                 *  }
                 *  else
                 *  {
                 *      responseMsg["status"] = "error";
                 *      responseMsg["message"] = "Not Validated";
                 *  }
                 *  break; */

                case "check_username":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    if (_mem.Check_UserName(UserName))
                    {
                        responseMsg["status"]  = "success";
                        responseMsg["message"] = "Validated";
                    }
                    else
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Not Validated";
                    }
                    context.Response.Write(responseMsg);
                    break;


                case "check_email":

                    if (context.Request.Params["email"] != null)
                    {
                        Email = context.Request.Params["email"].ToString();
                    }
                    if (_mem.Check_Email(Email))
                    {
                        responseMsg["status"]  = "success";
                        responseMsg["message"] = "Validated";
                    }
                    else
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Not Validated";
                    }
                    context.Response.Write(responseMsg);
                    break;

                case "check_key":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    if (context.Request.Params["key"] != null)
                    {
                        Key = context.Request.Params["key"].ToString();
                    }
                    if (_mem.Check_Key(UserName, Key))
                    {
                        responseMsg["status"]  = "success";
                        responseMsg["message"] = "Validated";
                    }
                    else
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Not Validated";
                    }
                    context.Response.Write(responseMsg);
                    break;

                case "getpicture":
                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    responseMsg["picture"] = _mem.Get_Picture_NO_Session(UserName);
                    context.Response.Write(responseMsg);

                    break;

                case "increment_views":

                    var _view_obj = JsonConvert.DeserializeObject <Member_Struct>(json);
                    members.Increment_Views(_view_obj.UserName, _view_obj.Views);
                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";

                    break;

                case "update_isenabled":


                    if (context.Request.Params["nval"] != null)
                    {
                        NewValue = Convert.ToInt32(context.Request.Params["nval"]);
                    }

                    var _upd_isenabled = JsonConvert.DeserializeObject <Member_Struct>(json);

                    _mem.Update_IsEnabled(_upd_isenabled.UserName, NewValue);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);

                    break;

                case "update_user_roles":



                    var _update_role = JsonConvert.DeserializeObject <Member_Struct>(json);

                    members.Update_User_Role(_update_role.UserName, _update_role.RoleID);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);

                    break;

                case "update_field":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    if (context.Request.Params["val"] != null)
                    {
                        Value = context.Request.Params["val"].ToString();
                    }
                    if (context.Request.Params["field"] != null)
                    {
                        FieldName = context.Request.Params["field"].ToString();
                    }

                    members.Update_Value(UserName, FieldName, Value);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);
                    break;

                case "get_field_value":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }

                    if (context.Request.Params["field"] != null)
                    {
                        FieldName = context.Request.Params["field"].ToString();
                    }

                    responseMsg["value"] = members.Return_Value(UserName, FieldName);

                    context.Response.Write(responseMsg);
                    break;

                case "load_channels":

                    var _ld_video_json = JsonConvert.DeserializeObject <Member_Struct>(json);
                    var _vObject       = new MembersObject()
                    {
                        Data  = _mem.Load_Channels_ADV(_ld_video_json),
                        Count = _mem.Count_Channels(_ld_video_json)
                    };

                    _ld_video_data["data"] = _vObject;

                    context.Response.Write(_ld_video_data);

                    break;

                case "load_users_autocomplete":
                    string _Term = "";
                    if (context.Request.Params["term"] != null)
                    {
                        _Term = context.Request.Params["term"].ToString();
                    }

                    responseMsg["data"] = members.Load_User_AutoComplete(_Term);

                    context.Response.Write(responseMsg);
                    break;

                case "fetch_record":
                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }

                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_Profile(UserName),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_user_channels":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_Channel(UserName),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_user_detail_profile":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_DetailProfile(UserName),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_user_status_info":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }

                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_Status_Info(UserName),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_user_usernames":

                    if (context.Request.Params["type"] != null)
                    {
                        Type = Convert.ToInt32(context.Request.Params["type"]);
                    }
                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_UserNames(Type),
                        Count = 0
                    };

                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_user_info":

                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }

                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_Info(UserName),
                        Count = 0
                    };

                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_usernames":


                    _ld_video_data["data"] = new MembersObject()
                    {
                        Data  = members.Fetch_User_UserNames(),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;
                }
            }
            else
            {
                // No action found
                responseMsg["status"]  = "error";
                responseMsg["message"] = "No action found";
                context.Response.Write(JsonConvert.SerializeObject(responseMsg));
            }
        }