/// <summary>
        /// Validates wheether the current user and password fits together.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.
        /// </param>
        private static void OnValidate(object source, ServerValidateEventArgs args)
        {
            ICustomerManager<CustomerInfo> customerManager = Ecommerce.Context.Entity.Resolve<ICustomerManager<CustomerInfo>>();
              string username = customerManager.CurrentUser.NickName;

              var provider = new FormsAuthenticationProvider();
              var helper = new AuthenticationHelper(provider);
              args.IsValid = helper.ValidateUser(username, args.Value);
        }
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            Tracing.Information("Simple HTTP endpoint called.");

            var query = request.GetQueryNameValuePairs();
            var auth = new AuthenticationHelper();

            var realm = query.FirstOrDefault(p => p.Key.Equals("realm", System.StringComparison.OrdinalIgnoreCase)).Value;
            var tokenType = query.FirstOrDefault(p => p.Key.Equals("tokenType", System.StringComparison.OrdinalIgnoreCase)).Value;

            if (string.IsNullOrWhiteSpace(realm))
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "realm parameter is missing.");
            }

            EndpointReference appliesTo;
            try
            {
                appliesTo = new EndpointReference(realm);
                Tracing.Information("Simple HTTP endpoint called for realm: " + realm);
            }
            catch
            {
                Tracing.Error("Malformed realm: " + realm);
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "malformed realm name.");
            }

            if (string.IsNullOrWhiteSpace(tokenType))
            {
                tokenType = ConfigurationRepository.Global.DefaultHttpTokenType;
            }

            Tracing.Verbose("Token type: " + tokenType);

            TokenResponse tokenResponse;
            var sts = new STS();
            if (sts.TryIssueToken(appliesTo, ClaimsPrincipal.Current, tokenType, out tokenResponse))
            {
                var resp = request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid request.");
            }
        }
        public ActionResult Index(IndexModel model)
        {
            if (!ModelState.IsValid)
                return View();

            var authenticationHelper = new AuthenticationHelper(_userService);
            try
            {
                authenticationHelper.AuthenticateUser(model.Username, model.Password);
            }
            catch (InvalidUserCredentialsException)
            {
                ModelState.AddModelError("", "Please enter a valid username and password.");
                return View();
            }

            return RedirectToAction("Index", "Account");
        }
示例#4
0
        /// <summary>Gets the new token used for requests authentication.</summary>
        /// <returns>OAuth object with token information.</returns>
        public OAuthTokenDTO CreateToken()
        {
            String urlMethod = this.GetRequestUrl(MethodKey.AuthenticationOAuth);
            String requestType = this.GetRequestType(MethodKey.AuthenticationOAuth);
            Dictionary<String, String> requestData = new Dictionary<String, String>
            {
                { Constants.GRANT_TYPE, Constants.CLIENT_CREDENTIALS }
            };

            RestTool restTool = new RestTool(this._root, false);
            AuthenticationHelper authHelper = new AuthenticationHelper(_root);

            restTool.AddRequestHttpHeader(Constants.HOST, (new Uri(_root.Config.BaseUrl)).Host);
            restTool.AddRequestHttpHeader(Constants.AUTHORIZATION, String.Format("{0} {1}", Constants.BASIC, authHelper.GetHttpHeaderBasicKey()));
            restTool.AddRequestHttpHeader(Constants.CONTENT_TYPE, Constants.APPLICATION_X_WWW_FORM_URLENCODED);

            OAuthTokenDTO response = restTool.Request<OAuthTokenDTO, OAuthTokenDTO>(urlMethod, requestType, requestData);

            return response;
        }
示例#5
0
 public BaseOffice365Helper(AuthenticationHelper authenticationHelper)
 {
     this.AuthenticationHelper = authenticationHelper;
 }
示例#6
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // Email format validation
        string emailAddress = txtEmailAddress.Text.Trim();

        if (!String.IsNullOrEmpty(emailAddress) && !ValidationHelper.IsEmail(emailAddress))
        {
            ShowError(GetString("Administration-User_New.WrongEmailFormat"));
            return;
        }

        // Find whether user name is valid
        string result = null;

        if (!ucUserName.IsValid())
        {
            result = ucUserName.ValidationError;
        }

        // Additional validation
        if (String.IsNullOrEmpty(result))
        {
            result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result;
        }

        userName = ValidationHelper.GetString(ucUserName.Value, String.Empty).Trim();

        // Check if user with the same user name exists
        if (UserInfoProvider.GetUserInfo(userName) != null)
        {
            ShowError(GetString("Administration-User_New.UserExists"));
            return;
        }

        SiteInfo siteInfo = SiteContext.CurrentSite;

        // Check if username with site prefix exists on current site
        var userNameWithPrefix = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, siteInfo));

        if (userNameWithPrefix != null)
        {
            ShowError(GetString("Administration-User_New.siteprefixeduserexists"));
            return;
        }

        // If site prefixed allowed - add site prefix to user name
        if (((SiteID != 0) || (chkAssignToSite.Checked && AllowAssignToWebsite)) && UserInfoProvider.UserNameSitePrefixEnabled(siteInfo.SiteName))
        {
            if (!UserInfoProvider.IsSitePrefixedUser(userName))
            {
                userName = UserInfoProvider.EnsureSitePrefixUserName(userName, siteInfo);
            }
        }
        // User without site prefix is going to be created -> check if site prefixed user does not exist in solution
        else if (!UserInfoProvider.IsUserNamePrefixUnique(userName, 0))
        {
            ShowError(GetString("Administration-User_New.siteprefixeduserexists"));
            return;
        }

        if (String.IsNullOrEmpty(result))
        {
            if (txtConfirmPassword.Text == passStrength.Text)
            {
                // Check whether password is valid according to policy
                if (passStrength.IsValid())
                {
                    int userId = SaveNewUser();
                    if (userId != -1)
                    {
                        var uiElementUrl = UIContextHelper.GetElementUrl("CMS.Users", QueryHelper.GetString("editelem", ""), false);
                        var url          = URLHelper.AppendQuery(uiElementUrl, "siteid=" + SiteID + "&objectid=" + userId);
                        URLHelper.Redirect(url);
                    }
                }
                else
                {
                    ShowError(AuthenticationHelper.GetPolicyViolationMessage(siteInfo.SiteName));
                }
            }
            else
            {
                ShowError(GetString("Administration-User_Edit_Password.PasswordsDoNotMatch"));
            }
        }
        else
        {
            ShowError(result);
        }
    }
示例#7
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            SetContext();

            GroupInfo group = CommunityContext.CurrentGroup;
            if (group != null)
            {
                string path = (GroupsSecurityAccessPath == "") ? GroupInfoProvider.GetGroupSecurityAccessPath(group.GroupName, SiteContext.CurrentSiteName) : GroupsSecurityAccessPath;
                string url  = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(path)));
                if (UseQueryString)
                {
                    url = URLHelper.UpdateParameterInUrl(url, "groupid", group.GroupID.ToString());
                }

                // Check whether group is approved
                if (!group.GroupApproved)
                {
                    URLHelper.Redirect(url);
                }
                else
                {
                    // Check permissions for current user
                    switch (group.GroupAccess)
                    {
                    // Anybody can view the content
                    default:
                    case SecurityAccessEnum.AllUsers:
                        break;

                    // Site members can view the content
                    case SecurityAccessEnum.AuthenticatedUsers:
                        if (!AuthenticationHelper.IsAuthenticated())
                        {
                            URLHelper.Redirect(url);
                        }
                        break;

                    // Only group members can view the content
                    case SecurityAccessEnum.GroupMembers:
                        if (!MembershipContext.AuthenticatedUser.IsGroupMember(group.GroupID))
                        {
                            URLHelper.Redirect(url);
                        }
                        break;
                    }
                }
            }
            else
            {
                Visible = false;
            }

            ReleaseContext();
        }
    }
