Advertisement
Guest User

Untitled

a guest
Oct 5th, 2016
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.23 KB | None | 0 0
  1. namespace Terrasoft.Configuration.UserWSService
  2. {
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.ServiceModel;
  6. using System.ServiceModel.Activation;
  7. using System.ServiceModel.Web;
  8. using System.Web;
  9. using System.Text.RegularExpressions;
  10. using Terrasoft.Common;
  11. using Terrasoft.Core;
  12. using Terrasoft.Core.Configuration;
  13. using Terrasoft.Core.DB;
  14. using Terrasoft.Core.Entities;
  15. using Terrasoft.Core.Factories;
  16. using Terrasoft.Configuration;
  17. using Terrasoft.Core.Configuration;
  18. using Terrasoft.Configuration.QMUserManagementService;
  19.  
  20. using global::Common.Logging;
  21.  
  22. public class CreateUserResult
  23. {
  24. public bool Result;
  25.  
  26. public string ErrorMessage;
  27.  
  28. public Guid? ApplicationId;
  29. }
  30.  
  31. public class GetAspAuthBySessionResult
  32. {
  33. public string AspAuth { get; set; }
  34.  
  35. public string City { get; set; }
  36.  
  37. public string RefSources { get; set; }
  38.  
  39. public string DeviceId { get; set; }
  40.  
  41. public string Error { get; set; }
  42. }
  43.  
  44. [ServiceContract]
  45. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
  46. public class UserWSService {
  47.  
  48. private UserConnection _userConnection;
  49. private UserConnection UserConnection {
  50. get {
  51. if (_userConnection == null) {
  52. _userConnection = (UserConnection)HttpContext.Current.Session["UserConnection"];
  53. }
  54. return _userConnection;
  55. }
  56. }
  57.  
  58. //private static readonly ILog log = LogManager.GetCurrentClassLogger();
  59.  
  60. [OperationContract]
  61. [WebInvoke(Method = "POST", UriTemplate = "CreateAccount", BodyStyle = WebMessageBodyStyle.Wrapped,
  62. RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  63. public string CreateAccount(string phoneNumber, string email, string passwordHash, string deviceId, string city, string offerSum, string offerPeriod,
  64. string tokenSurname, string tokenFirstName, string tokenAdditionalName, DateTime tokenBirthDate)
  65. {
  66. var log = LogManager.GetCurrentClassLogger();
  67. log.DebugFormat(string.Format("phoneNumber={0};email={1};passwordHash={2};deviceId={3};offerSum={4};offerPeriod={5};tokenSurname={6};tokenFirstName={7};tokenAdditionalName={8};tokenBirthDate={9};city={10}",
  68. phoneNumber, email,passwordHash,deviceId,offerSum,offerPeriod,tokenSurname,tokenFirstName,tokenAdditionalName,tokenBirthDate, city));
  69. CreateUserResult returnObject = new CreateUserResult(){
  70. Result = false,
  71. ErrorMessage = "Account Not Found"
  72. };
  73. try
  74. {
  75. if (tokenBirthDate.Kind == DateTimeKind.Utc) {
  76. tokenBirthDate = tokenBirthDate.ToLocalTime();
  77. }
  78. var noMiddleName = false;
  79. if (tokenAdditionalName == null || tokenAdditionalName == "") {
  80. noMiddleName = true;
  81. }
  82.  
  83. var login = new Regex("[^+\\d]").Replace(phoneNumber, "");
  84. log.DebugFormat("login: {0}", login);
  85.  
  86. var unitSelect = (new Select(UserConnection).Top(1)
  87. .From("SysAdminUnit")
  88. .Column("Id")
  89. .Where("Name").IsEqual(Column.Parameter(login))) as Select;
  90.  
  91. var unitId = Guid.Empty;
  92. using (var dbExecutor = UserConnection.EnsureDBConnection())
  93. {
  94. using (var reader = unitSelect.ExecuteReader(dbExecutor))
  95. {
  96. while(reader.Read())
  97. {
  98. if(!reader.IsDBNull(reader.GetOrdinal("Id")))
  99. {
  100. unitId = reader.GetGuid(reader.GetOrdinal("Id"));
  101. }
  102. }
  103. }
  104. }
  105. log.DebugFormat("unitId: {0}", unitId);
  106.  
  107. int iOfferSum = 5000;
  108. int iOfferPeriod = 9;
  109. Terrasoft.Configuration.Contact contact = null;
  110. if(unitId == Guid.Empty) {
  111. var name = string.Join(" ", tokenSurname, tokenFirstName, tokenAdditionalName);
  112. var number = new SysSettingsService.SysSettingsService().GetIncrementValueVsMask("ContactLastNumber", "ContactCodeMask");
  113. contact = new Terrasoft.Configuration.Contact(UserConnection);
  114. contact.SetDefColumnValues();
  115. contact.TypeId = QMConsts.Contact.Type.Borrower;
  116. contact.UniqueNumber = number;
  117. contact.Name = name;
  118. contact.FirstName = tokenFirstName;
  119. contact.SecondName = tokenSurname;
  120. contact.MiddleName = tokenAdditionalName;
  121. contact.CRBProcessingAgree = true;
  122. contact.TermsAgree = true;
  123. contact.PersonalDataProcessingAgree = true;
  124. contact.AccountId = QMConsts.Account.OurCompany;
  125. contact.BirthDate = tokenBirthDate;
  126. contact.MobilePhone = phoneNumber;
  127. contact.Email = email;
  128. contact.NoMiddleName = noMiddleName;
  129. contact.Save();
  130. log.DebugFormat("contact saved: {0}", contact.Id);
  131.  
  132. var updateCommunications = new Update(UserConnection, "ContactCommunication")
  133. .Set("IsConfirmed", Column.Parameter(1))
  134. .Where("ContactId").IsEqual(Column.Parameter(contact.Id)) as Update;
  135. var rows = updateCommunications.Execute();
  136. log.DebugFormat("Communication updated {0} rows", rows);
  137.  
  138. try
  139. {
  140. iOfferSum = (int)decimal.Parse(offerSum.Replace(".", ","));
  141. iOfferPeriod = int.Parse(offerPeriod);
  142. }
  143. catch (Exception ex)
  144. {
  145. log.Error(ex);
  146. log.DebugFormat("Error: {0}", ex.ToString());
  147. returnObject = new CreateUserResult()
  148. {
  149. Result = false,
  150. ErrorMessage = ex.ToString(),
  151. };
  152. return JsonConvert.SerializeObject(returnObject);
  153. }
  154. log.DebugFormat("iOfferSum={0};iOfferPeriod={1}", iOfferSum, iOfferPeriod);
  155.  
  156. unitId = SecurityUtilities.CreateSSPAdminUnit(login, passwordHash, contact.Id, UserConnection);
  157. log.DebugFormat("unitId: {0}", unitId);
  158. }
  159.  
  160. var cityStr = HttpUtility.UrlDecode(city);
  161. log.DebugFormat("cityStr: {0}", cityStr);
  162.  
  163. var timeZone = GetTimeZone(HttpUtility.UrlDecode(city));
  164. var unit = new Terrasoft.Configuration.SysAdminUnit(UserConnection);
  165. unit.FetchFromDB(unitId);
  166. unit.TimeZoneId = timeZone != null && timeZone != string.Empty ? timeZone : "Russian Standard Time";
  167. unit.HomePageId = (Guid)Core.Configuration.SysSettings.GetValue(UserConnection, "SSPHomePageId");
  168. unit.Save(false);
  169. log.Debug("SysAdminUnit updated");
  170.  
  171. log.DebugFormat("contact is null ? : {0}", contact == null);
  172. GrantContactRights(unitId, contact.Id);
  173.  
  174. var applicationId = CreateContactLoan(contact.Id, deviceId, iOfferSum.ToString(), iOfferPeriod.ToString(), cityStr == null || cityStr == string.Empty ? "Неизвестный (IP: )" : cityStr);
  175. log.DebugFormat("created application: {0}", applicationId);
  176.  
  177. GrantApplicationRights(unitId, new Guid(applicationId));
  178.  
  179. returnObject = new CreateUserResult(){
  180. Result = true,
  181. ApplicationId = new Guid(applicationId)
  182. };
  183. }
  184. catch (Exception ex)
  185. {
  186. log.DebugFormat("Error: {0}", ex.ToString());
  187. returnObject = new CreateUserResult(){
  188. Result = false,
  189. ErrorMessage = ex.ToString()
  190. };
  191. }
  192.  
  193. return JsonConvert.SerializeObject(returnObject);
  194. }
  195.  
  196. private string GetTimeZone(string city)
  197. {
  198. var log = LogManager.GetCurrentClassLogger();
  199. log.DebugFormat("GetTimeZone: {0}", city);
  200. try
  201. {
  202. var citySelect = (new Select(UserConnection).Top(1)
  203. .From("KladrCities")
  204. .Column("Code")
  205. .Where("Name").IsEqual(Column.Parameter(city))) as Select;
  206.  
  207. try
  208. {
  209. var regionCode = string.Empty;
  210. using (var dbExecutor = UserConnection.EnsureDBConnection())
  211. {
  212. using (var reader = citySelect.ExecuteReader(dbExecutor))
  213. {
  214. while(reader.Read())
  215. {
  216. if(!reader.IsDBNull(reader.GetOrdinal("Code")))
  217. {
  218. regionCode = reader.GetString(reader.GetOrdinal("Code")).Substring(0, 2);
  219. log.DebugFormat("GetTimeZone. regionCode: {0}", regionCode);
  220. }
  221. }
  222. }
  223. }
  224.  
  225. var zoneSelect = (new Select(UserConnection).Top(1)
  226. .From("KladrRegionTimeZone").As("regToZone")
  227. .Column("zone", "Code")
  228. .LeftOuterJoin("TimeZone").As("zone").On("zone", "Id").IsEqual("regToZone", "TimeZoneId")
  229. .Where("regToZone", "RegionCode").IsEqual(Column.Parameter(regionCode))) as Select;
  230.  
  231. using (var dbExecutor = UserConnection.EnsureDBConnection())
  232. {
  233. using (var reader = zoneSelect.ExecuteReader(dbExecutor))
  234. {
  235. while(reader.Read())
  236. {
  237. if(!reader.IsDBNull(reader.GetOrdinal("Code")))
  238. {
  239. var zoneCode = reader.GetString(reader.GetOrdinal("Code"));
  240. log.DebugFormat("GetTimeZone. zoneCode: {0}", zoneCode);
  241. return zoneCode;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. catch(Exception e)
  248. {
  249. log.DebugFormat("Error: {0}", e.ToString());
  250. return string.Empty;
  251. }
  252. }
  253. catch (Exception ex)
  254. {
  255. log.DebugFormat("Error: {0}", ex.ToString());
  256. return string.Empty;
  257. }
  258. return string.Empty;
  259. }
  260.  
  261. private string CreateContactLoan(Guid contactId, string deviceId, string offerSum, string offerPeriod, string city) {
  262. var applicationService = new QuickMoneyApplicationWebServicesEx.QuickMoneyApplicationWebServicesEx();
  263. var result = applicationService.CreateApplication(contactId, deviceId, city);
  264. if (!result.success ||
  265. (string.IsNullOrEmpty(deviceId) && string.IsNullOrEmpty(offerSum) && string.IsNullOrEmpty(offerPeriod))) {
  266. return result.applicationId.ToString();
  267. }
  268. var applicationSchema = UserConnection.EntitySchemaManager.GetInstanceByName("Application");
  269. var application = applicationSchema.CreateEntity(UserConnection);
  270. application.FetchFromDB(result.applicationId);
  271. application.SetColumnValue("OfferPeriod", offerPeriod);
  272. application.SetColumnValue("OfferSum", offerSum);
  273. application.Save();
  274. return result.applicationId.ToString();
  275. }
  276.  
  277. private void GrantContactRights(Guid unitId, Guid contactId) {
  278. using (var dbExecutor = UserConnection.EnsureDBConnection()) {
  279. for (var operationNumber = 0; operationNumber < 2; ++operationNumber) {
  280. var insert = new Insert(UserConnection)
  281. .Into("SysContactRight")
  282. .Set("RecordId", Column.Parameter(contactId))
  283. .Set("SysAdminUnitId", Column.Parameter(unitId))
  284. .Set("Position", Column.Parameter(0))
  285. .Set("SourceId", Column.Parameter(QMConsts.SysEntitySchemaRecRightSource.Owner))
  286. .Set("Operation", Column.Parameter(operationNumber))
  287. .Set("RightLevel", Column.Parameter(2));
  288. insert.Execute(dbExecutor);
  289. }
  290. }
  291. }
  292.  
  293. private void GrantApplicationRights(Guid unitId, Guid recordId) {
  294. var schema = UserConnection.EntitySchemaManager.GetInstanceByName("Application");
  295. if (!schema.AdministratedByRecords) {
  296. return;
  297. }
  298. using (var dbExecutor = UserConnection.EnsureDBConnection()) {
  299. for (var operationNumber = 0; operationNumber <= 1; operationNumber++) {
  300. var insert = new Insert(UserConnection)
  301. .Into("SysApplicationRight")
  302. .Set("RecordId", Column.Parameter(recordId))
  303. .Set("SysAdminUnitId", Column.Parameter(unitId))
  304. .Set("Position", Column.Parameter(0))
  305. .Set("SourceId", Column.Parameter(QMConsts.SysEntitySchemaRecRightSource.Owner))
  306. .Set("Operation", Column.Parameter(operationNumber))
  307. .Set("RightLevel", Column.Parameter(1));
  308. insert.Execute(dbExecutor);
  309. }
  310. }
  311. }
  312.  
  313. [OperationContract]
  314. [WebInvoke(Method = "POST", UriTemplate = "LogIn", BodyStyle = WebMessageBodyStyle.Wrapped,
  315. RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  316. public string LogIn(string userName, string userPassword, string workspaceName, int timeZoneOffset, string ipAddress, string agent){
  317. var returnObject = "OK";
  318. try
  319. {
  320.  
  321. string sessionId = Guid.NewGuid().ToString();//Terrasoft.Web.Common.SessionHelper.GetSessionId();
  322. var userCon = UserConnectionFactory.CreateUserConnection(
  323. UserConnection.AppConnection,
  324. new AuthData(){
  325. UserName = userName,
  326. UserPassword = userPassword,
  327. WorkspaceName = workspaceName,
  328. TimeZoneOffset = timeZoneOffset
  329. },
  330. sessionId,
  331. ipAddress,
  332. agent);
  333. return sessionId;
  334. }
  335. catch (Exception ex)
  336. {
  337. returnObject = "Error. " + ex.ToString();
  338. }
  339.  
  340. return returnObject;
  341. }
  342.  
  343. [OperationContract]
  344. [WebInvoke(Method = "POST", UriTemplate = "GetAspAuthBySession", BodyStyle = WebMessageBodyStyle.Wrapped,
  345. RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  346. public string GetAspAuthBySession(string sessionId){
  347. var returnObject = new GetAspAuthBySessionResult();
  348. try
  349. {
  350. var userSessionSelect = (new Select(UserConnection).Top(1)
  351. .From("UserSessionTable")
  352. .Column("AspAuth")
  353. .Column("City")
  354. .Column("RefSources")
  355. .Column("DeviceId")
  356. .Where("SessionId").IsEqual(Column.Parameter(sessionId))) as Select;
  357.  
  358. try
  359. {
  360. using (var dbExecutor = UserConnection.EnsureDBConnection())
  361. {
  362. using (var reader = userSessionSelect.ExecuteReader(dbExecutor))
  363. {
  364. while(reader.Read())
  365. {
  366. if(!reader.IsDBNull(reader.GetOrdinal("AspAuth")))
  367. returnObject.AspAuth = reader.GetString(reader.GetOrdinal("AspAuth"));
  368. if(!reader.IsDBNull(reader.GetOrdinal("City")))
  369. returnObject.City = reader.GetString(reader.GetOrdinal("City"));
  370. if(!reader.IsDBNull(reader.GetOrdinal("RefSources")))
  371. returnObject.RefSources = reader.GetString(reader.GetOrdinal("RefSources"));
  372. if(!reader.IsDBNull(reader.GetOrdinal("DeviceId")))
  373. returnObject.DeviceId = reader.GetString(reader.GetOrdinal("DeviceId"));
  374.  
  375. return JsonConvert.SerializeObject(returnObject);
  376. }
  377. }
  378. }
  379. }
  380. catch(Exception e)
  381. {
  382. returnObject.Error = e.ToString();
  383. return JsonConvert.SerializeObject(returnObject);
  384. }
  385. }
  386. catch (Exception ex)
  387. {
  388. returnObject.Error = ex.ToString();
  389. return JsonConvert.SerializeObject(returnObject);
  390. }
  391.  
  392. returnObject.Error = "NotFound";
  393. return JsonConvert.SerializeObject(returnObject);
  394. }
  395. }
  396. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement