PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/CMSWebParts/Membership/FacebookConnect/FacebookUsersRequiredData.ascx.cs

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