示例#8
0
        /// <summary>
        /// Creates a list of form instances stored on disk for a given partyId and serviceId
        /// </summary>
        /// <param name="partyId">The partyId</param>
        /// <param name="org">The Organization code for the service owner</param>
        /// <param name="service">The service code for the current service</param>
        /// <param name="edition">The edition code for the current service</param>
        /// <returns>The service instance list</returns>
        public List <ServiceInstance> GetFormInstances(int partyId, string org, string service, string edition)
        {
            List <ServiceInstance> formInstances = new List <ServiceInstance>();
            string formDataFilePath  = _settings.GetEditionPath(org, service, edition, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + "Testdataforparty/" + partyId;
            string archiveFolderPath = formDataFilePath + "/Archive/";

            if (!Directory.Exists(archiveFolderPath))
            {
                Directory.CreateDirectory(archiveFolderPath);
            }

            string[] files = Directory.GetFiles(formDataFilePath);

            foreach (string file in files)
            {
                if (int.TryParse(Path.GetFileNameWithoutExtension(file), out int instanceId))
                {
                    ServiceInstance serviceInstance = new ServiceInstance()
                    {
                        ServiceInstanceID = instanceId,
                        LastChanged       = File.GetLastWriteTime(file)
                    };

                    string archiveFilePath = archiveFolderPath + "/" + serviceInstance.ServiceInstanceID + ".xml";

                    if (File.Exists(archiveFilePath))
                    {
                        serviceInstance.LastChanged = File.GetLastWriteTime(archiveFilePath);
                        serviceInstance.IsArchived  = true;
                    }

                    formInstances.Add(serviceInstance);
                }
            }

            return(formInstances);
        }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with openID token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (response != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.openid.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.openid.fillvalidemail")).Result;
            string siteName = SiteContext.CurrentSiteName;
            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (errorMessage == String.Empty))
            {
                if (password == String.Empty)
                {
                    errorMessage = GetString("mem.liveid.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if (string.IsNullOrEmpty(errorMessage) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if (string.IsNullOrEmpty(errorMessage) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (string.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    string error = DisplayMessage;
                    // Register new user
                    ui             = AuthenticationHelper.AuthenticateOpenIDUser((string)response["ClaimedIdentifier"], ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, true, false, ref error);
                    DisplayMessage = error;

                    // If user successfully created
                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = ui.FullName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        // Load values submitted by OpenID provider
                        // Load date of birth
                        DateTime birthdate = (DateTime)response["BirthDate"];
                        if (birthdate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = birthdate;
                        }
                        // Load default country
                        var culture = (System.Globalization.CultureInfo)response["Culture"];
                        if (culture != null)
                        {
                            ui.PreferredCultureCode = culture.Name;
                        }
                        // Nick name
                        string nick = (string)response["Nickname"];
                        if (!String.IsNullOrEmpty(nick))
                        {
                            ui.UserSettings.UserNickName = nick;
                        }
                        // Full name
                        string full = (string)response["FullName"];
                        if (!String.IsNullOrEmpty(full))
                        {
                            ui.FullName = full;
                        }
                        // User gender
                        var gender = (int?)response["UserGender"];
                        if (gender != null)
                        {
                            ui.UserSettings.UserGender = (int)gender;
                        }
                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        // Set user
                        UserInfoProvider.SetUserInfo(ui);

                        // Clear used session
                        SessionHelper.Remove(SESSION_NAME_URL);
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, true, SendWelcomeEmail);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect("~/Default.aspx");
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
示例#10
0
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(mLinkedInProfile?.Id))
        {
            string currentSiteName = SiteContext.CurrentSiteName;

            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.linkedin.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.linkedin.fillvalidemail")).Result;

            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (String.IsNullOrEmpty(errorMessage)))
            {
                if (String.IsNullOrEmpty(password))
                {
                    errorMessage = GetString("mem.linkedin.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if ((String.IsNullOrEmpty(errorMessage)) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), currentSiteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if ((String.IsNullOrEmpty(errorMessage)) && UserInfoProvider.NameIsReserved(currentSiteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (String.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = DisplayMessage;
                    ui             = AuthenticationHelper.AuthenticateLinkedInUser(mLinkedInProfile.Id, mLinkedInProfile.LocalizedFirstName, mLinkedInProfile.LocalizedLastName, currentSiteName, true, false, ref error);
                    DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        var birthDate = mLinkedInProfile.BirthDate?.ToDateTime();

                        if (birthDate.HasValue && birthDate.Value != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = birthDate.Value;
                        }

                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Send registration e-mails
                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, true, SendWelcomeEmail);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(currentSiteName, ui, TrackConversionName, ConversionValue);

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect("~/Default.aspx");
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
 private void CreateTicket(Kullanici kullanici)
 {
     AuthenticationHelper.CreateAuthCookie(kullanici.KullaniciAdi, kullanici.Id,
                                           kullanici.KullaniciRolleri.Select(s => s.Rol.RolAdi).ToArray());
 }
示例#13
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData()
    {
        friendsListElem.StopProcessing           = true;
        friendsToApprovalListElem.StopProcessing = true;
        friendsRequestedListElem.StopProcessing  = true;
        friendsRejectedListElem.StopProcessing   = true;
        friendsRejectedListElem.UseEncapsulation = false;

        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Show content only for authenticated users
            if (AuthenticationHelper.IsAuthenticated())
            {
                // Set up controls
                friendsListElem.UserID           = UserID;
                friendsToApprovalListElem.UserID = UserID;
                friendsRequestedListElem.UserID  = UserID;
                friendsRejectedListElem.UserID   = UserID;

                // Remove 'saved' parameter from querystring
                string absoluteUri = RequestContext.CurrentURL;

                // Menu initialization
                tabMenu.TabControlIdPrefix = "MyFriends";
                tabMenu.UrlTarget          = "_self";

                if (DisplayFriendsRequested)
                {
                    tabMenu.AddTab(new TabItem
                    {
                        Text        = GetString("friends.requestedfriendships"),
                        RedirectUrl = URLHelper.AddParameterToUrl(absoluteUri, ParameterName, "requested")
                    });
                    selectedPage = "requested";
                }

                if (DisplayFriendsRejected)
                {
                    tabMenu.AddTab(new TabItem
                    {
                        Text        = GetString("friends.rejectedfriends"),
                        RedirectUrl = URLHelper.AddParameterToUrl(absoluteUri, ParameterName, "rejected")
                    });
                    selectedPage = "rejected";
                }

                if (DisplayFriendsList)
                {
                    tabMenu.AddTab(new TabItem
                    {
                        Text        = GetString("friends.myfriends"),
                        RedirectUrl = URLHelper.AddParameterToUrl(absoluteUri, ParameterName, "friends")
                    });
                    selectedPage = "friends";
                }

                // Set css class
                pnlBody.CssClass = CssClass;

                // Get page url
                page = QueryHelper.GetText(ParameterName, selectedPage);

                // Set controls visibility
                plcFriends.Visible              = false;
                plcApprovalFriends.Visible      = false;
                plcRequestedFriends.Visible     = false;
                friendsRejectedListElem.Visible = false;
                requestFriendshipElem1.UserID   = UserID;
                requestFriendshipElem2.UserID   = UserID;
                // Select current page
                switch (page)
                {
                default:
                case "friends":
                    tabMenu.SelectedTab = 2;
                    if (DisplayFriendsList)
                    {
                        plcFriends.Visible             = true;
                        friendsListElem.StopProcessing = false;
                    }
                    if (DisplayFriendsToApproval)
                    {
                        plcApprovalFriends.Visible = true;
                        friendsToApprovalListElem.StopProcessing = false;
                    }
                    break;

                case "requested":
                    tabMenu.SelectedTab                     = 0;
                    plcRequestedFriends.Visible             = true;
                    friendsRequestedListElem.StopProcessing = false;
                    break;

                case "rejected":
                    tabMenu.SelectedTab                    = 1;
                    friendsRejectedListElem.Visible        = true;
                    friendsRejectedListElem.StopProcessing = false;
                    break;
                }
            }
            else
            {
                Visible = false;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (!StopProcessing)
        {
            plcError.Visible = false;

            // Check if LinkedIn module is enabled
            if (!LinkedInHelper.LinkedInIsAvailable(SiteContext.CurrentSiteName) && !plcError.Visible)
            {
                // Error label is displayed only in Design mode
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmslinkedin"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(ApplicationUrlHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text      = String.Format(GetString("mem.linkedin.disabled"), parameter);
                    plcError.Visible   = true;
                    plcContent.Visible = false;
                }
                // In other modes is web part hidden
                else
                {
                    Visible = false;
                }
            }

            // Display web part when no error occurred
            if (!plcError.Visible && Visible)
            {
                // Hide web part if user is authenticated
                if (AuthenticationHelper.IsAuthenticated())
                {
                    Visible = false;
                    return;
                }

                plcPasswordNew.Visible  = AllowFormsAuthentication;
                pnlExistingUser.Visible = AllowExistingUser;

                SetLinkedInProfileFromSession();

                // There is no LinkedIn profile stored in session - hide all
                if (mLinkedInProfile == null && HideForNoLinkedInUserID)
                {
                    Visible = false;
                }
                else if (!RequestHelper.IsPostBack())
                {
                    LoadData();
                }
            }
        }
        else
        {
            Visible = false;
        }
    }
示例#15
0
        /// <summary>
        /// Зарегистрировать клиент.
        /// </summary>
        public static void Initialize()
        {
            LocalizationManager.Instance.AssignCurrentCulture();

            // Управление кэшами.
            var cacheConfigProvider = new CacheConfigProvider(null);

            Dependency.RegisterInstance <ICacheManager>(new CacheManagerImplementation(cacheConfigProvider));

            // Плагины.
            Dependency.RegisterInstance <Sungero.Plugins.IPluginManager>(new Sungero.Plugins.PluginManager(new Sungero.Domain.Client.ClientPluginDiscoverer(), new Sungero.Plugins.PluginSettingsLoader()));

            ServiceContext.Instance.ApplicationExit += (s, a) => { throw a.Exception; };
            if (UserCredentialsManager.IsRegistered)
            {
                return;
            }

            // Перенаправление вывода, чтобы не писать лишнюю информацию на экран.
            var consoleOut = Console.Out;

            try
            {
                Console.SetOut(System.IO.TextWriter.Null);
                Sungero.Domain.Client.SystemInfo.Tenant = CommandLine.options.Tenant;
                AuthenticationHelper.Register(CommandLine.options, false);
                Console.SetOut(consoleOut);
            }
            catch (InvalidSecurityException ex)
            {
                Console.SetOut(consoleOut);
                throw new InvalidSecurityException(ex.IsInternal, new LocalizedString("No access rights to the system - invalid username or password."), ex);
            }
            catch (Exception)
            {
                Console.SetOut(consoleOut);
                throw;
            }

            #region Загрузка модулей.

            ClientDevelopmentUpdater.Instance.RefreshDevelopment();
            MetadataService.ConfigurationSettingsPaths = new Sungero.Domain.ClientConfigurationSettingsPaths();
            ClientLazyAssembliesResolver.Instance.LinkToAssembliesFolder(ClientDevelopmentUpdater.Instance.CacheFolder);

            var baseDirectory        = AppDomain.CurrentDomain.BaseDirectory;
            var developmentDirectory = ClientDevelopmentUpdater.Instance.CacheFolder;

            Dependency.RegisterType <IClientLinqExtensions, ClientLinqExtensionsService>();
            Dependency.RegisterType <IHyperlinkEntityCache, HyperlinkEntityCacheImplementer>();
            Dependency.RegisterType <IHyperlinkDisplayTextCache, HyperlinkDisplayTextCacheImplementer>();

            LoadModules(baseDirectory, "*Client.dll");
            LoadModules(developmentDirectory, null);

            EntityFactory.ConfigureUnityContainer();

            #endregion

            var tenantCulture = TenantInfo.Culture;
            if (!LocalizationManager.Instance.ClientUICulture.Equals(tenantCulture))
            {
                Log.WarnFormat("Client culture changed to {0}", tenantCulture);
                LocalizationManager.Instance.SetSystemLanguage(tenantCulture.Name);
                LocalizationManager.Instance.AssignCurrentCulture();
                Cleanup();
                AuthenticationHelper.Register(CommandLine.options, false);
            }
        }
    /// <summary>
    /// Sends confirmation or welcome email.
    /// </summary>
    private void SendRegistrationEmail(UserInfo ui)
    {
        bool error = false;
        EmailTemplateInfo template = null;

        // Email message
        EmailMessage emailMessage = new EmailMessage();

        emailMessage.EmailFormat = EmailFormatEnum.Default;
        emailMessage.Recipients  = ui.Email;
        emailMessage.From        = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSNoreplyEmailAddress");

        // Send welcome message with username and password, with confirmation link, user must confirm registration
        if (ConfirmationRequired)
        {
            template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CurrentSiteName);
            emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
        }
        // Send welcome message with username and password, with information that user must be approved by administrator
        else if (SendWelcomeEmail)
        {
            if (AdminApprovalRequired)
            {
                template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CurrentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
            }
            // Send welcome message with username and password, user can logon directly
            else
            {
                template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CurrentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
            }
        }

        if (template != null)
        {
            // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required)
            int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
            if (contactId > 0)
            {
                ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId);
            }

            try
            {
                // Prepare resolver for notification and welcome emails
                MacroResolver resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, CurrentSiteName, NotifyAdministrator));
                EmailSender.SendEmailWithTemplateText(CurrentSiteName, emailMessage, template, resolver, true);
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                error = true;
            }
        }

        // If there was some error, user must be deleted
        if (error)
        {
            ShowError(GetString("RegistrationForm.UserWasNotCreated"));

            // Email was not send, user can't be approved - delete it
            UserInfoProvider.DeleteUser(ui);
        }
    }
    void formUser_OnAfterSave(object sender, EventArgs e)
    {
        // Get user info from form
        UserInfo ui = (UserInfo)formUser.Data;

        // Add user prefix if settings is on
        // Ensure site prefixes
        if (UserInfoProvider.UserNameSitePrefixEnabled(CurrentSiteName))
        {
            ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(ui.UserName, SiteContext.CurrentSite);
        }

        ui.Enabled         = EnableUserAfterRegistration;
        ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
        ui.UserCampaign    = Service <ICampaignService> .Entry().CampaignCode;

        ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;

        // Fill optionally full user name
        if (String.IsNullOrEmpty(ui.FullName))
        {
            ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
        }

        // Ensure nick name
        if (ui.UserNickName.Trim() == String.Empty)
        {
            ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
        }

        ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
        ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
        ui.UserSettings.UserLogActivities        = true;
        ui.UserSettings.UserShowIntroductionTile = true;

        // Check whether confirmation is required
        if (!ConfirmationRequired)
        {
            // If confirmation is not required check whether administration approval is required
            if (AdminApprovalRequired)
            {
                ui.Enabled = false;
                ui.UserSettings.UserWaitingForApproval = true;
            }
        }
        else
        {
            // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable
            ui.Enabled = false;
        }

        // Set user's starting alias path
        if (!String.IsNullOrEmpty(StartingAliasPath))
        {
            ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
        }

        // Get user password and save it in appropriate format after form save
        string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);

        UserInfoProvider.SetPassword(ui, password);

        if (!ConfirmationRequired)
        {
            SendAdminNotification(ui);
            LogOMActivity(ui);
        }

        SendRegistrationEmail(ui);
        LogWebAnalytics(ui);
        AssignToRoles(ui);

        if (ui.Enabled)
        {
            // Authenticate currently created user
            AuthenticationHelper.AuthenticateUser(ui.UserName, true);
        }

        var displayMessage = DisplayMessage.Trim();

        if (!String.IsNullOrEmpty(displayMessage))
        {
            ShowInformation(displayMessage);
        }
        else
        {
            if (RedirectToURL != String.Empty)
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL));
            }

            string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty);
            if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWith("~", StringComparison.Ordinal) || returnUrl.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath")))
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(HttpUtility.UrlDecode(returnUrl)));
            }
        }

        // Hide registration form
        pnlRegForm.Visible = false;
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Public user is not allowed for widgets
        if (!AuthenticationHelper.IsAuthenticated())
        {
            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
        }

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        if ((widgetId != string.Empty) && (aliasPath != string.Empty))
        {
            // Get page info
            var      siteName = SiteContext.CurrentSiteName;
            PageInfo pi       = PageInfoProvider.GetPageInfo(siteName, aliasPath, LocalizationContext.PreferredCultureCode, null, SiteInfoProvider.CombineWithDefaultCulture(siteName));

            if (pi == null)
            {
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            // Get widget from instance
            WidgetInfo wi = null;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGuid, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }


            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    var currentUser = MembershipContext.AuthenticatedUser;

                    bool checkSecurity = true;

                    // Check security
                    // It is group zone type but widget is not allowed in group
                    if (zone.WidgetZoneType == WidgetZoneTypeEnum.Group)
                    {
                        // Should always be, only group widget are allowed in group zone
                        if (wi.WidgetForGroup)
                        {
                            if (!currentUser.IsGroupAdministrator(pi.NodeGroupID))
                            {
                                RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                            }

                            // All ok, don't check classic security
                            checkSecurity = false;
                        }
                    }

                    if (checkSecurity && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }
            }
        }
        // If all ok, set up frames
        rowsFrameset.Attributes.Add("rows", string.Format("{0}, *", TitleOnlyHeight));

        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + RequestContext.CurrentQueryString);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + RequestContext.CurrentQueryString);
        }
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        SessionHelper.SetValue("ConditionBuilderCondition" + ClientID, EditorValue);

        string dialogUrl = String.Format("{0}?clientid={1}&module={2}&ruletype={3}&showglobal={4}", AuthenticationHelper.ResolveDialogUrl("~/CMSFormControls/Macros/ConditionBuilder.aspx"), ClientID, RuleCategoryNames, DisplayRuleType, ShowGlobalRules ? "1" : "0");

        if (!string.IsNullOrEmpty(ResolverName))
        {
            SessionHelper.SetValue("ConditionBuilderResolver" + ClientID, ResolverName);
        }
        if (!string.IsNullOrEmpty(DefaultConditionText))
        {
            SessionHelper.SetValue("ConditionBuilderDefaultText" + ClientID, DefaultConditionText);
        }

        ScriptHelper.RegisterStartupScript(Page, typeof(string), "ConditionBuilderDialog", "modalDialog('" + dialogUrl + "', 'editmacrocondition', '95%', 700);", true);
    }
示例#20
0
    /// <summary>
    /// Click event of btnOk.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Arguments</param>
    protected void btnReset_Click(object sender, EventArgs e)
    {
        if ((passStrength.Text.Length > 0) && rfvConfirmPassword.IsValid)
        {
            if (passStrength.Text == txtConfirmPassword.Text)
            {
                // Check policy
                if (passStrength.IsValid())
                {
                    // Check if password expired
                    if (pwdExp > 0)
                    {
                        UserInfo ui = UserInfoProvider.GetUserInfo(userID);
                        if (!UserInfoProvider.IsUserPasswordDifferent(ui, passStrength.Text))
                        {
                            ShowError(GetString("passreset.newpasswordrequired"));
                            return;
                        }
                    }

                    // Get e-mail address of sender
                    string emailFrom = DataHelper.GetNotEmpty(SendEmailFrom, SettingsKeyProvider.GetStringValue(siteName + ".CMSSendPasswordEmailsFrom"));

                    // Try to reset password and show result to user
                    bool   success;
                    string resultText = AuthenticationHelper.ResetPassword(hash, time, userID, interval, passStrength.Text, "Reset password control", emailFrom, siteName, null, out success, InvalidRequestText, ExceededIntervalText, returnUrl);

                    // If password reset was successful
                    if (success)
                    {
                        SessionHelper.Remove("UserPasswordRequestID");

                        // Redirect to specified URL
                        if (!string.IsNullOrEmpty(RedirectUrl))
                        {
                            URLHelper.Redirect(RedirectUrl);
                        }

                        // Get proper text
                        ShowConfirmation(DataHelper.GetNotEmpty(SuccessText, resultText));
                        pnlReset.Visible  = false;
                        lblLogonLink.Text = string.Format(GetString("memberhsip.logonlink"), returnUrl);
                    }
                    else
                    {
                        ShowError(resultText);
                    }
                }
                else
                {
                    ShowError(AuthenticationHelper.GetPolicyViolationMessage(CMSContext.CurrentSiteName));
                }
            }
            else
            {
                ShowError(GetString("passreset.notmatch"));
            }
        }
        else
        {
            ShowError(GetString("general.requiresvalue"));
        }
    }
示例#21
0
        /// <summary>
        /// Method that checks if there is a newer version of the workflow file and updates it if there are
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="app">Application identifier which is unique within an organisation.</param>
        private void CheckAndUpdateWorkflowFile(string org, string app)
        {
            string workflowFullFilePath = _serviceRepositorySettings.GetWorkflowPath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + _serviceRepositorySettings.WorkflowFileName;
            string templateWorkflowData = System.IO.File.ReadAllText(_generalSettings.WorkflowTemplate, Encoding.UTF8);

            if (!System.IO.File.Exists(workflowFullFilePath))
            {
                // Create the workflow folder
                Directory.CreateDirectory(_serviceRepositorySettings.GetWorkflowPath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)));
                System.IO.File.WriteAllText(workflowFullFilePath, templateWorkflowData, Encoding.UTF8);
            }
            else
            {
                if (ShouldUpdateFile(workflowFullFilePath, templateWorkflowData))
                {
                    // Overwrite existing file
                    System.IO.File.WriteAllText(workflowFullFilePath, templateWorkflowData, Encoding.UTF8);
                }
            }
        }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (!StopProcessing)
        {
            plcError.Visible = false;

            // Check renamed DLL library
            if (!SystemContext.IsFullTrustLevel)
            {
                // Error label is displayed when OpenID library is not enabled
                lblError.Text      = ResHelper.GetString("socialnetworking.fulltrustrequired");
                plcError.Visible   = true;
                plcContent.Visible = false;
            }

            // Check if OpenID module is enabled
            if (!SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOpenID") && !plcError.Visible)
            {
                // Error label is displayed only in Design mode
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsopenid"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(ApplicationUrlHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text      = String.Format(GetString("mem.openid.disabled"), parameter.ToString());
                    plcError.Visible   = true;
                    plcContent.Visible = false;
                }
                // In other modes is webpart hidden
                else
                {
                    Visible = false;
                }
            }

            // Display webpart when no error occured
            if (!plcError.Visible && Visible)
            {
                if (!AuthenticationHelper.IsAuthenticated())
                {
                    plcPasswordNew.Visible  = AllowFormsAuthentication;
                    pnlExistingUser.Visible = AllowExistingUser;

                    // Initialize OpenID session
                    response = (Dictionary <string, object>)SessionHelper.GetValue(SESSION_NAME_USERDATA);

                    userProviderUrl = ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null);

                    // Check that OpenID is not already registered
                    if (response != null)
                    {
                        UserInfo ui = OpenIDUserInfoProvider.GetUserInfoByOpenID((string)response["ClaimedIdentifier"]);

                        // OpenID is already registered to some user
                        if (ui != null)
                        {
                            plcContent.Visible = false;
                            plcError.Visible   = true;
                            lblError.Text      = GetString("mem.openid.openidregistered");
                        }
                    }

                    // There is no OpenID response object stored in session - hide all
                    if (response == null)
                    {
                        if (HideForNoOpenID)
                        {
                            Visible = false;
                        }
                    }
                    else if (!RequestHelper.IsPostBack())
                    {
                        LoadData();
                    }
                }
                // Hide webpart for authenticated users
                else
                {
                    Visible = false;
                }
            }
        }
        // Hide control when StopProcessing = TRUE
        else
        {
            Visible = false;
        }
    }
示例#23
0
        /// <inheritdoc/>
        public async Task <SearchResults> SearchRepository(bool onlyAdmin, string keyWord, int page)
        {
            User user = GetCurrentUser().Result;

            SearchResults repository = null;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SearchResults));

            Uri giteaUrl = new Uri(GetApiBaseUrl() + "/repos/search?");

            giteaUrl = new Uri(giteaUrl.OriginalString + "limit=" + _settings.RepoSearchPageCount);

            if (onlyAdmin)
            {
                giteaUrl = new Uri(giteaUrl.OriginalString + "&uid=" + user.Id);
            }

            if (!string.IsNullOrEmpty(keyWord))
            {
                giteaUrl = new Uri(giteaUrl.OriginalString + "&q=" + keyWord);
            }

            using (HttpClient client = GetApiClient())
            {
                bool allElementsRetrieved = false;

                int resultPage = 1;
                if (page != 0)
                {
                    resultPage = page;
                }

                int totalCount = 0;

                while (!allElementsRetrieved)
                {
                    Uri tempUrl = new Uri(giteaUrl.OriginalString + "&page=" + resultPage);

                    HttpResponseMessage response = await client.GetAsync(tempUrl);

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        Stream stream = await response.Content.ReadAsStreamAsync();

                        if (resultPage == 1 || page == resultPage)
                        {
                            // This is the first or a specific page requested
                            repository = serializer.ReadObject(stream) as SearchResults;
                        }
                        else
                        {
                            SearchResults pageResultRepository = serializer.ReadObject(stream) as SearchResults;
                            repository.Data.AddRange(pageResultRepository.Data);
                        }

                        IEnumerable <string> values;
                        if (response.Headers.TryGetValues("X-Total-Count", out values))
                        {
                            totalCount = Convert.ToInt32(values.First());
                        }

                        if (page == resultPage ||
                            (repository != null && repository.Data != null && repository.Data.Count >= totalCount) ||
                            (repository != null && repository.Data != null && repository.Data.Count >= _settings.RepoSearchPageCount))
                        {
                            allElementsRetrieved = true;
                        }
                        else
                        {
                            resultPage++;
                        }
                    }
                    else
                    {
                        _logger.LogError("User " + AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext) + " SearchRepository failed with statuscode " + response.StatusCode);
                        allElementsRetrieved = true;
                    }
                }
            }

            if (repository != null && repository.Data.Any())
            {
                foreach (Repository repo in repository.Data)
                {
                    if (repo.Owner != null && !string.IsNullOrEmpty(repo.Owner.Login))
                    {
                        repo.IsClonedToLocal = IsLocalRepo(repo.Owner.Login, repo.Name);
                        Organization org = await GetCachedOrg(repo.Owner.Login);

                        if (org != null)
                        {
                            repo.Owner.UserType = UserType.Org;
                        }
                    }
                }
            }

            return(repository);
        }
