using NEducation.Code; using NEducation.Content.Texts; using NEducation.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.ServiceModel; using System.Web; using System.Web.Mvc; using System.IO; using System.Globalization; using System.Linq; using System.Threading; using System.Web.SessionState; using Newtonsoft.Json; using System.Net.Sockets; using System.Net; using System.Security.Policy; using Microsoft.Extensions.Configuration; using System.Threading.Tasks; using System.Net.Http; using Microsoft.EntityFrameworkCore.Metadata.Internal; using log4net.Core; using Newtonsoft.Json.Serialization; using Devart.Common; namespace NEducation.Controllers { public class HomeController : BaseController { private static log4net.ILog log { get; set; } = log4net.LogManager.GetLogger(typeof(HomeController)); GenKeyWs.WsGenKeyClient wsClient = new GenKeyWs.WsGenKeyClient(); public ActionResult Index(String token) { HomeModel model = new HomeModel(); if (token != null) { log.Info("login_camid:"); Session["navitab"] = "Home"; //HomeModel model = new HomeModel(); // nhan dien thue bao String msisdnAuto = null; model.uuid = token; log.Info("uuid: " + token); HttpCookie reqCookies = Request.Cookies["onapp"]; if (reqCookies != null) { string isOnApp = reqCookies["isonapp"].ToString(); if (isOnApp == "1") { Session["WHICHDEVICE"] = UtilsController.Constant.REGISTER_ON_APP; } } Session["Token"] = token; String msisdnToken = getUserFromToken(token); log.Info("msisdn: " + msisdnToken); if (msisdnToken != "") { //String resDetect = CheckAutoLogin(log, msisdnToken); //log.Info("token: " + token + " res: " + resDetect); //if (resDetect != null) //{ // dynamic json = JsonConvert.DeserializeObject(resDetect); // log.Info("res json: " + json); // String code = json["code"]; // if (code == "200") // { // String errorCode = json["errorCode"]; // if (errorCode == "200") // { // msisdnAuto = json["data"]["msisdn"]; // log.Info("msisdnAuto: " + msisdnAuto); // } // auto login // reload user info HttpContext.Session.Remove("regInfos"); Session["msisdnDetect"] = msisdnToken; // dang ky tren app Session["WHICHDEVICE"] = UtilsController.Constant.REGISTER_ON_APP; HttpCookie onApp = new HttpCookie("onapp"); onApp["isonapp"] = "1"; onApp.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(onApp); // check user has account GetUserProfileReq req = new GetUserProfileReq(); req.users = msisdnToken; String rs = UtilsController.SendPost(req, System.Web.HttpContext.Current.Session.SessionID, UtilsController.WsType.UsersGetProfile); UserProfile profile = new UserProfile(rs); if (profile.id != null) { System.Web.HttpContext.Current.Session["profile"] = profile; // create new auth CreateAuthToken(); String sessionId = Session.SessionID; // login success --> store session Session["msisdn"] = msisdnToken; Session["Token"] = token; // get sub UtilsController.ReloadSubInfo(); // all info of user was loaded from server //UserProfile profile = Session["profile"] as UserProfile; String typeLanguage = Session["typeLanguage"] as String; } else { // Create a free account for the user UserRequest userRequest = new UserRequest { users = msisdnToken, msisdn = msisdnToken, command = "REGIST", channel = "WEB" }; string rsRegister = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.UsersRegister); UserActionResult resRegister = new UserActionResult(rsRegister); Session["isSub"] = "false"; if (resRegister.status == UtilsController.Constant.SUCCESS) { // Load profile GetUserProfileReq reqProfile = new GetUserProfileReq { users = msisdnToken }; string rsProfile = UtilsController.SendPost(reqProfile, Session.SessionID, UtilsController.WsType.UsersGetProfile); UserProfile profileGet = new UserProfile(rsProfile); if (profileGet.id != null) { Session["profile"] = profileGet; UserInfoRequest reqStatus = new UserInfoRequest { users = msisdnToken }; string rsStatus = UtilsController.SendPost(reqStatus, Session.SessionID, UtilsController.WsType.UsersCheckStatus); UserActionResult resStatus = new UserActionResult(rsStatus); if (resStatus.status == UtilsController.Constant.SUCCESS) { UserInfo userInfo = new UserInfo(rsStatus); Session["userInfo"] = userInfo; Session["Token"] = token; // Create new auth CreateAuthToken(); Session["msisdn"] = msisdnToken; // Reload user info UtilsController.ReloadSubInfo(); } } } } // } //} } return View(model); } else { Session["WHICHDEVICE"] = UtilsController.Constant.REGISTER_ON_WEB; return View(model); } return null; } private string getUserFromToken(string token) { String resGet = GetUserInfoFromApp(token); log.Info(" get user from app result: " + resGet); if (resGet != null && resGet != "") { dynamic json = JsonConvert.DeserializeObject(resGet); log.Info("res json: " + json); String code = json["code"]; if (code == "00") { String msisdnAuto = json["data"]["user"]["phone_number"]; String userName = json["data"]["user"]["username"]; log.Info("msisdnAuto: " + msisdnAuto); log.Info("userName: " + userName); // check phone number String msisdn = UtilsController.validateMsisdn(msisdnAuto); if (msisdn != null && msisdn != "") { Session["msisdn"] = msisdn; //Session["channel"] = "2"; //Response.Cookies["channel"].Value = "2"; //Response.Cookies["token"].Value = token; //ServiceLogin.WsGamePortalClient wsClient = new ServiceLogin.WsGamePortalClient(); //SetWsClient(ref wsClient, Session.SessionID); //ServiceLogin.response wsResponse = ReloadAccountInfo(msisdn); //if (wsResponse.msisdn != null && wsResponse.msisdn.Length > 0) //{ // CreateAuthToken(); //} return msisdn; } } } return null; } public string GetUserInfoFromApp(string token) { string res = null; try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); httpClient.DefaultRequestHeaders.Add("accessToken", ConfigurationManager.AppSettings["accessToken"]); // Ghi log tất cả các header log.Info("Headers:"); foreach (var header in httpClient.DefaultRequestHeaders) { log.Info($"{header.Key}: {string.Join(", ", header.Value)}"); } log.Info("Req " + ConfigurationManager.AppSettings["pathDetectUser"]); HttpResponseMessage response = httpClient.GetAsync(ConfigurationManager.AppSettings["pathDetectUser"]).Result; log.Info("response " + response.ToString()); response.EnsureSuccessStatusCode(); res = response.Content.ReadAsStringAsync().Result; } } catch (Exception ex) { log.Error(ex); } return res; } public ActionResult VietnameseIndex() { // check login try { if (!CheckAuthToken()) { // show login dialog return Redirect("/Home/Index"); } } catch (Exception exp) { System.Diagnostics.Debug.WriteLine("Exception: " + exp); } Session["COURSE_NOW"] = UtilsController.Constant.VIETNAMESE; return View("VietnameseIndex"); } public ActionResult LaosIndex() { if (!CheckAuthToken()) { // show login dialog return Redirect("/Home/Index"); } Session["COURSE_NOW"] = UtilsController.Constant.LAOS; return View("LaosIndex"); } public ActionResult EnglishIndex() { if (!CheckAuthToken()) { // show login dialog return Redirect("/Home/Index"); } Session["COURSE_NOW"] = UtilsController.Constant.ENGLISH; return View("EnglishIndex"); } public JsonResult CheckAccount(String typeCourse) { Session["typeLanguage"] = typeCourse; if (!CheckAuthToken()) { return Json(new { code = "-1", }); } return Json(new { code = "0", }); } public JsonResult CheckButton(String msisdn) { String mToken = Session["Token"] as String; return Json(new { token = mToken, msisdn = msisdn, }); } public JsonResult CourseSet(String courseId) { Session["COURSE_NOW"] = courseId; return Json(new { code = "0", }); } public ActionResult ChangeLanguage(String LanguageAbbrevation) { if (CheckAuthToken()) { System.Diagnostics.Debug.WriteLine("LanguageAbbrevation: " + LanguageAbbrevation); if (LanguageAbbrevation != null) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(LanguageAbbrevation); Thread.CurrentThread.CurrentUICulture = new CultureInfo(LanguageAbbrevation); } //Response.Cookies.Remove("Language"); HttpCookie cookie = new HttpCookie("Language"); cookie.Value = LanguageAbbrevation; Response.Cookies.Add(cookie); String mMsisdn = Session["msisdn"] as String; String lang = "1"; if (LanguageAbbrevation == "en") { lang = "0"; } SetLanguageRequest reqStatus = new SetLanguageRequest { users = mMsisdn, language = lang }; string rsStatus = UtilsController.SendPost(reqStatus, Session.SessionID, UtilsController.WsType.usersSetLanguage); SetLanguageResult resStatus = new SetLanguageResult(rsStatus); if (resStatus.status == UtilsController.Constant.SUCCESS) { log.Debug("ChangeLanguage_SUCCESS"); } else { log.Debug("ChangeLanguage_Faild"); } return View(); } else { Session.Clear(); return Redirect("/Home/Index"); } } [ValidateAntiForgeryToken] public async Task RegisterSub(string captcha, string phone, string otp) { try { log.Debug("RegisterSub: " + phone); String packageName = ConfigurationManager.AppSettings["packname"]; String REGISTER_ToBe = ConfigurationManager.AppSettings["packNameREGISTER_ToBe"]; String fee = ConfigurationManager.AppSettings["fee"]; // check account existed var checkSub = UtilsController.checkAccountSub(phone, REGISTER_ToBe); if (checkSub == false) { // Tạo đối tượng mpsparams với các giá trị từ tham số MpsParams mpsparams = new MpsParams { CMD = "REGISTER", PRICE = fee, MOBILE = phone, CATE = "BLANK", SUB = packageName }; // Gọi phương thức bất đồng bộ để đăng ký GenKeyWs.response makeUrl = await WapController.UserRegisteringAsync(wsClient, mpsparams); // Lưu thông tin vào session Session["mps-params"] = mpsparams; log.Debug("mpsparams_RegisterSub: " + mpsparams); log.Debug("makeUrl_RegisterSub: " + makeUrl); // Kiểm tra mã lỗi và trả về kết quả tương ứng if (makeUrl.errorCode == UtilsController.WapConstant.SUCCESS) { return Json(new { success = true, redirectUrl = makeUrl.enscrypt }); } else { return Json(new { success = false, error_code = makeUrl.errorCode, error_content = UtilsController.GetErrorCodeCharging(makeUrl.errorCode) }); } } else { return Json(new { success = true, redirectUrl = "/Home/Index" }); } } catch (Exception ex) { // Log lỗi nếu cần return Json(new { success = false, error_code = "UNKNOWN_ERROR", error_content = "An unexpected error occurred: " }); } } //[ValidateAntiForgeryToken] //public async Task RegisterSub(string captcha, string phone, string otp) //{ // try // { // string packageName = ConfigurationManager.AppSettings["packname"]; // string fee = ConfigurationManager.AppSettings["fee"]; // // Tạo đối tượng mpsparams với các giá trị từ tham số // MpsParams mpsparams = new MpsParams // { // CMD = "REGISTER", // PRICE = fee, // MOBILE = phone, // CATE = "BLANK", // SUB = packageName // }; // // Gọi phương thức bất đồng bộ để đăng ký // GenKeyWs.response makeUrl = await WapController.UserRegisteringAsync(wsClient, mpsparams); // // Lưu thông tin vào session // Session["mps-params"] = mpsparams; // // Kiểm tra mã lỗi và trả về kết quả tương ứng // if (makeUrl.errorCode == UtilsController.WapConstant.SUCCESS) // { // return Redirect(makeUrl.enscrypt); // Điều hướng đến URL thành công // } // else // { // // Nếu không thành công, trả về một lỗi hoặc thông báo // return Json(new // { // success = false, // error_code = makeUrl.errorCode, // error_content = UtilsController.GetErrorCodeCharging(makeUrl.errorCode) // }, JsonRequestBehavior.AllowGet); // } // } // catch (Exception ex) // { // // Log lỗi nếu cần // return Json(new // { // success = false, // error_code = "UNKNOWN_ERROR", // error_content = "An unexpected error occurred." // }, JsonRequestBehavior.AllowGet); // } //} [ValidateAntiForgeryToken] public JsonResult RegisterSubWithoutCaptcha() { if (!CheckAuthToken()) { return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = ErrCode.SystemErr }); } String msisdn = Session["msisdn"] as string; String whichDevice = Session["WHICHDEVICE"] as String; if (msisdn != "" && msisdn != null) { // get package String packageId = Session["COURSE_NOW"] as String; String package = UtilsController.GetPackagename(packageId, whichDevice, "REGISTER"); // check account existed var checkSub = UtilsController.checkAccountSub(msisdn, package); if (checkSub == false) { //AbandonSession(); UserRequest userRequest = new UserRequest(); userRequest.users = msisdn; userRequest.msisdn = msisdn; userRequest.subServiceCode = package; userRequest.requestId = "-1"; userRequest.otp = "-1"; String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.MpsRequest); UserActionResult res = new UserActionResult(rs); if (res.responseCode == UtilsController.Constant.WAITING_OTP) //if (res.responseCode == UtilsController.Constant.SUCCESS) // for test { Charging charging = new Charging(rs); Session["charging"] = charging; Session["msisdn"] = msisdn; Session["package"] = package; Session["CHARGE_ACTION"] = UtilsController.Constant.REGISTER; Session["CHARGE_DATA"] = userRequest; } return Json(new { error_code = res.responseCode, error_content = UtilsController.GetErrorCodeCharging(res.responseCode) }); } else { return Json(new { error_code = UtilsController.Constant.USER_EXISTED, error_content = UtilsController.GetErrorCodeCharging(UtilsController.Constant.USER_EXISTED) }); } } else { return Json(new { error_code = UtilsController.Constant.INVALID_MSISDN, error_content = Lang.InvalidMsisdn, }); } } [ValidateAntiForgeryToken] public JsonResult ResentOtp() { String msisdn = Session["msisdn"] as string; if (msisdn != "" && msisdn != null) { String chargeAction = Session["CHARGE_ACTION"] as String; UserRequest chargerequest = Session["CHARGE_DATA"] as UserRequest; if (chargeAction == UtilsController.Constant.REGISTER) { // get package String whichDevice = Session["WHICHDEVICE"] as String; String packageId = Session["COURSE_NOW"] as String; String package = UtilsController.GetPackagename(packageId, whichDevice, "REGISTER"); String rs = UtilsController.SendPost(chargerequest, Session.SessionID, UtilsController.WsType.MpsRequest); UserActionResult res = new UserActionResult(rs); if (res.responseCode == UtilsController.Constant.WAITING_OTP) //if (res.responseCode == UtilsController.Constant.SUCCESS) // for test { Charging charging = new Charging(rs); Session["charging"] = charging; Session["msisdn"] = msisdn; Session["package"] = package; } return Json(new { error_code = res.responseCode, error_content = Lang.otpSentAgain }); } else { String rs = UtilsController.SendPost(chargerequest, Session.SessionID, UtilsController.WsType.buyCourse); UserActionResult res = new UserActionResult(rs); System.Diagnostics.Debug.WriteLine(rs); if (res.status == UtilsController.Constant.WAITING_OTP) //if (res.status == UtilsController.Constant.SUCCESS) // for test { Charging charging = new Charging(rs); Session["charging"] = charging; } return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } } else { return Json(new { error_code = UtilsController.Constant.EXCEPTION, }); } } [HttpPost] public ActionResult UploadImage(HttpPostedFileBase file) { if (CheckAuthToken()) { System.Diagnostics.Debug.WriteLine("file: " + file); // check type of file if (file != null && file.ContentLength > 0) try { var supportedTypes = new[] { "jpg", "png" }; var fileExt = Path.GetExtension(file.FileName).Substring(1); System.Diagnostics.Debug.WriteLine("fileExt: " + fileExt); System.Diagnostics.Debug.WriteLine("file.ContentLength: " + file.ContentLength); if (!supportedTypes.Contains(fileExt)) { //return Json(new //{ // error_content = "File Extension Is InValid - Only Upload WORD/PDF/EXCEL/TXT File", //}); ViewBag.Message = "File Extension Is InValid - Only Upload WORD/PDF/EXCEL/TXT File"; return View("ProfileView"); } else if (file.ContentLength > (5 * 1024 * 1024)) { //return Json(new //{ // error_content = "File size Should Be UpTo " + 5 + "MB", //}); ViewBag.Message = "File size Should Be UpTo 5MB"; return View("ProfileView"); } else { //string path = Path.Combine(Server.MapPath("~/Images"), // Path.GetFileName(file.FileName)); var msisdn = Session["msisdn"] as string; System.Diagnostics.Debug.WriteLine("msisdn: " + msisdn); if (msisdn != null) { System.Diagnostics.Debug.WriteLine("FileName: " + Path.GetFileName(file.FileName)); var fileName = msisdn + "_" + Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Content/assets/imgs/post/"), fileName); System.Diagnostics.Debug.WriteLine("path: " + path); file.SaveAs(path); ViewBag.Message = "File uploaded successfully"; ProfileModel model = new ProfileModel(); UserProfile userProfile = Session["profile"] as UserProfile; // update icon userProfile.picture = UtilsController.GetContentPath.IndividualContentPath + fileName; String rs = UtilsController.SendPost(userProfile, Session.SessionID, UtilsController.WsType.UsersUpdateProfile); UserActionResult res = new UserActionResult(rs); if (res.status == UtilsController.Constant.SUCCESS) { // update success --> store session Session["profile"] = userProfile; } else { return Redirect("/Common/Error"); } model.profileDetail = userProfile; return View("ProfileView", model); } else { ViewBag.Message = "File uploaded failure"; return Redirect("/Common/Error"); } } } catch (Exception ex) { ViewBag.Message = "ERROR:" + ex.Message.ToString(); return Redirect("/Common/Error"); } else { ViewBag.Message = "You have not specified a file."; return Redirect("/Common/Error"); } } else { Session.Clear(); return Redirect("/Home/Index"); } } [HttpPost] public ActionResult UploadExistedImage(String picture) { if (CheckAuthToken()) { // check type of file if (picture != null) { UserProfile userProfile = Session["profile"] as UserProfile; // update icon userProfile.picture = picture; String rs = UtilsController.SendPost(userProfile, Session.SessionID, UtilsController.WsType.UsersUpdateProfile); UserActionResult res = new UserActionResult(rs); if (res.status == UtilsController.Constant.SUCCESS) { // update success --> store session Session["profile"] = userProfile; } return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } else { ViewBag.Message = "You have not specified a file."; return Redirect("/Common/Error"); } } else { Session.Clear(); return Redirect("/Home/Index"); } } [ValidateAntiForgeryToken] public JsonResult CreateFree(String captcha, String phone) { try { if (!ReCaptcha.Validate(captcha)) { return Json(new { error_code = UtilsController.Constant.USER_EXISTED, error_content = "Your captcha is not valid" }); } String msisdn = UtilsController.validateMsisdn(phone); if (msisdn != "") { //AbandonSession(); UserRequest userRequest = new UserRequest(); userRequest.users = msisdn; userRequest.msisdn = msisdn; userRequest.command = "REGIST"; userRequest.channel = "WEB"; String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.UsersRegister); System.Diagnostics.Debug.WriteLine("res: " + rs); UserActionResult res = new UserActionResult(rs); Session["isSub"] = "false"; return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), href = res.status == UtilsController.Constant.SUCCESS ? "/Home/Login" : null, //href = res.status == UtilsController.Constant.SUCCESS ? "/Home/Login" : null // for test }); } else { return Json(new { error_code = UtilsController.Constant.INVALID_MSISDN, error_content = Lang.InvalidMsisdn, }); } } catch (Exception ex) { return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } public ActionResult LoginSuccess(String code) { try { // verify String tempCode = code; log.Info("Login success: code = " + code + ", tempCode = " + tempCode); Verify.VerifyReq req = new Verify.VerifyReq(); req.code = code; req.secretKey = ConfigurationManager.AppSettings["secretKey"]; string url = ConfigurationManager.AppSettings["uniIdVerifier"]; String result = UtilsController.SendPostWithAuthen(req, url, ConfigurationManager.AppSettings["secretKey"]); Verify.VerifyRes res = Verify.VerifyRes.Parse(result); if (res.status == 100) { // success -> check token String token = res.data.accessToken; Dictionary headers = new Dictionary(); headers.Add("Authorization", "Bearer " + token); result = UtilsController.SendGetWithAuthen(ConfigurationManager.AppSettings["uniIdUsers"], token); Verify.UserRes users = Verify.UserRes.Parse(result); if (users.status == 100) { // success // login success --> store session String msisdn = UtilsController.validateMsisdn(users.data.phone); // create new auth CreateAuthToken(); String sessionId = Session.SessionID; // login success --> store session Session["msisdn"] = msisdn; // get profile UtilsController.ReloadProfileInfo(); UserProfile profile = Session["profile"] as UserProfile; if (profile != null) { // get sub UtilsController.ReloadSubInfo(); } else { // create account UserRequest userRequest = new UserRequest(); userRequest.users = msisdn; userRequest.msisdn = msisdn; userRequest.command = "REGIST"; userRequest.channel = "WEB"; String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.UsersRegister); System.Diagnostics.Debug.WriteLine("res: " + rs); UtilsController.ReloadSubInfo(); } } } return Redirect("/Home"); } catch (Exception ex) { log.Error("Exception login success: " + ex.Message, ex); return Redirect("/Error"); } } [ValidateAntiForgeryToken] public JsonResult Login(String phoneNumber, String password, String typeLang) { try { String msisdn = UtilsController.validateMsisdn(phoneNumber); if (msisdn != "" && msisdn != null) { //AbandonSession(); UserInfoRequest user = new UserInfoRequest(); user.users = msisdn; user.msisdn = msisdn; user.pass = password; user.command = "LOGIN"; user.channel = "WEB"; String rs = UtilsController.SendPost(user, Session.SessionID, UtilsController.WsType.UsersRegister); UserActionResult res = new UserActionResult(rs); // fake if (msisdn == "8562098376035") { // create new auth CreateAuthToken(); String sessionId = Session.SessionID; // login success --> store session Session["msisdn"] = msisdn; // get profile UtilsController.ReloadProfileInfo(); // get sub UtilsController.ReloadSubInfo(); // all info of user was loaded from server //UserProfile profile = Session["profile"] as UserProfile; String typeLanguage = Session["typeLanguage"] as String; // check sub String isSub = Session["isSub"] as String; //HttpCookie onApp = new HttpCookie("onapp"); //onApp["isonapp"] = "1"; //onApp.Expires = DateTime.Now.AddDays(30); //Response.Cookies.Add(onApp); return Json(new { error_code = "0", error_content = "Success", msisdn = msisdn.Substring(UtilsController.CountryCode.Length), href = typeLanguage == UtilsController.Constant.LAOS ? "/Home/LaosIndex" : typeLanguage == UtilsController.Constant.VIETNAMESE ? "/Home/VietnameseIndex" : typeLanguage == UtilsController.Constant.ENGLISH ? "/Home/EnglishIndex" : "/Home/Index" }); } else if (res.status == UtilsController.Constant.SUCCESS) { // create new auth CreateAuthToken(); String sessionId = Session.SessionID; // login success --> store session Session["msisdn"] = msisdn; // get profile UtilsController.ReloadProfileInfo(); // get sub UtilsController.ReloadSubInfo(); // all info of user was loaded from server //UserProfile profile = Session["profile"] as UserProfile; String typeLanguage = Session["typeLanguage"] as String; //HttpCookie onApp = new HttpCookie("onapp"); //onApp["isonapp"] = "1"; //onApp.Expires = DateTime.Now.AddDays(30); //Response.Cookies.Add(onApp); return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), msisdn = msisdn.Substring(UtilsController.CountryCode.Length), href = typeLanguage == UtilsController.Constant.LAOS ? "/Home/LaosIndex" : typeLanguage == UtilsController.Constant.VIETNAMESE ? "/Home/VietnameseIndex" : typeLanguage == UtilsController.Constant.ENGLISH ? "/Home/EnglishIndex" : "/Home/Index" }); } else { return Json(new { error_code = res.status, //error_content = CommonController.ErrorContent(res.status), error_content = UtilsController.GetErrorCodeCharging(res.status), msisdn = msisdn.Substring(UtilsController.CountryCode.Length) }); } } else { return Json(new { error_code = UtilsController.Constant.INVALID_MSISDN, error_content = Lang.InvalidMsisdn, }); } } catch (Exception ex) { log.Error("Exception: ", ex); return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult AccountProfile() { if (CheckAuthToken()) { ProfileModel model = new ProfileModel(); model.profileDetail = Session["profile"] as UserProfile; return View("AccountProfileView", model); } else { Session.Clear(); return Redirect("/Home/Index"); } } public ActionResult Profile() { if (CheckAuthToken()) { ProfileModel model = new ProfileModel(); model.profileDetail = Session["profile"] as UserProfile; return View("ProfileView", model); } else { Session.Clear(); return Redirect("/Home/Index"); } } public ActionResult ChangePass() { if (CheckAuthToken()) { ProfileModel model = new ProfileModel(); model.profileDetail = Session["profile"] as UserProfile; return View("ChangePassView", model); } else { Session.Clear(); return Redirect("/Home/Index"); } } [ValidateAntiForgeryToken] public JsonResult UpdateProfile(String fullname, String birthday) { try { if (CheckAuthToken()) { UserProfile userProfile = Session["profile"] as UserProfile; userProfile.fullName = fullname; userProfile.birthday = birthday; String rs = UtilsController.SendPost(userProfile, Session.SessionID, UtilsController.WsType.UsersUpdateProfile); UserActionResult res = new UserActionResult(rs); if (res.status == UtilsController.Constant.SUCCESS) { // update success --> store session Session["profile"] = userProfile; return Json(new { error_code = res.status, error_content = res.message, href = "/Home/Profile" }); } else { return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } } else { Session.Clear(); return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } catch (Exception ex) { return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } [ValidateAntiForgeryToken] public JsonResult UpdatePass(String oldPassword, String password) { try { if (CheckAuthToken()) { UserInfoRequest userRequest = new UserInfoRequest(); userRequest.users = Session["msisdn"] as string; userRequest.passnew = password; userRequest.pass = oldPassword; userRequest.command = "CHANGEPASS"; String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.UsersRegister); UserActionResult res = new UserActionResult(rs); if (res.status == UtilsController.Constant.SUCCESS) { // update success --> store session return Json(new { error_code = res.status, error_content = res.message, href = "/Home/Profile" }); } else { return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } } else { Session.Clear(); return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } catch (Exception ex) { return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } [ValidateAntiForgeryToken] public JsonResult ResetPassword(String phoneNumber) { //if (CheckAuthToken()) //{ String msisdn = UtilsController.validateMsisdn(phoneNumber); if (msisdn != "") { UserInfoRequest userRequest = new UserInfoRequest(); userRequest.users = msisdn; userRequest.msisdn = msisdn; userRequest.command = "RESETPASS"; String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.UsersRegister); UserActionResult res = new UserActionResult(rs); if (res.status == UtilsController.Constant.SUCCESS) { // update success --> store session return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), //href = "/Home/Profile" }); } else { return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } } else { return Json(new { error_code = UtilsController.Constant.INVALID_MSISDN, error_content = Lang.InvalidMsisdn, }); } } [ValidateAntiForgeryToken] public JsonResult BuyCourse(String courseId, String phone, int courseChoose, String otpConfirm) { try { if (CheckAuthToken()) { if (otpConfirm == null) { UserRequest userRequest = new UserRequest(); userRequest.users = phone; userRequest.courseId = courseId; userRequest.codeBuy = courseChoose == 7 ? "EDU_CHARGE_50" : "EDU_CHARGE_200"; userRequest.requestId = "-1"; userRequest.otp = "-1"; String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.buyCourse); UserActionResult res = new UserActionResult(rs); System.Diagnostics.Debug.WriteLine(rs); if (res.status == UtilsController.Constant.WAITING_OTP) //if (res.status == UtilsController.Constant.SUCCESS) // for test { Charging charging = new Charging(rs); Session["charging"] = charging; Session["CHARGE_ACTION"] = UtilsController.Constant.BUY_COURSE; Session["CHARGE_DATA"] = userRequest; } return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } else { String msisdn = UtilsController.validateMsisdn(phone); if (msisdn != "") { UserRequest userRequest = new UserRequest(); userRequest.users = phone; userRequest.courseId = courseId; userRequest.codeBuy = courseChoose == 7 ? "EDU_CHARGE_50" : "EDU_CHARGE_200"; // get requestId on buying course Charging charging = Session["charging"] as Charging; userRequest.requestId = charging.requestId; userRequest.otp = otpConfirm.ToString(); String rs = UtilsController.SendPost(userRequest, Session.SessionID, UtilsController.WsType.buyCourse); UserActionResult res = new UserActionResult(rs); System.Diagnostics.Debug.WriteLine(rs); return Json(new { error_code = res.status, error_content = UtilsController.GetErrorCodeCharging(res.status), }); } else { return Json(new { error_code = UtilsController.Constant.INVALID_MSISDN, error_content = Lang.InvalidMsisdn, }); } } } else { Session.Clear(); return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } catch (Exception ex) { return Json(new { error_code = UtilsController.Constant.EXCEPTION, error_content = UtilsController.GetErrorCodeCharging("-10"), }); } } public ActionResult GetRanking() { if (CheckAuthToken()) { RankingModel model = new RankingModel(); UserInfoRequest user = new UserInfoRequest(); user.users = Session["msisdn"] as string; user.msisdn = Session["msisdn"] as String; String rs = UtilsController.SendPost(user, Session.SessionID, UtilsController.WsType.GetRanking); System.Diagnostics.Debug.WriteLine("rs: " + rs); UserActionResult res = new UserActionResult(rs); if (res.status == UtilsController.Constant.SUCCESS) { Ranking ranking = new Ranking(rs); model.ranking = ranking; // get current ranking for (int i = 0; i < ranking.listRanking.Count; i++) { if (ranking.listRanking[i].users == Session["msisdn"] as string) { model.currentRanking = ranking.listRanking[i]; } } return PartialView("_ModalRanking", model); } else { return Redirect("/Common/Error"); } } else { Session.Clear(); return Redirect("/Home/Index"); } } private void CreateAuthToken() { // create session authen SessionIDManager manager = new SessionIDManager(); string newSessionId = manager.CreateSessionID(System.Web.HttpContext.Current); Response.Cookies["AuthToken"].Value = newSessionId; Session["AuthToken"] = newSessionId; } private bool CheckAuthToken() { if (Session["AuthToken"] != null && Request.Cookies["AuthToken"] != null) { if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value)) { return false; } else { return true; } } else { return false; } } public RedirectResult Logout() { Session.Clear(); return Redirect("/Home/Index"); } } }