using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataLibrary; using System.Web; using EncryptDecryptEngine; namespace CoreSavingLibrary { public class WebStateFactory : WebState { private XmlConfigService xmlconfig; private bool jmeterEnvironment = false; public WebStateFactory(Sdt dtToken, XmlConfigService xmlconfig, int conIndex, string conStr) { this.session = HttpContext.Current.Session; this.request = HttpContext.Current.Request; this.xmlconfig = xmlconfig; // ตอนแรกไม่ใช่ Ss แต่จะเปลี่ยนเป็น Ss แล้ว String coop_name = dtToken.GetString("coop_name"); SetSsApplicationName(dtToken.GetString("description")); SetSsCoopLogo(dtToken.GetString("cooplogo_path")); SetSsCoopName(dtToken.GetString("coop_name")); SetSsCoopNameEng(dtToken.GetString("coop_name")); // ตั้งค่า Session SetSsApplication(dtToken.GetString("application")); SetSsClientIp(); SetSsCloseDayStatus(dtToken.GetInt32("closeday_status")); SetSsCloseMonthStatus(-1); SetSsCloseYearStatus(-1); SetSsConnectionIndex(conIndex); SetSsConnectionString(conStr); SetSsCoopControl(dtToken.GetString("coop_control")); SetSsCoopId(dtToken.GetString("coop_id")); SetSsIsLocalIp(); SetSsPassword(dtToken.GetString("password")); SetSsPhysicalPath(); // ยังไม่แน่ใจวิธีการใช้งาน SetSsTokenId(dtToken.GetString("token_id")); SetSsUrl(); SetSsUserLevel(-1); SetSsUsername(dtToken.GetString("username")); SetSsWorkDate(dtToken.GetDate("workdate")); SetSsWsPass(); } private void initJmeter(PageWeb pw) { string sqlToken = @" select 'jmeter' as token_id, {0} as application, app.description, app.workdate, app.closeday_status, app.used_flag, c.coop_name, c.coop_control, c.cooplogo_path, {1} as coop_id, '127.0.0.1' as client_ip, 0 as con_index, {2} as username, {3} as password, sysdate as create_time, sysdate as last_try from amappstatus app, cmcoopmaster c where app.coop_id = c.coop_id and app.application = {0}"; sqlToken = WebUtil.SQLFormat(sqlToken, pw.Request["jmeter_application"], // 0 application pw.Request["jmeter_coop_id"], // 1 coop_id pw.Request["jmeter_username"], // 2 username pw.Request["jmeter_password"] // 3 password ); int conIndex = int.Parse(pw.Request["jmeter_connection_index"]); string conStr = pw.xmlconfig.ConnectionStringData.Rows[conIndex]["connection_string"].ToString(); Sta ta = new Sta(0, WebUtil.GetGcoopPath()); try { Sdt dtToken = ta.Query(sqlToken); if (dtToken.Next()) { // ตอนแรกไม่ใช่ Ss แต่จะเปลี่ยนเป็น Ss แล้ว SetSsApplicationName(dtToken.GetString("description")); SetSsCoopLogo(dtToken.GetString("cooplogo_path")); SetSsCoopName(dtToken.GetString("coop_name")); SetSsCoopNameEng(dtToken.GetString("coop_name")); // ตั้งค่า Session SetSsApplication(dtToken.GetString("application")); SetSsClientIp(); SetSsCloseDayStatus(dtToken.GetInt32("closeday_status")); SetSsCloseMonthStatus(-1); SetSsCloseYearStatus(-1); SetSsConnectionIndex(conIndex); SetSsConnectionString(conStr); SetSsCoopControl(dtToken.GetString("coop_control")); SetSsCoopId(dtToken.GetString("coop_id")); SetSsIsLocalIp(); SetSsPassword(dtToken.GetString("password")); SetSsPhysicalPath(); // ยังไม่แน่ใจวิธีการใช้งาน SetSsTokenId(dtToken.GetString("token_id")); SetSsUrl(); SetSsUserLevel(-1); SetSsUsername(dtToken.GetString("username")); SetSsWorkDate(dtToken.GetDate("workdate")); SetSsWsPass(); } } catch { } ta.Close(); } public WebStateFactory(PageWeb pw, PageWebType webType) { // เช็ค request มาจาก jmeter หรือไม่ if (!String.IsNullOrEmpty(pw.Request["jmeter_username"])) { jmeterEnvironment = true; initJmeter(pw); } // ตั้งค่า cookie virtual directory if (WebUtil.GetVirtualDirectoryCurrent() != "ICORE") { pw.Response.Cookies["vdir"].Value = WebUtil.GetVirtualDirectoryCurrent(); pw.Response.Cookies["vdir"].Expires = DateTime.Now.AddDays(1); } if (WebUtil.GetVirtualDirectory() == "ICORE") { pw.Response.Clear(); pw.Response.Write("ไม่พบ virtual directory"); pw.Response.End(); return; } // ตั้งค่า default ให้ object หลัก this.session = pw.Session; this.request = pw.Request; this.xmlconfig = pw.xmlconfig; // หาค่าการ authen จาก session string tokenId = this.SsTokenId; string username = this.SsUsername; int userLabel = this.SsUserLevel; string application = this.SsApplication; // ถ้าไม่พบการ authen ให้ redirect ไป SingleSignOn if (string.IsNullOrEmpty(tokenId) || string.IsNullOrEmpty(username)) { RequireToSSO(pw); } // ดูว่าเป็นหน้าจอประเภทไหน PageWebSheet pwSheet = null; PageWebDialog pwDialog = null; PageWebReport pwReport = null; try { pwSheet = (PageWebSheet)pw; } catch { pwSheet = null; } try { pwDialog = (PageWebDialog)pw; } catch { pwDialog = null; } try { pwReport = (PageWebReport)pw; } catch { pwReport = null; } // ถ้าพบว่ายังไม่ได้เลือกระบบ กรณี dialog ให้ throw exception นอกนั้นให้ redirect ไปหน้าเลือกระบบแบบ page if (string.IsNullOrEmpty(application)) { if (pwDialog != null) { throw new Exception("เกิดข้อผิดผลาดเนื่องจากไม่พบ application"); } else { string urlApplicationSelectionPage = WebUtil.GetSavingUrlCurrent() + "ApplicationSelectionPage.aspx"; pw.Response.Redirect(urlApplicationSelectionPage); } } // พยายามเชื่อมต่อ Database try { pw.oracleTA = new Sta(this.SsConnectionString); } catch { SetSsOracleTA(null); throw new Exception("ไม่สามารถเชื่อมต่อฐานข้อมูล [" + this.SsConnectionIndex + "]"); } // ลบ token ที่ไม่ได้ทำรายการนานกว่ากำหนดใน xmlconfig try { if (!jmeterEnvironment) { DateTime timeNow = DateTime.Now; int timeOut = xmlconfig.SSOTimeOutLogon; timeOut = (timeOut == 0 ? 60 : timeOut) * -1; String dtCut = "to_date('" + timeNow.AddMinutes(timeOut).ToString("yyyy-MM-d H:m:s", WebUtil.EN) + "', 'yyyy-mm-dd hh24:mi:ss')"; String sqlDelete = "delete from ssotoken where last_try < " + dtCut; pw.oracleTA.Exe(sqlDelete); } } catch { } // ถ้ามีกรณีบังคับเลือกระบบจาก query string argument และ update last try เลยหากทำได้ bool isUpdateLastTry = false; try { string setApp = request["setApp"]; if (!jmeterEnvironment) { if (!string.IsNullOrEmpty(setApp)) { pw.oracleTA.Exe(WebUtil.SQLFormat("update ssotoken set application={0}, last_try=sysdate where token_id={1}", setApp, tokenId)); } } } catch { } // ตรวจสอบ token ว่าเรายังอยู่ในระบบหรือไม่ ถ้าไม่มีให้ redirect ไป SSO (รวมทั้งเช็คสิทธิ์การใช้ระบบ) string sqlSelectToken = @" select s.token_id, s.application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = s.coop_id and application = s.application and user_name = s.username) as useapps, (select user_level from amsecusers where coop_id = s.coop_id and user_name = s.username) as user_level from ssotoken s, amappstatus a where s.coop_control = a.coop_id(+) and s.application = a.application(+) and s.token_id='" + tokenId + @"' "; if(Sta.IS_MYSQL_MODE){ sqlSelectToken = @" select s.token_id, s.application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = s.coop_id and application = s.application and user_name = s.username) as useapps, (select user_level from amsecusers where coop_id = s.coop_id and user_name = s.username) as user_level from ssotoken s left join amappstatus a on (s.coop_control = a.coop_id and s.application = a.application) where s.token_id='" + tokenId + @"' "; } if (jmeterEnvironment) { sqlSelectToken = @" select '" + tokenId + @"' as token_id, '" + this.SsApplication + @"' as application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = '" + this.SsCoopId + @"' and application = '" + this.SsApplication + @"' and user_name = '" + this.SsUsername + @"') as useapps, (select user_level from amsecusers where coop_id = '" + this.SsCoopId + @"' and user_name = '" + this.SsUsername + @"') as user_level from amappstatus a where a.coop_control = '" + this.SsCoopControl + @"' and a.application = '" + this.SsApplication + @"' "; } //ให้หาปิดเปิดวันตามสาขาก่อน ถ้าไม่เจอไปเอาจาก coop_control sqlSelectToken = @" select s.token_id, s.application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = s.coop_id and application = s.application and user_name = s.username) as useapps, (select user_level from amsecusers where coop_id = s.coop_id and user_name = s.username) as user_level from ssotoken s, amappstatus a where s.coop_id = a.coop_id and s.application = a.application(+) and s.token_id='" + tokenId + @"' "; if (Sta.IS_MYSQL_MODE) { sqlSelectToken = @" select s.token_id, s.application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = s.coop_id and application = s.application and user_name = s.username) as useapps, (select user_level from amsecusers where coop_id = s.coop_id and user_name = s.username) as user_level from ssotoken s left join amappstatus a on ( s.application = a.application ) where s.coop_id = a.coop_id and s.token_id='" + tokenId + @"' "; } Sdt dtToken = pw.oracleTA.Query(sqlSelectToken); if (dtToken.Rows.Count <= 0) { sqlSelectToken = @" select s.token_id, s.application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = s.coop_id and application = s.application and user_name = s.username) as useapps, (select user_level from amsecusers where coop_id = s.coop_id and user_name = s.username) as user_level from ssotoken s, amappstatus a where s.coop_control = a.coop_id(+) and s.application = a.application(+) and s.token_id='" + tokenId + @"' "; if (Sta.IS_MYSQL_MODE) { sqlSelectToken = @" select s.token_id, s.application, a.description, a.workdate, a.closeday_status, a.closemonth_status, a.closeyear_status, (select user_name from amsecuseapps where coop_id = s.coop_id and application = s.application and user_name = s.username) as useapps, (select user_level from amsecusers where coop_id = s.coop_id and user_name = s.username) as user_level from ssotoken s left join amappstatus a on (s.coop_control = a.coop_id and s.application = a.application) where s.token_id='" + tokenId + @"' "; } dtToken = pw.oracleTA.Query(sqlSelectToken); } if (!dtToken.Next()) { RequireToSSO(pw); } else { // เช็คสิทธิ์การใช้ระบบ if (dtToken.GetString("useapps").ToLower() == this.SsUsername.ToLower() && !string.IsNullOrEmpty(this.SsUsername)) { application = dtToken.GetString("application"); SetSsApplication(application); SetSsApplicationName(dtToken.GetString("description")); SetSsWorkDate(dtToken.GetDate("workdate")); SetSsCloseDayStatus(dtToken.GetInt32("closeday_status")); SetSsCloseMonthStatus(dtToken.GetInt32("closemonth_status")); SetSsCloseYearStatus(dtToken.GetInt32("closeyear_status")); SetSsUserLevel(dtToken.GetInt32("user_level")); } else { application = ""; SetSsApplication(application); SetSsApplicationName(""); SetSsWorkDate(new DateTime(1500, 1, 1)); SetSsCloseDayStatus(-1); SetSsCloseMonthStatus(-1); SetSsCloseYearStatus(-1); SetSsUserLevel(-1); } } // ถ้าไม่พบระบบ หรือวันทำการ ให้ redirect ไป application selection page if (string.IsNullOrEmpty(application) || this.SsWorkDate.Year <= 1700) { if (pwDialog != null) { throw new Exception("เกิดข้อผิดผลาดเนื่องจากไม่พบ application"); } else { try { pw.oracleTA.Close(); } catch { } string urlApplicationSelectionPage = WebUtil.GetSavingUrlCurrent() + "ApplicationSelectionPage.aspx"; pw.Response.Redirect(urlApplicationSelectionPage); } } // ถ้าเป็น PageWebSheet ให้ set ค่าต่างๆ สำหรับ Frame if (webType == PageWebType.Sheet) { SetCurrentGroup(); SetCurrentPage(); SetCurrentPageId(); } // set ค่าว่าเป็น web sheet หรือไม่ SetIsWebSheet(webType != PageWebType.Dialog); // ดึงค่าและเซ็ตค่าเกี่ยวกับ PageWebSheet try { string currPage = this.CurrentPage.Replace(".aspx", ""); string currPageId = this.CurrentPageId; string sqlAmSecWins = @" select application, window_id, win_object, win_description, win_parameter, win_toolbar, open_type, used_flag, group_code, web_redirect, (select check_flag from amsecpermiss where coop_id='"+this.SsCoopId+@"' and user_name={1} and application=amsecwins.application and window_id=amsecwins.window_id) as check_flag, (select save_status from amsecpermiss where coop_id='"+this.SsCoopId+@"' and user_name={1} and application=amsecwins.application and window_id=amsecwins.window_id) as save_status from amsecwins where application = {2} and window_id = {3} and win_object = {4} "; sqlAmSecWins = WebUtil.SQLFormat(sqlAmSecWins, this.SsCoopId, this.SsUsername, this.SsApplication, currPageId, currPage); Sdt dtAmSecWins = pw.oracleTA.Query(sqlAmSecWins); if (dtAmSecWins.Next()) { SetIsReadable(dtAmSecWins.GetInt32("check_flag") == 1); SetIsWritable(dtAmSecWins.GetInt32("save_status") == 1); SetCurrentPageName(dtAmSecWins.GetString("win_description")); } else { SetIsReadable(false); SetIsWritable(false); } } catch { SetIsReadable(false); SetIsWritable(false); } // update token last try try { if (!string.IsNullOrEmpty(this.SsTokenId) && !isUpdateLastTry) { if (!jmeterEnvironment) { string sqlUpdate = "update ssotoken set last_try = sysdate where token_id = '" + this.SsTokenId + "'"; pw.oracleTA.Exe(sqlUpdate); } } } catch { } // set ให้ transaction เป็น session SetSsOracleTA(pw.oracleTA); // set ws pass ใหม่อีกครั้ง SetSsWsPass(); } private void SetSsApplication(string application) { session["SsApplication"] = application; } private void SetSsApplicationName(string applicationName) { session["SsApplicationName"] = applicationName; } private void SetSsCoopLogo(string logoPath) { this.session["SsCoopLogo"] = logoPath; } private void SetSsCoopName(string coopName) { this.session["SsCoopName"] = coopName; } private void SetSsCoopNameEng(string coopNameEng) { this.session["SsCoopNameEng"] = coopNameEng; } // ต้อง set ทุก request private void SetCurrentGroup() { String setGroup = ""; try { setGroup = request["setGroup"].Trim(); } catch { } this.currentGroup = setGroup; } // ต้อง set ทุก request private void SetCurrentPage() { try { String url = request.Url.AbsolutePath; String urlLow = url.ToLower(); int index1 = urlLow.LastIndexOf("/"); if (index1 > 0) { currentPage = url.Substring(index1 + 1); } else { currentPage = ""; } } catch { currentPage = ""; } } // ต้อง set ทุก request private void SetCurrentPageId() { try { String wId = request["setWinId"].Trim(); currentPageId = wId; } catch { currentPageId = ""; } } // ต้อง set ทุก request private void SetCurrentPageName(string pageName) { currentPageName = pageName; } // ต้อง set ทุก request private void SetIsReadable(bool readable) { isReadable = readable; } // ต้อง set ทุก request public void SetIsWebSheet(bool isNotDlg) { try { String url = request.Url.AbsolutePath.ToLower(); if (url.IndexOf("/applications/") > 0 && url.IndexOf("/dlg/") < 0 && isNotDlg) { isWebSheet = true; } else { isWebSheet = false; } } catch { isWebSheet = false; } } // ต้อง set ทุก request private void SetIsWritable(bool writable) { isWritable = writable; } // ต้อง set ทุก request private void SetSsOracleTA(Sta ta) { session["SsOracleTA"] = ta; } private void SetSsClientIp() { string bfIpAdd = ""; if (string.IsNullOrEmpty(bfIpAdd)) { String ipAdd = "0.0.0.0"; try { ipAdd = request.UserHostAddress; } catch { } bfIpAdd = ipAdd; } session["SsClientIp"] = bfIpAdd; } // ต้อง set ทุก request private void SetSsCloseDayStatus(int closeDayStatus) { session["SsCloseDayStatus"] = closeDayStatus; } // ต้อง set ทุก request private void SetSsCloseMonthStatus(int closeMonthStatus) { session["SsCloseMonthStatus"] = closeMonthStatus; } // ต้อง set ทุก request private void SetSsCloseYearStatus(int closeYearStatus) { session["SsCloseYearStatus"] = closeYearStatus; } private void SetSsConnectionIndex(int conIndex) { session["SsConnectionIndex"] = conIndex; } private void SetSsConnectionString(string conStr) { conStr = conStr + ";"; conStr = conStr.Replace(";;", ";"); session["SsConnectionString"] = conStr; } private void SetSsCoopControl(string coopControl) { session["SsCoopControl"] = coopControl; } private void SetSsCoopId(string coopId) { session["SsCoopId"] = coopId; } private void SetSsIsLocalIp() { try { String ipAddress = this.SsClientIp.Trim(); if (ipAddress == "127.0.0.1" || ipAddress == "::1") { session["SsIsLocalIp"] = true; return; } String ipPattern = xmlconfig.ClientIpPattern; if (ipPattern.IndexOf(".xxx") > 0) { ipPattern = ipPattern.Substring(0, ipPattern.IndexOf(".xxx")); } if (ipAddress.IndexOf(ipPattern) == 0) { session["SsIsLocalIp"] = true; } else { session["SsIsLocalIp"] = false; } } catch { session["SsIsLocalIp"] = false; } } private void SetSsPassword(string password) { session["SsPassword"] = password; } // ยังไม่แน่ใจว่าใช้ทำอะไรกันแน่ private void SetSsPhysicalPath() { try { String pathPattern = xmlconfig.SavPathPattern; String path = request.Url.AbsolutePath; path = path.Replace(pathPattern, ""); path = path.Replace("/", "\\"); path = xmlconfig.SavingPath + path; int id = path.LastIndexOf("\\"); path = path.Substring(0, id + 1); session["SsPhysicalPath"] = path; } catch { session["SsPhysicalPath"] = ""; } } private void SetSsTokenId(string tokenId) { session["SsTokenId"] = tokenId; } // ต้อง set ทุก request private void SetSsUrl() { //string fullUrl = request.Url.AbsoluteUri; //int indexOfSaving = fullUrl.ToLower().IndexOf("/gcoop/saving"); //string savUrl = fullUrl.Substring(0, indexOfSaving) + "/GCOOP/Saving/"; session["SsUrl"] = WebUtil.GetSavingUrlCore(); } // ต้อง set ทุก request private void SetSsUserLevel(int userLavel) { session["SsUserLevel"] = userLavel; } private void SetSsUsername(string username) { session["SsUsername"] = username; } // ต้อง set ทุก request private void SetSsWorkDate(DateTime workDate) { session["SsWorkDate"] = workDate; } // ต้อง set ทุก request และ set เป็นอันสุดท้ายตลอด private void SetSsWsPass() { try { session["SsWsPass"] = this.SsConnectionString + "gcoop_path=" + WebUtil.GetGcoopPath() + ";saving_address=" + WebUtil.GetSavingAddress() + ";client_ip=" + this.SsClientIp + ";coop_id=" + this.SsCoopId + ";coop_control=" + this.SsCoopControl; } catch { session["SsWsPass"] = ""; } } /// /// ดึงค่า url ของ SingleSignOn /// /// private string GetSingleSignOnUrl() { string domain = xmlconfig.SSODomain; if (domain == "*") { domain = xmlconfig.SavDomain; } if (domain == "*") { domain = WebUtil.GetSavingAddress(); } string url = xmlconfig.SSOProtocol + "://" + domain + ":" + xmlconfig.SSOPort + "/ICORE/" + xmlconfig.SSOPathPattern; return url; } private void RequireToSSO(PageWeb pw) { // จัดเตรียม argument เพื่อส่งไปยัง SingleSignOn string sessionId = this.session.SessionID; sessionId = Encryption.SessionFormat(sessionId); string refUrl = WebUtil.GetSavingUrlCurrent() + "Restore.aspx"; refUrl = Encryption.SessionFormat(refUrl); int conIndex = 0; try { conIndex = int.Parse(this.request.Cookies["cid"].Value); } catch { conIndex = this.SsConnectionIndex; } string vDir = WebUtil.GetVirtualDirectory(); string ssoUrl = GetSingleSignOnUrl() + "Default.aspx?ss={0}&ref={1}&vdir={2}&cid={3}"; ssoUrl = string.Format(ssoUrl, sessionId, refUrl, vDir, conIndex); // สร้าง session เก็บค่า url เพื่อเวลา login สำเร็จจะได้กลับมาหน้าเดิม this.session["SsRestoreUrl"] = this.request.Url.AbsoluteUri; pw.Response.Redirect(ssoUrl); } } }