示例#24
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                string siteName = SiteContext.CurrentSiteName;
                if (!string.IsNullOrEmpty(siteName))
                {
                    // Get LiveID settings
                    string appId  = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationID");
                    string secret = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationSecret");

                    if (!WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Add windows live ID script
                        ScriptHelper.RegisterClientScriptInclude(Page, typeof(string), "WLScript", LIVE_CONNECT_API_URL);

                        btnHidden.Visible = true;

                        // Add login functions
                        String loginLiveIDClientScript = @"

                            function signUserIn() {
                                WL.login({ scope: 'wl.signin' });
                            }
                    
                            function refreshLiveID(param)
                            {
                                " + ControlsHelper.GetPostBackEventReference(btnHidden, "#").Replace("'#'", "param") + @" 
                            }                                       
                        ";

                        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ClientInitLiveIDScript", ScriptHelper.GetScript(loginLiveIDClientScript));
                    }

                    // Check valid Windows LiveID parameters
                    if ((appId == string.Empty) || (secret == string.Empty))
                    {
                        lblError.Visible = true;
                        lblError.Text    = GetString("liveid.incorrectsettings");
                        return;
                    }

                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);
                    var designMode       = PortalContext.IsDesignMode(ViewMode);

                    // If user is already authenticated
                    if (AuthenticationHelper.IsAuthenticated())
                    {
                        // Signout is visible when ShowSignOut set to true and user has LiveID registered (ignored on design mode)
                        if ((ShowSignOut && !String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.WindowsLiveID)) || designMode)
                        {
                            // Get data from auth cookie
                            string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie();

                            // Check if user has truly logged in by LiveID (ignored on design mode)
                            if (((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0)) || designMode)
                            {
                                // Redirect to Windows Live and back to "home" page
                                string defaultAliasPath = SettingsKeyInfoProvider.GetValue(siteName + ".CMSDefaultAliasPath");
                                string url    = DocumentURLProvider.GetUrl(defaultAliasPath);
                                string navUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url));

                                // If text is set use text/button link
                                if (!string.IsNullOrEmpty(SignOutText))
                                {
                                    // Button link
                                    if (ShowAsButton)
                                    {
                                        btnSignOut.CommandArgument = navUrl;
                                        btnSignOut.Text            = SignOutText;
                                        btnSignOut.Visible         = true;
                                    }
                                    // Text link
                                    else
                                    {
                                        btnSignOutLink.CommandArgument = navUrl;
                                        btnSignOutLink.Text            = SignOutText;
                                        btnSignOutLink.Visible         = true;
                                    }
                                }
                                // Image link
                                else
                                {
                                    btnSignOutImage.CommandArgument = navUrl;
                                    btnSignOutImage.ImageUrl        = ResolveUrl(SignOutImageURL);
                                    btnSignOutImage.Visible         = true;
                                    btnSignOut.Text = GetString("webparts_membership_signoutbutton.signout");
                                }
                            }
                        }
                        else
                        {
                            Visible = false;
                        }
                    }
                    // Sign In
                    else
                    {
                        // Create return URL
                        string returnUrl = QueryHelper.GetText("returnurl", null);

                        if (!URLHelper.IsLocalUrl(returnUrl))
                        {
                            returnUrl = RequestContext.CurrentURL;
                        }

                        // Create parameters for LiveID request URL
                        String[] parameters = new String[3];
                        parameters[0] = returnUrl;
                        parameters[1] = TrackConversionName;
                        parameters[2] = ConversionValue.ToString();
                        SessionHelper.SetValue("LiveIDInformtion", parameters);

                        returnUrl = wll.GetLoginUrl();

                        // Get App ID
                        appId = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationID");

                        // Create full LiveID request URL
                        string navUrl = AUTHORIZATION_URL + "?client_id=" + appId + "&redirect=true&scope=wl.signin&response_type=code&redirect_uri=" + HttpUtility.UrlEncode(returnUrl);

                        // If text is set use text/button link
                        if (!string.IsNullOrEmpty(SignInText))
                        {
                            // Button link
                            if (ShowAsButton)
                            {
                                AssignButtonControl(navUrl, returnUrl, appId);
                                btnSignIn.Text = SignInText;
                            }
                            // Text link
                            else
                            {
                                AssignHyperlinkControl(navUrl, returnUrl, appId);
                                lnkSignIn.Text = SignInText;
                            }
                        }
                        // Image link
                        else
                        {
                            AssignHyperlinkControl(navUrl, returnUrl, appId);
                            lnkSignIn.ImageUrl = ResolveUrl(SignInImageURL);
                            lnkSignIn.Text     = GetString("webparts_membership_signoutbutton.signin");
                        }
                    }
                }
            }
            else
            {
                // Error label is displayed in Design mode when Windows Live ID is disabled
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmswindowsliveid"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(ApplicationUrlHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text    = String.Format(GetString("mem.liveid.disabled"), parameter);
                    lblError.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
示例#25
0
        private HttpClient GetApiClient(bool allowAutoRedirect = true)
        {
            HttpClientHandler httpClientHandler = new HttpClientHandler();

            httpClientHandler.AllowAutoRedirect = allowAutoRedirect;

            HttpClient client = new HttpClient(httpClientHandler);

            client.DefaultRequestHeaders.Add(Constants.General.AuthorizationTokenHeaderName, AuthenticationHelper.GetDeveloperTokenHeaderValue(_httpContextAccessor.HttpContext));
            return(client);
        }
示例#26
0
 public void TestInitialize()
 {
     AuthenticationHelper.Authenticate();
 }
示例#27
0
        /// <summary>
        /// Generates a new service instanceID for a service.
        /// </summary>
        /// <returns>A new instanceId.</returns>
        public async Task <Guid> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid   instanceId         = Guid.NewGuid();
            string applicationId      = startServiceModel.Service;
            string applicationOwnerId = startServiceModel.Org;
            int    instanceOwnerId    = startServiceModel.ReporteeID;

            Instance instance = new Instance
            {
                Id = instanceId.ToString(),
                InstanceOwnerId = instanceOwnerId.ToString(),
                ApplicationId   = applicationId,
                CreatedBy       = instanceOwnerId,
                CreatedDateTime = DateTime.UtcNow,
            };

            string developer = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            string apiUrl    = $"{_settings.GetRuntimeAPIPath(SaveInstanceMethod, applicationOwnerId, applicationId, developer, instanceOwnerId)}&instanceId={instanceId}";

            using (HttpClient client = AuthenticationHelper.GetDesignerHttpClient(_httpContextAccessor.HttpContext, _testdataRepositorySettings.GetDesignerHost()))
            {
                client.BaseAddress = new Uri(apiUrl);

                using (MemoryStream stream = new MemoryStream())
                {
                    var          jsonData = JsonConvert.SerializeObject(instance);
                    StreamWriter writer   = new StreamWriter(stream);
                    writer.Write(jsonData);
                    writer.Flush();
                    stream.Position = 0;

                    Task <HttpResponseMessage> response = client.PostAsync(apiUrl, new StreamContent(stream));
                    if (!response.Result.IsSuccessStatusCode)
                    {
                        throw new Exception("Unable to save instance");
                    }
                }
            }

            // Save instantiated form model
            Guid dataId = await _form.SaveFormModel(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                applicationOwnerId,
                applicationId,
                instanceOwnerId,
                Guid.Empty);

            // Update instance with dataId
            instance = await GetInstance(applicationId, applicationOwnerId, instanceOwnerId, instanceId);

            Data data = new Data
            {
                Id          = dataId.ToString(),
                ContentType = "application/Xml",
                StorageUrl  = "data/boatdata/",
                CreatedBy   = instanceOwnerId.ToString(),
            };
            Dictionary <string, Data> formData = new Dictionary <string, Data>();

            formData.Add(dataId.ToString(), data);
            instance.Data = new Dictionary <string, Dictionary <string, Data> >();
            instance.Data.Add("boatData", formData);
            UpdateInstance(instance, applicationId, applicationOwnerId, instanceOwnerId, instanceId);

            return(instanceId);
        }
