PageRenderTime 28ms CodeModel.GetById 41ms RepoModel.GetById 1ms app.codeStats 0ms

/CMSWebParts/Membership/OpenID/OpenIDUserRequiredData.ascx.cs

https://bitbucket.org/kudutest2/kenticogit
C# | 654 lines | 456 code | 88 blank | 110 comment | 90 complexity | 4aec30a804411eefe90c66f9bd214c35 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using CMS.PortalControls;
  8. using CMS.GlobalHelper;
  9. using CMS.SettingsProvider;
  10. using CMS.CMSHelper;
  11. using CMS.PortalEngine;
  12. using CMS.SiteProvider;
  13. using CMS.URLRewritingEngine;
  14. using CMS.EventLog;
  15. using CMS.EmailEngine;
  16. using CMS.WebAnalytics;
  17. using CMS.MembershipProvider;
  18. using TreeNode = CMS.TreeEngine.TreeNode;
  19. public partial class CMSWebParts_Membership_OpenID_OpenIDUserRequiredData : CMSAbstractWebPart
  20. {
  21. #region "Constants"
  22. protected const string SESSION_NAME_USERDATA = "OpenIDAuthenticatedUserData";
  23. protected const string SESSION_NAME_URL = "OpenIDProviderURL";
  24. #endregion
  25. #region "Variables"
  26. private string mDefaultTargetUrl = null;
  27. private string userProviderUrl = null;
  28. private CMSOpenIDHelper openIDhelper = null;
  29. #endregion
  30. #region "Public properties"
  31. /// <summary>
  32. /// Gets or sets the value that indicates whether email to user should be sent.
  33. /// </summary>
  34. public bool SendWelcomeEmail
  35. {
  36. get
  37. {
  38. return ValidationHelper.GetBoolean(this.GetValue("SendWelcomeEmail"), true);
  39. }
  40. set
  41. {
  42. this.SetValue("SendWelcomeEmail", value);
  43. }
  44. }
  45. /// <summary>
  46. /// Gets or sets registration approval page URL.
  47. /// </summary>
  48. public string ApprovalPage
  49. {
  50. get
  51. {
  52. return DataHelper.GetNotEmpty(this.GetValue("ApprovalPage"), "");
  53. }
  54. set
  55. {
  56. this.SetValue("ApprovalPage", value);
  57. }
  58. }
  59. /// <summary>
  60. /// Gets or sets the sender email (from).
  61. /// </summary>
  62. public string FromAddress
  63. {
  64. get
  65. {
  66. return DataHelper.GetNotEmpty(this.GetValue("FromAddress"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
  67. }
  68. set
  69. {
  70. this.SetValue("FromAddress", value);
  71. }
  72. }
  73. /// <summary>
  74. /// Gets or sets the recipient email (to).
  75. /// </summary>
  76. public string ToAddress
  77. {
  78. get
  79. {
  80. return DataHelper.GetNotEmpty(this.GetValue("ToAddress"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSAdminEmailAddress"));
  81. }
  82. set
  83. {
  84. this.SetValue("ToAddress", value);
  85. }
  86. }
  87. /// <summary>
  88. /// Gets or sets the value that indicates whether after successful registration is
  89. /// notification email sent to the administrator
  90. /// </summary>
  91. public bool NotifyAdministrator
  92. {
  93. get
  94. {
  95. return ValidationHelper.GetBoolean(this.GetValue("NotifyAdministrator"), false);
  96. }
  97. set
  98. {
  99. this.SetValue("NotifyAdministrator", value);
  100. }
  101. }
  102. /// <summary>
  103. /// Gets or sets the message which is displayed after successful registration.
  104. /// </summary>
  105. public string DisplayMessage
  106. {
  107. get
  108. {
  109. return ValidationHelper.GetString(this.GetValue("DisplayMessage"), "");
  110. }
  111. set
  112. {
  113. this.SetValue("DisplayMessage", value);
  114. }
  115. }
  116. /// <summary>
  117. /// Gets or sets the value which enables abitity of new user to set password.
  118. /// </summary>
  119. public bool AllowFormsAuthentication
  120. {
  121. get
  122. {
  123. return ValidationHelper.GetBoolean(GetValue("AllowFormsAuthentication"), false);
  124. }
  125. set
  126. {
  127. SetValue("AllowFormsAuthentication", value);
  128. plcPasswordNew.Visible = value;
  129. }
  130. }
  131. /// <summary>
  132. /// Gets or sets the value which enables abitity join OpenID with existing account.
  133. /// </summary>
  134. public bool AllowExistingUser
  135. {
  136. get
  137. {
  138. return ValidationHelper.GetBoolean(GetValue("AllowExistingUser"), true);
  139. }
  140. set
  141. {
  142. SetValue("AllowExistingUser", value);
  143. plcPasswordNew.Visible = value;
  144. }
  145. }
  146. /// <summary>
  147. /// Gets or sets the default target url (rediredction when the user is logged in).
  148. /// </summary>
  149. public string DefaultTargetUrl
  150. {
  151. get
  152. {
  153. return ValidationHelper.GetString(GetValue("DefaultTargetUrl"), mDefaultTargetUrl);
  154. }
  155. set
  156. {
  157. SetValue("DefaultTargetUrl", value);
  158. mDefaultTargetUrl = value;
  159. }
  160. }
  161. /// <summary>
  162. /// Gets or sets the value which determines the behaviour if no OpenID user stored in SESSION.
  163. /// </summary>
  164. public bool HideForNoOpenID
  165. {
  166. get
  167. {
  168. return ValidationHelper.GetBoolean(GetValue("HideForNoOpenID"), true);
  169. }
  170. set
  171. {
  172. SetValue("HideForNoOpenID", 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 "Methods"
  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.Text = ResHelper.GetString("mem.openid.library");
  232. plcError.Visible = true;
  233. plcContent.Visible = false;
  234. }
  235. // Check if OpenID module is enabled
  236. if (!SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSEnableOpenID") && !this.plcError.Visible)
  237. {
  238. // Error label is displayed only in Design mode
  239. if (CMSContext.ViewMode == ViewModeEnum.Design)
  240. {
  241. StringBuilder parameter = new StringBuilder();
  242. parameter.Append(GetString("header.sitemanager") + " -> ");
  243. parameter.Append(GetString("settingscategory.cmssettings") + " -> ");
  244. parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
  245. parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
  246. parameter.Append(GetString("settingscategory.cmsopenid"));
  247. if (CMSContext.CurrentUser.UserSiteManagerAdmin)
  248. {
  249. // Make it link for SiteManager Admin
  250. parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl("~/CMSSiteManager/default.aspx?section=settings") + "\" target=\"_top\">");
  251. parameter.Append("</a>");
  252. }
  253. lblError.Text = String.Format(GetString("mem.openid.disabled"), parameter.ToString());
  254. plcError.Visible = true;
  255. plcContent.Visible = false;
  256. }
  257. // In other modes is webpart hidden
  258. else
  259. {
  260. this.Visible = false;
  261. }
  262. }
  263. // Display webpart when no error occured
  264. if (!plcError.Visible && this.Visible)
  265. {
  266. if (!CMSContext.CurrentUser.IsAuthenticated())
  267. {
  268. plcPasswordNew.Visible = this.AllowFormsAuthentication;
  269. pnlExistingUser.Visible = this.AllowExistingUser;
  270. // Initialize OpenID session
  271. openIDhelper = new CMSOpenIDHelper();
  272. openIDhelper.Initialize(SessionHelper.GetValue(SESSION_NAME_USERDATA));
  273. userProviderUrl = ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null);
  274. // Check that OpenID is not already registered
  275. if (openIDhelper.GetResponseObject() != null)
  276. {
  277. UserInfo ui = OpenIDUserInfoProvider.GetUserInfoByOpenID(openIDhelper.ClaimedIdentifier);
  278. // OpenID is already registered to some user
  279. if (ui != null)
  280. {
  281. plcContent.Visible = false;
  282. plcError.Visible = true;
  283. lblError.Text = GetString("mem.openid.openidregistered");
  284. }
  285. }
  286. // There is no OpenID response object stored in session - hide all
  287. if (openIDhelper.GetResponseObject() == null && HideForNoOpenID)
  288. {
  289. this.Visible = false;
  290. }
  291. else if (!RequestHelper.IsPostBack())
  292. {
  293. LoadData();
  294. }
  295. }
  296. // Hide webpart for authenticated users
  297. else
  298. {
  299. this.Visible = false;
  300. }
  301. }
  302. }
  303. // Hide control when StopProcessing = TRUE
  304. else
  305. {
  306. this.Visible = false;
  307. }
  308. }
  309. /// <summary>
  310. /// Loads textboxes with provider-supplied data.
  311. /// </summary>
  312. private void LoadData()
  313. {
  314. if (!String.IsNullOrEmpty(openIDhelper.Nickname))
  315. {
  316. txtUserNameNew.Text = txtUserName.Text = openIDhelper.Nickname;
  317. }
  318. if (!String.IsNullOrEmpty(openIDhelper.Email))
  319. {
  320. txtEmail.Text = openIDhelper.Email;
  321. }
  322. }
  323. /// <summary>
  324. /// Handles btnOkExist click, joins existing user with OpenID.
  325. /// </summary>
  326. protected void btnOkExist_Click(object sender, EventArgs e)
  327. {
  328. // OpenID response object must be retrieved from session
  329. if ((openIDhelper != null) && (openIDhelper.GetResponseObject() != null))
  330. {
  331. if (txtUserName.Text != String.Empty)
  332. {
  333. // Try to authenticate user
  334. UserInfo ui = UserInfoProvider.AuthenticateUser(txtUserName.Text, txtPassword.Text, CMSContext.CurrentSiteName);
  335. // Check banned IPs
  336. BannedIPInfoProvider.CheckIPandRedirect(CMSContext.CurrentSiteName, BanControlEnum.Login);
  337. if (ui != null)
  338. {
  339. // Check if user is not already registered with different OpenID provider
  340. string openID = OpenIDUserInfoProvider.GetOpenIDByUserID(ui.UserID);
  341. if (String.IsNullOrEmpty(openID))
  342. {
  343. // Add OpenID token to user
  344. OpenIDUserInfoProvider.AddOpenIDToUser(openIDhelper.ClaimedIdentifier, userProviderUrl, ui.UserID);
  345. // Remove user info from session
  346. SessionHelper.Remove(SESSION_NAME_USERDATA);
  347. SessionHelper.Remove(SESSION_NAME_URL);
  348. // Set authentication cookie and redirect to page
  349. SetAuthCookieAndRedirect(ui);
  350. }
  351. // User is already registered under different OpenID provider
  352. else
  353. {
  354. lblError.Text = GetString("mem.openid.alreadyregistered");
  355. plcError.Visible = true;
  356. }
  357. }
  358. else // Invalid credentials
  359. {
  360. lblError.Text = GetString("Login_FailureText");
  361. plcError.Visible = true;
  362. }
  363. }
  364. else // User did not fill the form
  365. {
  366. lblError.Text = GetString("mem.openid.fillloginform");
  367. plcError.Visible = true;
  368. }
  369. }
  370. }
  371. /// <summary>
  372. /// Handles btnOkNew click, creates new user and joins it with openID token.
  373. /// </summary>
  374. protected void btnOkNew_Click(object sender, EventArgs e)
  375. {
  376. if ((openIDhelper != null) && (openIDhelper.GetResponseObject() != null))
  377. {
  378. // Validate entered values
  379. string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.openid.fillcorrectusername"))
  380. .IsEmail(txtEmail.Text, GetString("mem.openid.fillvalidemail")).Result;
  381. string siteName = CMSContext.CurrentSiteName;
  382. string password = passStrength.Text;
  383. // If password is enabled to set, check it
  384. if (plcPasswordNew.Visible && (errorMessage == String.Empty))
  385. {
  386. if (password == String.Empty)
  387. {
  388. errorMessage = GetString("mem.liveid.specifyyourpass");
  389. }
  390. else if (password != txtConfirmPassword.Text.Trim())
  391. {
  392. errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
  393. }
  394. // Check policy
  395. if (!passStrength.IsValid())
  396. {
  397. errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
  398. }
  399. }
  400. // Check whether email is unique if it is required
  401. if (string.IsNullOrEmpty(errorMessage) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0))
  402. {
  403. errorMessage = GetString("UserInfo.EmailAlreadyExist");
  404. }
  405. // Check reserved names
  406. if (string.IsNullOrEmpty(errorMessage) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim()))
  407. {
  408. errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
  409. }
  410. if (string.IsNullOrEmpty(errorMessage))
  411. {
  412. // Check if user with given username already exists
  413. UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());
  414. // User with given username is already registered
  415. if (ui != null)
  416. {
  417. plcError.Visible = true;
  418. lblError.Text = GetString("mem.openid.usernameregistered");
  419. }
  420. else
  421. {
  422. string error = this.DisplayMessage;
  423. // Register new user
  424. ui = UserInfoProvider.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, true, false, ref error);
  425. this.DisplayMessage = error;
  426. // If user successfuly created
  427. if (ui != null)
  428. {
  429. // Set additional information
  430. ui.UserName = ui.UserNickName = ui.FullName = txtUserNameNew.Text.Trim();
  431. ui.Email = txtEmail.Text;
  432. // Load values submited by OpenID provider
  433. // Load date of birth
  434. if (openIDhelper.BirthDate != DateTime.MinValue)
  435. {
  436. ui.UserSettings.UserDateOfBirth = openIDhelper.BirthDate;
  437. }
  438. // Load default country
  439. if (openIDhelper.Culture != null)
  440. {
  441. ui.PreferredCultureCode = openIDhelper.Culture.Name;
  442. }
  443. // Nick name
  444. if (!String.IsNullOrEmpty(openIDhelper.Nickname))
  445. {
  446. ui.UserSettings.UserNickName = openIDhelper.Nickname;
  447. }
  448. // User gender
  449. if (openIDhelper.UserGender != null)
  450. {
  451. ui.UserSettings.UserGender = (int)openIDhelper.UserGender;
  452. }
  453. UserInfoProvider.SetUserInfo(ui);
  454. // Set password
  455. if (plcPasswordNew.Visible)
  456. {
  457. UserInfoProvider.SetPassword(ui, password);
  458. // If user can choose password then is not considered external(external user can't login in common way)
  459. ui.IsExternal = false;
  460. }
  461. // Additional information which was provided by OpenID provider to user account
  462. // Birth date
  463. if (openIDhelper.BirthDate != DateTime.MinValue)
  464. {
  465. ui.UserSettings.UserDateOfBirth = openIDhelper.BirthDate;
  466. }
  467. // Full name
  468. if (!String.IsNullOrEmpty(openIDhelper.FullName))
  469. {
  470. ui.FullName = openIDhelper.FullName;
  471. }
  472. // Nick name
  473. if (!String.IsNullOrEmpty(openIDhelper.Nickname))
  474. {
  475. ui.UserNickName = openIDhelper.Nickname;
  476. }
  477. // Set user
  478. UserInfoProvider.SetUserInfo(ui);
  479. // Clear used session
  480. SessionHelper.Remove(SESSION_NAME_URL);
  481. SessionHelper.Remove(SESSION_NAME_USERDATA);
  482. UserInfoProvider.SendRegistrationEmails(ui, this.ApprovalPage, password, true, this.SendWelcomeEmail);
  483. // Notify administrator
  484. bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
  485. if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty))
  486. {
  487. UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress);
  488. }
  489. // Log registration into analytics
  490. UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, siteName, ui);
  491. // Log activity
  492. if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserRegistrationEnabled(siteName)
  493. && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser))
  494. {
  495. int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
  496. ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId);
  497. TreeNode currentDoc = CMSContext.CurrentDocument;
  498. ActivityLogProvider.LogRegistrationActivity(contactId,
  499. ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture);
  500. }
  501. // Set authentication cookie and redirect to page
  502. SetAuthCookieAndRedirect(ui);
  503. if (!String.IsNullOrEmpty(this.DisplayMessage))
  504. {
  505. lblInfo.Visible = true;
  506. lblInfo.Text = this.DisplayMessage;
  507. plcForm.Visible = false;
  508. }
  509. else
  510. {
  511. URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
  512. }
  513. }
  514. }
  515. }
  516. // Validation failed - display error message
  517. else
  518. {
  519. lblError.Text = errorMessage;
  520. plcError.Visible = true;
  521. }
  522. }
  523. }
  524. /// <summary>
  525. /// Helper method, set authentication cookie and redirect to return URL or default page.
  526. /// </summary>
  527. /// <param name="ui">User info</param>
  528. private void SetAuthCookieAndRedirect(UserInfo ui)
  529. {
  530. // Create autentification cookie
  531. if (ui.Enabled)
  532. {
  533. UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openidlogin" });
  534. // Log activity
  535. string siteName = CMSContext.CurrentSiteName;
  536. if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName))
  537. {
  538. int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
  539. ActivityLogHelper.UpdateContactLastLogon(contactId);
  540. if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
  541. {
  542. TreeNode currentDoc = CMSContext.CurrentDocument;
  543. ActivityLogProvider.LogLoginActivity(contactId,
  544. ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture);
  545. }
  546. }
  547. string returnUrl = QueryHelper.GetString("returnurl", null);
  548. // Redirect to ReturnURL
  549. if (!String.IsNullOrEmpty(returnUrl))
  550. {
  551. URLHelper.Redirect(ResolveUrl(HttpUtility.UrlDecode(returnUrl)));
  552. }
  553. // Redirect to default page
  554. else if (!String.IsNullOrEmpty(this.DefaultTargetUrl))
  555. {
  556. URLHelper.Redirect(ResolveUrl(this.DefaultTargetUrl));
  557. }
  558. // Otherwise refresh current page
  559. else
  560. {
  561. URLHelper.Redirect(URLRewriter.CurrentURL);
  562. }
  563. }
  564. }
  565. #endregion
  566. }