PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/CMSWebParts/Membership/LinkedIn/LinkedInUsersRequiredData.ascx.cs

https://bitbucket.org/kudutest2/kenticogit
C# | 594 lines | 415 code | 87 blank | 92 comment | 66 complexity | be34a195a3b486fc3f3d9c07417bf6b5 MD5 | raw file
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Text;
  5. using System.Web;
  6. using System.Xml;
  7. using System.Web.UI;
  8. using System.Web.Security;
  9. using CMS.PortalControls;
  10. using CMS.GlobalHelper;
  11. using CMS.TreeEngine;
  12. using CMS.CMSHelper;
  13. using CMS.SiteProvider;
  14. using CMS.EmailEngine;
  15. using CMS.EventLog;
  16. using CMS.DataEngine;
  17. using CMS.WebAnalytics;
  18. using CMS.LicenseProvider;
  19. using CMS.PortalEngine;
  20. using CMS.SettingsProvider;
  21. using CMS.MembershipProvider;
  22. using CMS.URLRewritingEngine;
  23. public partial class CMSWebParts_Membership_LinkedIn_LinkedInUsersRequiredData : CMSAbstractWebPart
  24. {
  25. #region "Constants"
  26. protected const string SESSION_NAME_USERDATA = "LinkedInUserData";
  27. #endregion
  28. #region "Private variables"
  29. private LinkedInHelper linkedInHelper = null;
  30. #endregion
  31. #region "Public properties"
  32. /// <summary>
  33. /// Gets or sets the value that indicates whether email to user should be sent.
  34. /// </summary>
  35. public bool SendWelcomeEmail
  36. {
  37. get
  38. {
  39. return ValidationHelper.GetBoolean(this.GetValue("SendWelcomeEmail"), true);
  40. }
  41. set
  42. {
  43. this.SetValue("SendWelcomeEmail", value);
  44. }
  45. }
  46. /// <summary>
  47. /// Gets or sets registration approval page URL.
  48. /// </summary>
  49. public string ApprovalPage
  50. {
  51. get
  52. {
  53. return DataHelper.GetNotEmpty(this.GetValue("ApprovalPage"), "");
  54. }
  55. set
  56. {
  57. this.SetValue("ApprovalPage", value);
  58. }
  59. }
  60. /// <summary>
  61. /// Gets or sets the sender email (from).
  62. /// </summary>
  63. public string FromAddress
  64. {
  65. get
  66. {
  67. return DataHelper.GetNotEmpty(this.GetValue("FromAddress"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
  68. }
  69. set
  70. {
  71. this.SetValue("FromAddress", value);
  72. }
  73. }
  74. /// <summary>
  75. /// Gets or sets the recipient email (to).
  76. /// </summary>
  77. public string ToAddress
  78. {
  79. get
  80. {
  81. return DataHelper.GetNotEmpty(this.GetValue("ToAddress"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSAdminEmailAddress"));
  82. }
  83. set
  84. {
  85. this.SetValue("ToAddress", value);
  86. }
  87. }
  88. /// <summary>
  89. /// Gets or sets the value that indicates whether after successful registration is
  90. /// notification email sent to the administrator.
  91. /// </summary>
  92. public bool NotifyAdministrator
  93. {
  94. get
  95. {
  96. return ValidationHelper.GetBoolean(this.GetValue("NotifyAdministrator"), false);
  97. }
  98. set
  99. {
  100. this.SetValue("NotifyAdministrator", value);
  101. }
  102. }
  103. /// <summary>
  104. /// Gets or sets the message which is displayed after successful registration.
  105. /// </summary>
  106. public string DisplayMessage
  107. {
  108. get
  109. {
  110. return ValidationHelper.GetString(this.GetValue("DisplayMessage"), "");
  111. }
  112. set
  113. {
  114. this.SetValue("DisplayMessage", value);
  115. }
  116. }
  117. /// <summary>
  118. /// Gets or sets the value which enables abitity of new user to set password.
  119. /// </summary>
  120. public bool AllowFormsAuthentication
  121. {
  122. get
  123. {
  124. return ValidationHelper.GetBoolean(GetValue("AllowFormsAuthentication"), false);
  125. }
  126. set
  127. {
  128. SetValue("AllowFormsAuthentication", value);
  129. plcPasswordNew.Visible = value;
  130. }
  131. }
  132. /// <summary>
  133. /// Gets or sets the value which enables abitity join liveid with existing account.
  134. /// </summary>
  135. public bool AllowExistingUser
  136. {
  137. get
  138. {
  139. return ValidationHelper.GetBoolean(GetValue("AllowExistingUser"), true);
  140. }
  141. set
  142. {
  143. SetValue("AllowExistingUser", value);
  144. plcPasswordNew.Visible = value;
  145. }
  146. }
  147. /// <summary>
  148. /// Gets or sets the default target url (redirection when the user is logged in).
  149. /// </summary>
  150. public string DefaultTargetUrl
  151. {
  152. get
  153. {
  154. return ValidationHelper.GetString(GetValue("DefaultTargetUrl"), "");
  155. }
  156. set
  157. {
  158. SetValue("DefaultTargetUrl", value);
  159. }
  160. }
  161. /// <summary>
  162. /// Gets or sets the value which determines the behaviour for no LinkedIn users.
  163. /// </summary>
  164. public bool HideForNoLinkedInUserID
  165. {
  166. get
  167. {
  168. return ValidationHelper.GetBoolean(GetValue("HideForNoLinkedInUserID"), true);
  169. }
  170. set
  171. {
  172. SetValue("HideForNoLinkedInUserID", value);
  173. }
  174. }
  175. #endregion
  176. #region "Conversion properties"
  177. /// <summary>
  178. /// Gets or sets the conversion track name used after successful registration.
  179. /// </summary>
  180. public string TrackConversionName
  181. {
  182. get
  183. {
  184. return ValidationHelper.GetString(this.GetValue("TrackConversionName"), "");
  185. }
  186. set
  187. {
  188. if ((value != null) && (value.Length > 400))
  189. {
  190. value = value.Substring(0, 400);
  191. }
  192. this.SetValue("TrackConversionName", value);
  193. }
  194. }
  195. /// <summary>
  196. /// Gets or sets the conversion value used after successful registration.
  197. /// </summary>
  198. public double ConversionValue
  199. {
  200. get
  201. {
  202. return ValidationHelper.GetDouble(this.GetValue("ConversionValue"), 0);
  203. }
  204. set
  205. {
  206. this.SetValue("ConversionValue", value);
  207. }
  208. }
  209. #endregion
  210. #region "Page events"
  211. /// <summary>
  212. /// Content loaded event handler.
  213. /// </summary>
  214. public override void OnContentLoaded()
  215. {
  216. base.OnContentLoaded();
  217. SetupControl();
  218. }
  219. /// <summary>
  220. /// Initializes the control properties.
  221. /// </summary>
  222. protected void SetupControl()
  223. {
  224. if (!this.StopProcessing)
  225. {
  226. plcError.Visible = false;
  227. // Check renamed DLL library
  228. if (!CMSOpenIDHelper.CheckOpenIdDLL())
  229. {
  230. // Error label is displayed when OpenID library is not enabled
  231. lblError.ResourceString = "mem.openid.library";
  232. plcError.Visible = true;
  233. plcContent.Visible = false;
  234. }
  235. string currentSiteName = CMSContext.CurrentSiteName;
  236. // Check if LinkedIn module is enabled
  237. if (!LinkedInHelper.LinkedInIsAvailable(CMSContext.CurrentSiteName) && !this.plcError.Visible)
  238. {
  239. // Error label is displayed only in Design mode
  240. if (CMSContext.ViewMode == ViewModeEnum.Design)
  241. {
  242. StringBuilder parameter = new StringBuilder();
  243. parameter.Append(GetString("header.sitemanager") + " -> ");
  244. parameter.Append(GetString("settingscategory.cmssettings") + " -> ");
  245. parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
  246. parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
  247. parameter.Append(GetString("settingscategory.cmslinkedin"));
  248. if (CMSContext.CurrentUser.UserSiteManagerAdmin)
  249. {
  250. // Make it link for SiteManager Admin
  251. parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl("~/CMSSiteManager/default.aspx?section=settings") + "\" target=\"_top\">");
  252. parameter.Append("</a>");
  253. }
  254. lblError.Text = String.Format(GetString("mem.linkedin.disabled"), parameter.ToString());
  255. plcError.Visible = true;
  256. plcContent.Visible = false;
  257. }
  258. // In other modes is webpart hidden
  259. else
  260. {
  261. this.Visible = false;
  262. }
  263. }
  264. // Display webpart when no error occured
  265. if (!plcError.Visible && this.Visible)
  266. {
  267. // Hide webpart if user is authenticated
  268. if (CMSContext.CurrentUser.IsAuthenticated())
  269. {
  270. this.Visible = false;
  271. return;
  272. }
  273. plcPasswordNew.Visible = this.AllowFormsAuthentication;
  274. pnlExistingUser.Visible = this.AllowExistingUser;
  275. linkedInHelper = new LinkedInHelper();
  276. linkedInHelper.Initialize(SessionHelper.GetValue(SESSION_NAME_USERDATA) as XmlDocument);
  277. // There is no LinkedIn user ID stored in session - hide all
  278. if (string.IsNullOrEmpty(linkedInHelper.MemberId) && HideForNoLinkedInUserID)
  279. {
  280. this.Visible = false;
  281. }
  282. else if (!RequestHelper.IsPostBack())
  283. {
  284. LoadData();
  285. }
  286. }
  287. }
  288. else
  289. {
  290. this.Visible = false;
  291. }
  292. }
  293. /// <summary>
  294. /// Handles btnOkExist click, joins existing user with LinkedIn member id.
  295. /// </summary>
  296. protected void btnOkExist_Click(object sender, EventArgs e)
  297. {
  298. if (!String.IsNullOrEmpty(linkedInHelper.MemberId))
  299. {
  300. if (!String.IsNullOrEmpty(txtUserName.Text))
  301. {
  302. // Try to authenticate user
  303. UserInfo ui = UserInfoProvider.AuthenticateUser(txtUserName.Text, txtPassword.Text, CMSContext.CurrentSiteName);
  304. // Check banned IPs
  305. BannedIPInfoProvider.CheckIPandRedirect(CMSContext.CurrentSiteName, BanControlEnum.Login);
  306. if (ui != null)
  307. {
  308. // Add LinkedIn profile member id to user
  309. ui.UserSettings.UserLinkedInID = linkedInHelper.MemberId;
  310. UserInfoProvider.SetUserInfo(ui);
  311. // Set authentication cookie and redirect to page
  312. SetAuthCookieAndRedirect(ui);
  313. }
  314. else // Invalid credentials
  315. {
  316. lblError.Text = GetString("Login_FailureText");
  317. plcError.Visible = true;
  318. }
  319. }
  320. else // User did not fill the form
  321. {
  322. lblError.Text = GetString("mem.linkedin.fillloginform");
  323. plcError.Visible = true;
  324. }
  325. }
  326. }
  327. /// <summary>
  328. /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
  329. /// </summary>
  330. protected void btnOkNew_Click(object sender, EventArgs e)
  331. {
  332. if (!String.IsNullOrEmpty(linkedInHelper.MemberId))
  333. {
  334. string currentSiteName = CMSContext.CurrentSiteName;
  335. // Validate entered values
  336. string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.linkedin.fillcorrectusername"))
  337. .IsEmail(txtEmail.Text, GetString("mem.linkedin.fillvalidemail")).Result;
  338. string password = passStrength.Text;
  339. // If password is enabled to set, check it
  340. if (plcPasswordNew.Visible && (String.IsNullOrEmpty(errorMessage)))
  341. {
  342. if (String.IsNullOrEmpty(password))
  343. {
  344. errorMessage = GetString("mem.linkedin.specifyyourpass");
  345. }
  346. else if (password != txtConfirmPassword.Text.Trim())
  347. {
  348. errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
  349. }
  350. // Check policy
  351. if (!passStrength.IsValid())
  352. {
  353. errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
  354. }
  355. }
  356. // Check whether email is unique if it is required
  357. if ((String.IsNullOrEmpty(errorMessage)) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), currentSiteName, 0))
  358. {
  359. errorMessage = GetString("UserInfo.EmailAlreadyExist");
  360. }
  361. // Check reserved names
  362. if ((String.IsNullOrEmpty(errorMessage)) && UserInfoProvider.NameIsReserved(currentSiteName, txtUserNameNew.Text.Trim()))
  363. {
  364. errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
  365. }
  366. if (String.IsNullOrEmpty(errorMessage))
  367. {
  368. // Check if user with given username already exists
  369. UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());
  370. // User with given username is already registered
  371. if (ui != null)
  372. {
  373. plcError.Visible = true;
  374. lblError.Text = GetString("mem.openid.usernameregistered");
  375. }
  376. else
  377. {
  378. // Register new user
  379. string error = this.DisplayMessage;
  380. ui = UserInfoProvider.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, currentSiteName, true, false, ref error);
  381. this.DisplayMessage = error;
  382. if (ui != null)
  383. {
  384. // Set additional information
  385. ui.UserName = ui.UserNickName = txtUserNameNew.Text.Trim();
  386. ui.Email = txtEmail.Text;
  387. if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
  388. {
  389. ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
  390. }
  391. // Set password
  392. if (plcPasswordNew.Visible)
  393. {
  394. UserInfoProvider.SetPassword(ui, password);
  395. // If user can choose password then is not considered external(external user can't login in common way)
  396. ui.IsExternal = false;
  397. }
  398. UserInfoProvider.SetUserInfo(ui);
  399. // Remove live user object from session, won't be needed
  400. SessionHelper.Remove(SESSION_NAME_USERDATA);
  401. // Notify administrator
  402. bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
  403. if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty))
  404. {
  405. UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress);
  406. }
  407. // Send registration e-mails
  408. UserInfoProvider.SendRegistrationEmails(ui, this.ApprovalPage, password, true, this.SendWelcomeEmail);
  409. // Log registration into analytics
  410. UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, currentSiteName, ui);
  411. // Log activity
  412. if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.UserLoginEnabled(currentSiteName)
  413. && ActivitySettingsHelper.UserRegistrationEnabled(currentSiteName))
  414. {
  415. int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
  416. ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId);
  417. TreeNode currentDoc = CMSContext.CurrentDocument;
  418. ActivityLogProvider.LogRegistrationActivity(contactId,
  419. ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, currentSiteName, CMSContext.Campaign, currentDoc.DocumentCulture);
  420. }
  421. // Set authentication cookie and redirect to page
  422. SetAuthCookieAndRedirect(ui);
  423. if (!String.IsNullOrEmpty(this.DisplayMessage))
  424. {
  425. lblInfo.Visible = true;
  426. lblInfo.Text = this.DisplayMessage;
  427. plcForm.Visible = false;
  428. }
  429. else
  430. {
  431. URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
  432. }
  433. }
  434. }
  435. }
  436. // Validation failed - display error message
  437. else
  438. {
  439. lblError.Text = errorMessage;
  440. plcError.Visible = true;
  441. }
  442. }
  443. }
  444. #endregion
  445. #region "Private methods"
  446. /// <summary>
  447. /// Helper method, sets authentication cookie and redirects to return URL or default page.
  448. /// </summary>
  449. /// <param name="ui">User info</param>
  450. private void SetAuthCookieAndRedirect(UserInfo ui)
  451. {
  452. // Create autentification cookie
  453. if (ui.Enabled)
  454. {
  455. UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" });
  456. // Log activity
  457. string siteName = CMSContext.CurrentSiteName;
  458. if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName))
  459. {
  460. int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
  461. ActivityLogHelper.UpdateContactLastLogon(contactId);
  462. if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
  463. {
  464. TreeNode currDoc = CMSContext.CurrentDocument;
  465. ActivityLogProvider.LogLoginActivity(contactId,
  466. ui, URLHelper.CurrentRelativePath, currDoc.NodeID, siteName, CMSContext.Campaign, currDoc.DocumentCulture);
  467. }
  468. }
  469. string returnUrl = QueryHelper.GetString("returnurl", null);
  470. // Redirect to ReturnURL
  471. if (!String.IsNullOrEmpty(returnUrl))
  472. {
  473. URLHelper.Redirect(ResolveUrl(HttpUtility.UrlDecode(returnUrl)));
  474. }
  475. // Redirect to default page
  476. else if (!String.IsNullOrEmpty(this.DefaultTargetUrl))
  477. {
  478. URLHelper.Redirect(ResolveUrl(this.DefaultTargetUrl));
  479. }
  480. // Otherwise refresh current page
  481. else
  482. {
  483. URLHelper.Redirect(URLRewriter.CurrentURL);
  484. }
  485. }
  486. }
  487. /// <summary>
  488. /// Loads textboxes with LinkedIn data.
  489. /// </summary>
  490. private void LoadData()
  491. {
  492. string userName = linkedInHelper.FirstName;
  493. if (!String.IsNullOrEmpty(linkedInHelper.LastName))
  494. {
  495. if (String.IsNullOrEmpty(userName))
  496. {
  497. userName = linkedInHelper.LastName;
  498. }
  499. else
  500. {
  501. userName += "_" + linkedInHelper.LastName;
  502. }
  503. }
  504. txtUserNameNew.Text = userName;
  505. }
  506. #endregion
  507. }