示例#28
0
        /// <summary>
        /// Returns a list of prefill instances for a given party and service
        /// </summary>
        /// <param name="partyId">The partyId</param>
        /// <param name="org">The Organization code for the service owner</param>
        /// <param name="service">The service code for the current service</param>
        /// <param name="edition">The edition code for the current service</param>
        /// <returns>A list of prefill to be used</returns>
        public List <ServicePrefill> GetServicePrefill(int partyId, string org, string service, string edition)
        {
            List <ServicePrefill> formInstances = new List <ServicePrefill>();
            string formDataFilePath             = _settings.GetEditionPath(org, service, edition, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + "Testdataforparty/" + partyId + "/Prefill/";

            if (!Directory.Exists(formDataFilePath))
            {
                Directory.CreateDirectory(formDataFilePath);
            }

            string[] files = Directory.GetFiles(formDataFilePath);

            foreach (string file in files)
            {
                formInstances.Add(new ServicePrefill()
                {
                    PrefillKey = Path.GetFileNameWithoutExtension(file), LastChanged = File.GetLastWriteTime(file)
                });
            }

            return(formInstances);
        }
        private HttpResponseMessage CreateTokenResponse(string userName, Client client, EndpointReference scope, string tokenType, bool includeRefreshToken)
        {
            var auth = new AuthenticationHelper();

            var principal = auth.CreatePrincipal(userName, "OAuth2",
                    new Claim[]
                        {
                            new Claim(Constants.Claims.Client, client.Name),
                            new Claim(Constants.Claims.Scope, scope.Uri.AbsoluteUri)
                        });

            if (!ClaimsAuthorization.CheckAccess(principal, Constants.Actions.Issue, Constants.Resources.OAuth2))
            {
                Tracing.Error("OAuth2 endpoint authorization failed for user: " + userName);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            var sts = new STS();
            TokenResponse tokenResponse;
            if (sts.TryIssueToken(scope, principal, tokenType, out tokenResponse))
            {
                if (includeRefreshToken)
                {
                    tokenResponse.RefreshToken = RefreshTokenRepository.AddCode(CodeTokenType.RefreshTokenIdentifier, client.ID, userName, scope.Uri.AbsoluteUri);
                }

                var resp = Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest);
            }
        }
        public async Task <IHttpActionResult> GetSharePointAccessToken()
        {
            var retValue = await AuthenticationHelper.AcquireSharePointTokenAsync();

            return(Ok(retValue));
        }
示例#31
0
        public BookingMutation()
        {
            Field <NonNullGraphType <BookingType> >(
                "CheckIn",
                "Cập nhật thời gian checkin của phòng",
                _IdArgument(),
                _CheckPermission_TaskObject(
                    p => p.PermissionManageRentingRoom,
                    context =>
            {
                var employee = AuthenticationHelper.GetEmployee(context);
                return(BookingBusiness.CheckIn(employee, _GetId <int>(context)));
            }
                    )
                );

            Field <NonNullGraphType <BookingType> >(
                "RequestCheckOut",
                "Yêu cầu kiểm tra khi trả phòng",
                _IdArgument(),
                _CheckPermission_TaskObject(
                    p => p.PermissionManageRentingRoom,
                    context =>
            {
                var employee = AuthenticationHelper.GetEmployee(context);
                return(BookingBusiness.RequestCheckOut(employee, _GetId <int>(context)));
            }
                    )
                );

            Field <NonNullGraphType <BookingType> >(
                "CheckOut",
                "Thực hiện xác nhận trả phòng",
                _IdArgument(),
                _CheckPermission_TaskObject(
                    p => p.PermissionManageRentingRoom,
                    context =>
            {
                var employee = AuthenticationHelper.GetEmployee(context);
                return(BookingBusiness.CheckOut(employee, _GetId <int>(context)));
            }
                    )
                );

            Field <NonNullGraphType <StringGraphType> >(
                "Cancel",
                "Hủy đặt phòng",
                _IdArgument(),
                _CheckPermission_String(
                    p => p.PermissionManageRentingRoom,
                    context =>
            {
                BookingBusiness.Cancel(_GetId <int>(context));
                return("Hủy thành công");
            }
                    )
                );

            Field <NonNullGraphType <BookingType> >(
                "AddBookingToBill",
                "Thêm phòng khách đoàn",
                new QueryArguments(
                    new QueryArgument <NonNullGraphType <BillIdInput> > {
                Name = "bill"
            },
                    new QueryArgument <NonNullGraphType <BookingCreateInput> > {
                Name = "booking"
            }
                    ),
                _CheckPermission_TaskObject(
                    p => p.PermissionManageRentingRoom,
                    context =>
            {
                var employee = AuthenticationHelper.GetEmployee(context);
                var bill     = context.GetArgument <Bill>("bill");
                var booking  = context.GetArgument <Booking>("booking");

                return(BookingBusiness.Add(employee, bill, booking));
            }
                    )
                );
        }
示例#32
0
 public static void p5_auth_my_settings_set(ApplicationContext context, ActiveEventArgs e)
 {
     using (new ArgsRemover(e.Args, true)) {
         AuthenticationHelper.ChangeSettings(context, e.Args);
     }
 }
示例#33
0
    /// <summary>
    /// Page load.
    /// </summary>
    /// <param name="sender">Sender.</param>
    /// <param name="e">Arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        userID = ValidationHelper.GetInteger(SessionHelper.GetValue("UserPasswordRequestID"), 0);

        hash      = QueryHelper.GetString("hash", string.Empty);
        time      = QueryHelper.GetString("datetime", string.Empty);
        policyReq = QueryHelper.GetInteger("policyreq", 0);
        pwdExp    = QueryHelper.GetInteger("exp", 0);
        returnUrl = QueryHelper.GetString("returnurl", null);

        btnReset.Text           = GetString("general.reset");
        rfvConfirmPassword.Text = GetString("general.requiresvalue");

        siteName = CMSContext.CurrentSiteName;

        // Get interval from settings
        interval = SettingsKeyProvider.GetDoubleValue(siteName + ".CMSResetPasswordInterval");

        // Prepare failed message
        string invalidRequestMessage = DataHelper.GetNotEmpty(InvalidRequestText, String.Format(ResHelper.GetString("membership.passwresetfailed"), ResolveUrl("~/cmspages/logon.aspx?forgottenpassword=1")));

        // Reset password cancelation
        if (QueryHelper.GetBoolean("cancel", false))
        {
            // Get user info
            UserInfo ui = UserInfoProvider.GetUserInfoWithSettings("UserPasswordRequestHash = '" + SqlHelperClass.GetSafeQueryString(hash, true) + "'");
            if (ui != null)
            {
                ui.UserPasswordRequestHash = null;
                UserInfoProvider.SetUserInfo(ui);

                SessionHelper.Remove("UserPasswordRequestID");

                ShowInformation(GetString("membership.passwresetcancelled"));
            }
            else
            {
                ShowError(invalidRequestMessage);
            }

            pnlReset.Visible = false;
            return;
        }

        // Reset password request
        if (!URLHelper.IsPostback())
        {
            if (policyReq > 0)
            {
                ShowInformation(GetString("passwordpolicy.policynotmet") + "<br />" + passStrength.GetPasswordPolicyHint());
            }

            // Prepare query
            string query = "UserPasswordRequestHash = '" + SqlHelperClass.GetSafeQueryString(hash, true) + "'";
            if (userID > 0)
            {
                query = SqlHelperClass.AddWhereCondition(query, "UserID = " + userID, "OR");
            }

            // Get user info
            UserInfo ui = UserInfoProvider.GetUserInfoWithSettings(query);

            // Validate request
            ResetPasswordResultEnum result = AuthenticationHelper.ValidateResetPassword(ui, hash, time, interval, "Reset password control");

            // Prepare messages
            string timeExceededMessage = DataHelper.GetNotEmpty(ExceededIntervalText, String.Format(ResHelper.GetString("membership.passwreqinterval"), ResolveUrl("~/cmspages/logon.aspx?forgottenpassword=1")));
            string resultMessage       = string.Empty;

            // Check result
            switch (result)
            {
            case ResetPasswordResultEnum.Success:
                // Save user is to session
                SessionHelper.SetValue("UserPasswordRequestID", ui.UserID);

                // Delete it from user info
                ui.UserPasswordRequestHash = null;
                UserInfoProvider.SetUserInfo(ui);

                break;

            case ResetPasswordResultEnum.TimeExceeded:
                resultMessage = timeExceededMessage;
                break;

            default:
                resultMessage = invalidRequestMessage;
                break;
            }

            if (!string.IsNullOrEmpty(resultMessage))
            {
                // Show error message
                ShowError(resultMessage);

                pnlReset.Visible = false;

                return;
            }
        }
    }
    /// <summary>
    /// Loads the widget form.
    /// </summary>
    private void LoadForm()
    {
        // Setup basic form on live site
        formCustom.AllowMacroEditing = false;
        formCustom.IsLiveSite        = IsLiveSite;

        // Load settings
        if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the widget variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateId, variantName, false);

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        EnsureDashboard();

        if (!String.IsNullOrEmpty(WidgetId) && !IsInline)
        {
            if (CurrentPageInfo == null)
            {
                ShowError(GetString("Widgets.Properties.aliasnotfound"));
                pnlFormArea.Visible = false;
                return;
            }

            // Get template instance
            mTemplateInstance = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo);

            if (!IsNewWidget)
            {
                // Get the instance of widget
                mWidgetInstance = mTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                if (mWidgetInstance == null)
                {
                    ShowError(GetString("Widgets.Properties.WidgetNotFound"));
                    pnlFormArea.Visible = false;
                    return;
                }

                if ((VariantID > 0) && (mWidgetInstance != null) && (mWidgetInstance.PartInstanceVariants != null))
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        mWidgetInstance = CurrentPageInfo.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                        mWidgetInstance = mWidgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID));
                        // Set the widget variant mode
                        if (mWidgetInstance != null)
                        {
                            VariantMode = mWidgetInstance.VariantMode;
                        }
                    }
                    else
                    {
                        // Not authorized for OnlineMarketing - Manage.
                        RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                    }
                }

                // Get widget info by widget name(widget type)
                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(mWidgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
            }

            // Keep xml version
            if (mWidgetInstance != null)
            {
                mXmlVersion = mWidgetInstance.XMLVersion;
            }

            UIContext.EditedObject = mWidgetInfo;

            // Get the zone to which it inserts
            WebPartZoneInstance zone = mTemplateInstance.GetZone(ZoneId);
            if ((ZoneType == WidgetZoneTypeEnum.None) && (zone != null))
            {
                ZoneType = zone.WidgetZoneType;
            }

            // Check security
            var currentUser = MembershipContext.AuthenticatedUser;

            switch (ZoneType)
            {
            // Group zone => Only group widgets and group admin
            case WidgetZoneTypeEnum.Group:
                // Should always be, only group widget are allowed in group zone
                if (!mWidgetInfo.WidgetForGroup || (!currentUser.IsGroupAdministrator(CurrentPageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for editor zones
            case WidgetZoneTypeEnum.Editor:
                if (!mWidgetInfo.WidgetForEditor)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for user zones
            case WidgetZoneTypeEnum.User:
                if (!mWidgetInfo.WidgetForUser)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for dashboard zones
            case WidgetZoneTypeEnum.Dashboard:
                if (!mWidgetInfo.WidgetForDashboard)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;
            }

            // Check security
            if ((ZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                if (OnNotAllowed != null)
                {
                    OnNotAllowed(this, null);
                }
            }

            // Get form schemas
            mWebPartInfo = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID);
            string   widgetProperties = FormHelper.MergeFormDefinitions(mWebPartInfo.WebPartProperties, mWidgetInfo.WidgetProperties);
            FormInfo fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, ZoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues);

            if (fi != null)
            {
                fi.ContextResolver.Settings.RelatedObject = mTemplateInstance;

                // Check if there are some editable properties
                var ffi = fi.GetFields(true, false);
                if ((ffi == null) || (ffi.Count == 0))
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                DataRow dr = fi.GetDataRow();

                // Load overridden values for new widget
                if (IsNewWidget || (mXmlVersion > 0))
                {
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }

                if (IsNewWidget)
                {
                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(mWidgetInfo.WidgetDisplayName));
                }

                // Load values from existing widget
                LoadDataRowFromWidget(dr, fi);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.ExtendedControls.ControlContext.WIDGET_PROPERTIES;
            }
        }

        if (IsInline)
        {
            // Load text definition from session
            string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty);
            if (String.IsNullOrEmpty(definition))
            {
                definition = Request.Form[hdnWidgetDefinition.UniqueID];
            }
            else
            {
                hdnWidgetDefinition.Value = definition;
            }

            Hashtable parameters = null;
            string    widgetName = string.Empty;



            if (IsNewWidget)
            {
                // New widget - load widget info by id
                if (!String.IsNullOrEmpty(WidgetId))
                {
                    mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
                }
                else
                {
                    // Try to get widget from codename
                    widgetName  = QueryHelper.GetString("WidgetName", String.Empty);
                    mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }
            else
            {
                if (definition == null)
                {
                    DisplayError("widget.failedtoload");
                    return;
                }

                // Parse definition
                parameters = CMSDialogHelper.GetHashTableFromString(definition);

                // Trim control name
                if (parameters["name"] != null)
                {
                    widgetName = parameters["name"].ToString();
                }

                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }
            if (mWidgetInfo == null)
            {
                DisplayError("widget.failedtoload");
                return;
            }

            // If widget cant be used as inline
            if (!mWidgetInfo.WidgetForInline)
            {
                DisplayError("widget.cantbeusedasinline");
                return;
            }


            // Test permission for user
            var currentUser = MembershipContext.AuthenticatedUser;
            if (!WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                mIsValidWidget = false;
                OnNotAllowed(this, null);
            }

            // If user is editor, more properties are shown
            WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
            if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName))
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }

            WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID);
            string      widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, mWidgetInfo.WidgetProperties);
            FormInfo    fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, zoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues);
            if (fi != null)
            {
                // Check if there are some editable properties
                mFields = fi.GetFields(true, true);
                if ((mFields == null) || !mFields.Any())
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                // Get datarows with required columns
                DataRow dr = PortalHelper.CombineWithDefaultValues(fi, mWidgetInfo);

                if (IsNewWidget)
                {
                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }
                else
                {
                    foreach (string key in parameters.Keys)
                    {
                        object value = parameters[key];
                        // Test if given property exists
                        if (dr.Table.Columns.Contains(key) && (value != null))
                        {
                            try
                            {
                                dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                // Override default value and set title as widget display name
                DataHelper.SetDataRowValue(dr, "WidgetTitle", mWidgetInfo.WidgetDisplayName);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.ExtendedControls.ControlContext.WIDGET_PROPERTIES;
            }
        }
    }
示例#35
0
        private async Task GetSampleDataAsync()
        {
            Uri         dataUri = new Uri("ms-appx:///DataModel/InitialData.json");
            StorageFile file    = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

            string jsonText = await FileIO.ReadTextAsync(file);

            // Ensure that we have a valid access token before updating the data
            string accessToken = await AuthenticationHelper.EnsureAccessTokenAvailableAsync();

            lock (this.Groups)
            {
                if (this.Groups.Count != 0)
                {
                    return;
                }

                JsonObject jsonObject = JsonObject.Parse(jsonText);
                JsonArray  jsonArray  = jsonObject["Groups"].GetArray();

                foreach (JsonValue groupValue in jsonArray)
                {
                    JsonObject groupObject = groupValue.GetObject();
                    DataGroup  group       = new DataGroup(groupObject["UniqueId"].GetString(),
                                                           groupObject["Title"].GetString(),
                                                           groupObject["Subtitle"].GetString(),
                                                           groupObject["ImagePath"].GetString(),
                                                           groupObject["MoreInfoText"].GetString(),
                                                           new Uri(groupObject["MoreInfoUri"].GetString()));

                    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                    {
                        JsonObject itemObject    = itemValue.GetObject();
                        JsonObject requestObject = itemObject["Request"].GetObject();

                        //Add the Authorization header with the access token.
                        JsonObject jsonHeaders = requestObject["Headers"].GetObject();
                        jsonHeaders["Authorization"] = JsonValue.CreateStringValue(jsonHeaders["Authorization"].GetString()
                                                                                   + accessToken);

                        // The body can be a JSON object or string, we need to
                        // determine the type of JSON value and use the right
                        // method to get the value.
                        string strBody;
                        if (requestObject["Body"].ValueType == JsonValueType.Object)
                        {
                            strBody = requestObject["Body"].GetObject().Stringify();
                        }
                        else if (requestObject["Body"].ValueType == JsonValueType.String)
                        {
                            strBody = requestObject["Body"].GetString();
                        }
                        else
                        {
                            throw new NotSupportedException("The body should only be of value JSON object or JSON string.");
                        }

                        //Create the request object
                        RequestItem request = new RequestItem(new Uri(requestObject["ApiUrl"].GetString(), UriKind.Relative),
                                                              requestObject["Method"].GetString(),
                                                              jsonHeaders,
                                                              strBody);

                        //Create the data item object
                        DataItem item = new DataItem(itemObject["UniqueId"].GetString(),
                                                     itemObject["Title"].GetString(),
                                                     itemObject["Subtitle"].GetString(),
                                                     itemObject["ImagePath"].GetString()
                                                     );

                        // Add the request object to the item
                        item.Request = request;

                        //Add the item to the group
                        group.Items.Add(item);
                    }
                    this.Groups.Add(group);
                }
            }
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(string userName, string password, EndpointReference appliesTo, string tokenType, Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            var auth = new AuthenticationHelper();
            ClaimsPrincipal principal;
            if (UserRepository.ValidateUser(userName, password))
            {
                principal = auth.CreatePrincipal(userName, "OAuth2",
                    new Claim[]
                        {
                            new Claim(Constants.Claims.Client, client.Name),
                            new Claim(Constants.Claims.Scope, appliesTo.Uri.AbsoluteUri)
                        });

                if (!ClaimsAuthorization.CheckAccess(principal, Constants.Actions.Issue, Constants.Resources.OAuth2))
                {
                    Tracing.Error("OAuth2 endpoint authorization failed for user: "******"Resource owner credential validation failed: " + userName);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            var sts = new STS();
            TokenResponse tokenResponse;
            if (sts.TryIssueToken(appliesTo, principal, tokenType, out tokenResponse))
            {
                var resp = Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest);
            }
        }
 public void TearDown()
 {
     AuthenticationHelper.AuthenticateUser(this.AdminEmail, this.AdminPass, true);
     ServerOperations.Pages().DeleteAllPages();
     ServerOperations.Users().DeleteUserAndProfile(NewUserEmail);
 }