public async Task<ExchangeClient> EnsureExchangeClient()
        {
            if (_exchangeClient != null)
                return _exchangeClient;

            var authenticator = new Authenticator();
            _authenticationInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);

            _exchangeClient = new ExchangeClient(new Uri(ExchangeServiceRoot), _authenticationInfo.GetAccessToken);
            _isAuthenticated = true;
            return _exchangeClient;
        }
Пример #2
0
 internal LaunchHandle(AuthenticationInfo info)
 {
     Info = info;
 }
 public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo package) : base(package)
 {
     AuthSystem = authSystem;
     Initialize();
 }
Пример #4
0
 public AuthenticationRecord(string accName, AuthenticationInfo srp)
 {
     AccName  = accName;
     AuthInfo = srp;
 }
Пример #5
0
        private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo)
        {
            if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
            {
                return(true);
            }

            if (authAttribtues.AllowLocal && request.IsLocal)
            {
                return(true);
            }

            if (authAttribtues.AllowLocalOnly && request.IsLocal)
            {
                return(true);
            }

            if (string.IsNullOrEmpty(auth.Token))
            {
                return(true);
            }

            if (tokenInfo != null && tokenInfo.UserId.Equals(Guid.Empty))
            {
                return(true);
            }

            return(false);
        }
Пример #6
0
        /// <summary>
        /// Normalization of a git directory turns all remote branches into local branches, turns pull request refs into a real branch and a few other things. This is designed to be run *only on the build server* which checks out repositories in different ways.
        /// It is not recommended to run normalization against a local repository
        /// </summary>
        public static void NormalizeGitDirectory(ILog log, IEnvironment environment, string gitDirectory, AuthenticationInfo authentication,
                                                 bool noFetch, string currentBranch, bool isDynamicRepository)
        {
            using var repo = new Repository(gitDirectory);
            // Need to ensure the HEAD does not move, this is essentially a BugCheck
            var expectedSha        = repo.Head.Tip.Sha;
            var expectedBranchName = repo.Head.CanonicalName;

            try
            {
                var remote = EnsureOnlyOneRemoteIsDefined(log, repo);

                AddMissingRefSpecs(log, repo, remote);

                //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
                if (noFetch)
                {
                    log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
                }
                else
                {
                    Fetch(log, authentication, remote, repo);
                }

                EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch);
                CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name);

                // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
                // if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
                if (expectedSha != repo.Head.Tip.Sha &&
                    (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
                {
                    var newExpectedSha        = repo.Head.Tip.Sha;
                    var newExpectedBranchName = repo.Head.CanonicalName;

                    log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");

                    expectedSha = newExpectedSha;
                }

                var headSha = repo.Refs.Head.TargetIdentifier;

                if (!repo.Info.IsHeadDetached)
                {
                    log.Info($"HEAD points at branch '{headSha}'.");
                    return;
                }

                log.Info($"HEAD is detached and points at commit '{headSha}'.");
                log.Info(string.Format("Local Refs:\r\n" + string.Join(System.Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})"))));

                // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
                // If they do, go ahead and checkout that branch
                // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
                var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

                var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
                    ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
                    : null;
                if (matchingCurrentBranch != null)
                {
                    log.Info($"Checking out local branch '{currentBranch}'.");
                    Commands.Checkout(repo, matchingCurrentBranch);
                }
                else if (localBranchesWhereCommitShaIsHead.Count > 1)
                {
                    var          branchNames   = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
                    var          csvNames      = string.Join(", ", branchNames);
                    const string moveBranchMsg = "Move one of the branches along a commit to remove warning";

                    log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
                    var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
                    if (master != null)
                    {
                        log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
                        Commands.Checkout(repo, master);
                    }
                    else
                    {
                        var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
                        if (branchesWithoutSeparators.Count == 1)
                        {
                            var branchWithoutSeparator = branchesWithoutSeparators[0];
                            log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
                            Commands.Checkout(repo, branchWithoutSeparator);
                        }
                        else
                        {
                            throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
                        }
                    }
                }
                else if (localBranchesWhereCommitShaIsHead.Count == 0)
                {
                    log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
                    CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication);
                }
                else
                {
                    log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
                    Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
                }
            }
            finally
            {
                if (repo.Head.Tip.Sha != expectedSha)
                {
                    if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
                    {
                        // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
                        throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.

To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1

Please run `git {CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
                    }
                }
            }
        }
Пример #7
0
        public static int AddPackage(PackageInfo package, bool includeDetail)
        {
            int packageID = provider.AddPackage(package.PortalID,
                                                package.Name,
                                                package.FriendlyName,
                                                package.Description,
                                                package.PackageType,
                                                package.Version.ToString(3),
                                                package.License,
                                                package.Manifest,
                                                package.Owner,
                                                package.Organization,
                                                package.Url,
                                                package.Email,
                                                package.ReleaseNotes,
                                                package.IsSystemPackage,
                                                UserController.GetCurrentUserInfo().UserID,
                                                package.FolderName,
                                                package.IconFile);
            var objEventLog = new EventLogController();

            objEventLog.AddLog(package, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PACKAGE_CREATED);
            if (includeDetail)
            {
                Locale           locale;
                LanguagePackInfo languagePack;
                switch (package.PackageType)
                {
                case "Auth_System":
                    //Create a new Auth System
                    var authSystem = new AuthenticationInfo();
                    authSystem.AuthenticationType = package.Name;
                    authSystem.IsEnabled          = Null.NullBoolean;
                    authSystem.PackageID          = packageID;
                    AuthenticationController.AddAuthentication(authSystem);
                    break;

                case "Container":
                case "Skin":
                    var skinPackage = new SkinPackageInfo();
                    skinPackage.SkinName  = package.Name;
                    skinPackage.PackageID = packageID;
                    skinPackage.SkinType  = package.PackageType;
                    SkinController.AddSkinPackage(skinPackage);
                    break;

                case "CoreLanguagePack":
                    locale                          = LocaleController.Instance.GetLocale(PortalController.GetCurrentPortalSettings().DefaultLanguage);
                    languagePack                    = new LanguagePackInfo();
                    languagePack.PackageID          = packageID;
                    languagePack.LanguageID         = locale.LanguageId;
                    languagePack.DependentPackageID = -2;
                    LanguagePackController.SaveLanguagePack(languagePack);
                    break;

                case "ExtensionLanguagePack":
                    locale                          = LocaleController.Instance.GetLocale(PortalController.GetCurrentPortalSettings().DefaultLanguage);
                    languagePack                    = new LanguagePackInfo();
                    languagePack.PackageID          = packageID;
                    languagePack.LanguageID         = locale.LanguageId;
                    languagePack.DependentPackageID = Null.NullInteger;
                    LanguagePackController.SaveLanguagePack(languagePack);
                    break;

                case "Module":
                    //Create a new DesktopModule
                    var desktopModule = new DesktopModuleInfo();
                    desktopModule.PackageID         = packageID;
                    desktopModule.ModuleName        = package.Name;
                    desktopModule.FriendlyName      = package.FriendlyName;
                    desktopModule.FolderName        = package.Name;
                    desktopModule.Description       = package.Description;
                    desktopModule.Version           = package.Version.ToString(3);
                    desktopModule.SupportedFeatures = 0;
                    int desktopModuleId = DesktopModuleController.SaveDesktopModule(desktopModule, false, true);
                    if (desktopModuleId > Null.NullInteger)
                    {
                        DesktopModuleController.AddDesktopModuleToPortals(desktopModuleId);
                    }
                    break;

                case "SkinObject":
                    var skinControl = new SkinControlInfo();
                    skinControl.PackageID  = packageID;
                    skinControl.ControlKey = package.Name;
                    SkinControlController.SaveSkinControl(skinControl);
                    break;
                }
            }
            return(packageID);
        }
Пример #8
0
        private static List<Session> searchForSessions(AuthenticationInfo auth, SessionManagementClient smc, Folder folder)
        {
            List<Session> sessionsToIndex = new List<Session>();
            try
            {
                // Search for all sessions in this folder
                Guid folderId = folder.Id;

                Pagination pagination = new Pagination { PageNumber = 0, MaxNumberResults = maxPerPage };
                ListSessionsRequest sessionRequest = new ListSessionsRequest { Pagination = pagination, FolderId = folderId};
                ListSessionsResponse response = smc.GetSessionsList(auth, sessionRequest, "");

                if (response.TotalNumberResults == 0)
                {
                    Console.WriteLine("Found 0 results.");
                }
                else
                {
                    int pagesOfResults = response.TotalNumberResults / maxPerPage;

                    // List the sessions from the initial request
                    foreach (Session session in response.Results)
                    {
                        // Add sessions to the list.
                        sessionsToIndex.Add(session);
                    }

                    // If there are more pages, make additional network requests
                    for (int page = 1; page < pagesOfResults; page++)
                    {
                        pagination = new Pagination { PageNumber = page, MaxNumberResults = maxPerPage };
                        sessionRequest = new ListSessionsRequest { Pagination = pagination, FolderId = folderId };
                        response = smc.GetSessionsList(auth, sessionRequest, "");

                        // List the sessions from the initial request
                        foreach (Session session in response.Results)
                        {
                            // Add sessions to the list.
                            sessionsToIndex.Add(session);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Error while searching for sessions in folder: {0} - {1}", folder.Name, e.Message));
            }
            return sessionsToIndex;
        }
Пример #9
0
 public AuthenticationInfoUpdatedMessage(AuthenticationInfo info)
 {
     Info = info;
 }
Пример #10
0
        public AuthenticationInfo GetCredentials()
        {
            AuthenticationInfo newAuthInfo = new AuthenticationInfo(username, null, System.Text.Encoding.UTF8.GetBytes(password), Name);

            return(newAuthInfo);
        }
 public static IVostokZooKeeperClientBuilder AddAuthenticationInfo(this IVostokZooKeeperClientBuilder builder, [NotNull] string login, [NotNull] string password)
 => builder.AddAuthenticationInfo(AuthenticationInfo.Digest(login, password));
Пример #12
0
 public string GenerateTicket(AuthenticationInfo authenticationInfo, string userUniqueID)
 {
     return("MockTicket");
 }
Пример #13
0
 public bool IsAllowedForContent(AuthenticationInfo authenticationInfo, bool RequireAdminAccess)
 {
     return(true);
 }
Пример #14
0
 public AuthService(AuthenticationInfo authenticationInfo, string redirectUrl)
 {
     AuthenticationInfo = authenticationInfo;
     RedirectUrl        = redirectUrl;
 }
Пример #15
0
 public RepositoryInfo()
 {
     Authentication = new AuthenticationInfo();
 }
Пример #16
0
        public void Create(AuthenticationInfo info, CancellationToken cancellationToken)
        {
            info.Id = Guid.NewGuid().ToString("N");

            Update(info, cancellationToken);
        }
Пример #17
0
 public void Meaningful_Exception_for_Unknown_Auth_Header()
 {
     AuthenticationInfo authInfo = new AuthenticationInfo("Negotiate,NTLM");
 }
Пример #18
0
 private static FetchOptions GetFetchOptions(AuthenticationInfo auth) =>
Пример #19
0
 public bool IsAllowedForContent(AuthenticationInfo authenticationInfo, bool RequireAdminAccess)
 {
     return(authenticationInfo != default && (!RequireAdminAccess || authenticationInfo.IsAdmin));
 }
Пример #20
0
 private static void Fetch(ILog log, AuthenticationInfo authentication, Remote remote, Repository repo)
 {
     log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}.");
     Commands.Fetch(repo, remote.Name, new string[0], authentication.ToFetchOptions(), null);
 }
 public DataBaseUserItemViewModel(IServiceProvider serviceProvier, AuthenticationInfo authenticationInfo)
     : base(serviceProvier)
 {
     this.authenticationInfo = authenticationInfo;
 }
Пример #22
0
        private static void CreateFakeBranchPointingAtThePullRequestTip(ILog log, Repository repo, AuthenticationInfo authentication)
        {
            var remote = repo.Network.Remotes.Single();

            log.Info("Fetching remote refs to see if there is a pull request ref");
            var remoteTips = (string.IsNullOrEmpty(authentication.Username) ?
                              GetRemoteTipsForAnonymousUser(repo, remote) :
                              GetRemoteTipsUsingUsernamePasswordCredentials(repo, remote, authentication.Username, authentication.Password))
                             .ToList();

            log.Info("Remote Refs:\r\n" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName)));

            var headTipSha = repo.Head.Tip.Sha;

            var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList();

            if (refs.Count == 0)
            {
                var message = $"Couldn't find any remote tips from remote '{remote.Url}' pointing at the commit '{headTipSha}'.";
                throw new WarningException(message);
            }

            if (refs.Count > 1)
            {
                var names   = string.Join(", ", refs.Select(r => r.CanonicalName));
                var message = $"Found more than one remote tip from remote '{remote.Url}' pointing at the commit '{headTipSha}'. Unable to determine which one to use ({names}).";
                throw new WarningException(message);
            }

            var reference     = refs[0];
            var canonicalName = reference.CanonicalName;

            log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'.");

            if (canonicalName.StartsWith("refs/tags"))
            {
                log.Info($"Checking out tag '{canonicalName}'");
                Commands.Checkout(repo, reference.Target.Sha);
                return;
            }

            if (!canonicalName.StartsWith("refs/pull/") && !canonicalName.StartsWith("refs/pull-requests/"))
            {
                var message = $"Remote tip '{canonicalName}' from remote '{remote.Url}' doesn't look like a valid pull request.";
                throw new WarningException(message);
            }

            var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/");

            log.Info($"Creating fake local branch '{fakeBranchName}'.");
            repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha));

            log.Info($"Checking local branch '{fakeBranchName}' out.");
            Commands.Checkout(repo, fakeBranchName);
        }
Пример #23
0
        private void BindLogin()
        {
            List <AuthenticationInfo> authSystems         = AuthenticationController.GetEnabledAuthenticationServices();
            AuthenticationLoginBase   defaultLoginControl = null;

            foreach (AuthenticationInfo authSystem in authSystems)
            {
                try
                {
                    //Figure out if known Auth types are enabled (so we can improve perf and stop loading the control)
                    bool enabled = true;
                    if (authSystem.AuthenticationType == "Facebook" || authSystem.AuthenticationType == "Google" ||
                        authSystem.AuthenticationType == "Live" || authSystem.AuthenticationType == "Twitter")
                    {
                        enabled = PortalController.GetPortalSettingAsBoolean(authSystem.AuthenticationType + "_Enabled", PortalId, false);
                    }

                    if (enabled)
                    {
                        var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                        BindLoginControl(authLoginControl, authSystem);
                        if (authSystem.AuthenticationType == "DNN")
                        {
                            defaultLoginControl = authLoginControl;
                        }

                        //Check if AuthSystem is Enabled
                        if (authLoginControl.Enabled)
                        {
                            var oAuthLoginControl = authLoginControl as OAuthLoginBase;
                            if (oAuthLoginControl != null)
                            {
                                //Add Login Control to List
                                _oAuthControls.Add(oAuthLoginControl);
                            }
                            else
                            {
                                //Add Login Control to List
                                _loginControls.Add(authLoginControl);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);
                }
            }
            int authCount = _loginControls.Count;

            switch (authCount)
            {
            case 0:
                //No enabled controls - inject default dnn control
                if (defaultLoginControl == null)
                {
                    //No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN)
                    AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN");
                    var authLoginControl          = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                    BindLoginControl(authLoginControl, authSystem);
                    DisplayLoginControl(authLoginControl, false, false);
                }
                else
                {
                    //Portal has no login controls enabled so load default DNN control
                    DisplayLoginControl(defaultLoginControl, false, false);
                }
                break;

            case 1:
                //We don't want the control to render with tabbed interface
                DisplayLoginControl(_loginControls[0], false, false);
                break;

            default:
                foreach (AuthenticationLoginBase authLoginControl in _loginControls)
                {
                    DisplayTabbedLoginControl(authLoginControl, tsLogin.Tabs);
                }

                break;
            }
            BindOAuthControls();
        }
Пример #24
0
 void IDataBaseCollectionServiceCallback.OnDataBasesAuthenticationLeft(SignatureDate signatureDate, string[] dataBaseNames, AuthenticationInfo authenticationInfo)
 {
     this.InvokeAsync(() =>
     {
         var authentication = this.userContext.Authenticate(signatureDate);
         var dataBases      = new DataBase[dataBaseNames.Length];
         for (var i = 0; i < dataBaseNames.Length; i++)
         {
             var dataBaseName = dataBaseNames[i];
             var dataBase     = this[dataBaseName];
             dataBase.SetAuthenticationLeft(authentication);
             dataBases[i] = dataBase;
         }
         this.InvokeItemsAuthenticationLeftEvent(authentication, dataBases);
     }, nameof(IDataBaseCollectionServiceCallback.OnDataBasesAuthenticationLeft));
 }
Пример #25
0
        public Task Create(AuthenticationInfo info, CancellationToken cancellationToken)
        {
            info.Id = Guid.NewGuid().ToString("N");

            return(Update(info, cancellationToken));
        }
 public AuthenticationEventArgs(AuthenticationInfo authenticationInfo)
 {
     this.AuthenticationInfo = authenticationInfo;
 }
Пример #27
0
        public async Task Update(AuthenticationInfo info, CancellationToken cancellationToken)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            cancellationToken.ThrowIfCancellationRequested();

            await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);

            IDbTransaction transaction = null;

            try
            {
                transaction = _connection.BeginTransaction();

                var index = 0;

                _saveInfoCommand.GetParameter(index++).Value = new Guid(info.Id);
                _saveInfoCommand.GetParameter(index++).Value = info.AccessToken;
                _saveInfoCommand.GetParameter(index++).Value = info.DeviceId;
                _saveInfoCommand.GetParameter(index++).Value = info.AppName;
                _saveInfoCommand.GetParameter(index++).Value = info.AppVersion;
                _saveInfoCommand.GetParameter(index++).Value = info.DeviceName;
                _saveInfoCommand.GetParameter(index++).Value = info.UserId;
                _saveInfoCommand.GetParameter(index++).Value = info.IsActive;
                _saveInfoCommand.GetParameter(index++).Value = info.DateCreated;
                _saveInfoCommand.GetParameter(index++).Value = info.DateRevoked;

                _saveInfoCommand.Transaction = transaction;

                _saveInfoCommand.ExecuteNonQuery();

                transaction.Commit();
            }
            catch (OperationCanceledException)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
            catch (Exception e)
            {
                _logger.ErrorException("Failed to save record:", e);

                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }

                _writeLock.Release();
            }
        }
Пример #28
0
 public SearchController(IConfiguration icon)
 {
     authInfo = new AuthenticationInfo(icon);
 }
Пример #29
0
 public string ReGenerateTicket(AuthenticationInfo authenticationInfo, string userUniqueID)
 {
     return(this.CipherService.Encrypt(SettingsManager.AppPrefix, userUniqueID, authenticationInfo, SettingsManager.TicketDurationTimeSpan));
 }
Пример #30
0
 internal LaunchHandle(AuthenticationInfo info)
 {
     Info = info;
 }
Пример #31
0
 public bool IsAllowedForManagementContent(AuthenticationInfo authenticationInfo)
 {
     return(authenticationInfo != default(AuthenticationInfo) && authenticationInfo.IsManager);
 }
Пример #32
0
        /// <summary>
        /// Create user access
        /// </summary>
        /// <returns>access id</returns>
        public string CreateUserAccess(string userTitle, string userName, string userFirstname, string userPhoneNumber, string backUrl, bool isMainContractor, string termAndConditionsUrl, bool isCustomer)
        {
            try
            {
                //#3- Ouverture d'un acces pour utilisateur
                //TODO : Data from certificate
                UserDN userDN = new UserDN()
                {
                    countryName = "FR",
                    organizationName = "Dictao Trust Services Application CA",
                    organizationalUnitName = "AnySign",
                    //emailAddress = "TODO",
                    commonName = "SAAS QA DTP UPSIDEO Client",
                };

                string user = (isCustomer) ? "USER-CUSTOMER" : "USER-ADVISER";
                PersonalInfo personalInfo = new PersonalInfo()
                {
                    user = user,
                    mainContractor = isMainContractor,
                    title = userTitle,
                    firstName = userFirstname,
                    lastName = userName,
                    userDN = userDN
                };


                string consent = "J'ai bien lu les documents ci-contre que j'accepte de signer selon les termes des conditions générales et de la convention de preuve. J'ai connaissance du fait que la signature des documents au moyen d'une signature électronique manifeste mon consentement aux droits et obligations qui en découlent, au même titre qu'une signature manuscrite. J'accepte la ${TermAndConditionsUrl}."; // et la convention de preuve
                UIInfo uiInfo = new UIInfo()
                {
                    ui = "standard",
                    backUrl = backUrl,
                    consent = consent,
                    termAndConditionsUrl = termAndConditionsUrl
                };

                // Check phone number
                // After DICTAO update, this checking is outdated
                /*Match match = Regex.Match(userPhoneNumber, @"[0-9]{10}", RegexOptions.IgnoreCase);

                if (!match.Success)
                {
                    throw new Exception(string.Format(@"La signature électronique requiert un numéro de téléphone valide composé exactement de 10 chiffres. <br />
                                        Le numéro &laquo;{0}&raquo; est incorrect.", userPhoneNumber));
                }*/

                //Phone number should be composed only with [0-9]+
                userPhoneNumber = this.GetCorrectDictaoMobile(userPhoneNumber);

                AuthenticationInfo authentificationInfo = new AuthenticationInfo()
                {
                    //phoneNumber = (!string.IsNullOrEmpty(userPhoneNumber)) ? userPhoneNumber : "0000000000",
                    phoneNumber = userPhoneNumber,
                    userId = System.Guid.NewGuid().ToString()
                };

                addUserAccess addUserAccess = new addUserAccess()
                {
                    transactionId = TransactionId,
                    userInfo = personalInfo,
                    uiInfo = uiInfo,
                    authenticationInfo = authentificationInfo,
                    externalAccessId = null,
                    singleUsage = true,
                    timeout = (long)3600000, //ms
                    metadata = null
                };

                addUserAccessResponse addUserAccessResponse = _TransactionPortCli.addUserAccess(addUserAccess);
                string accessId = addUserAccessResponse.accessId;

                return accessId;
            }
            catch (Exception ex)
            {
                //this.CancelTransaction();
                string errorMessage = "Il est impossible de signer électroniquement votre document car le numéro de mobile indiqué n'est pas valide.";

                string showError = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ShowErrors"]);
                if (!string.IsNullOrEmpty(showError) && showError == "1")
                {
                    errorMessage = string.Format("{0} : {1}", ex.Message, ex.StackTrace);
                }
                throw new Exception(errorMessage);
            }
        }
Пример #33
0
 public bool IsAllowedForRegularContent(AuthenticationInfo authInfo)
 {
     return(authInfo != default(AuthenticationInfo));
 }
Пример #34
0
        private static void Main(string[] args)
        {
            var hosts = new[] {
                new { ConfigName = "testing", Description = "Via SLB and ELB" }
            };

            foreach (var host in hosts)
            {
                Console.WriteLine("Testing: {0} ({1})", host.Description, host.ConfigName);

                try
                {
                    SessionManagementClient smc = new SessionManagementClient();
                    AuthenticationInfo auth = new AuthenticationInfo();

                    // Use an account that is a member of groups that have the right permissions.
                    auth.Password = "******";
                    auth.UserKey = "testAccount";
                    auth.AuthCode = String.Empty;

                    // Names of folders to scan
                    string[] folderNames = new string[] { "One Folder", "Some other folder name" };

                    List<Session> sessions = new List<Session>();

                    Pagination pagination = new Pagination { PageNumber = 0, MaxNumberResults = maxPerPage };
                    ListFoldersRequest request = new ListFoldersRequest { Pagination = pagination };

                    // Get all the folders we need to index
                    foreach (string folderName in folderNames)
                    {
                        ListFoldersResponse response = smc.GetFoldersList(auth, request, folderName);
                        foreach (Folder folder in response.Results)
                        {
                            // Confirm we found a folder with the exact right name, then add.
                            if (folder.Name.ToLower() == folderName.ToLower())
                            {
                                Console.WriteLine("\tSearching folder: " + folderName);
                                sessions.AddRange(searchForSessions(auth, smc, folder));
                            }
                        }
                    }

                    if (sessions.Count > 0)
                    {
                        string gsaStream = sessionsAsGsaStream(sessions);

                        Console.WriteLine("\tAll sessions: \n" + gsaStream);
                    }
                    else
                    {
                        Console.WriteLine("\tFound zero sessions.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("\tError: " + e.Message);
                }

                Console.WriteLine();
            }

            Console.WriteLine("\nCompleted");
            Console.ReadLine();
        }
        public bool Authenticate(ICredentialsProvider provider)
        {
            log.Info("Authenticating");
            if (provider == null)
            {
                throw new ArgumentNullException("AuthenticationInfo can not be null in order to authenticate.");
            }
            AuthenticationInfo authInfoToUse = null;

            try
            {
                authInfoToUse = provider.GetCredentials();
                if (authInfoToUse == null)
                {
                    throw new InvalidCredentialsException("Credential provider returned null");
                }
            }
            catch (InvalidCredentialsException ice)
            {
                log.Error("Failed to obtain credentials.", ice);
                return(false);
            }

            // save important information
            lock (this)
            {
                this.provider       = provider;
                this.clientAuthInfo = authInfoToUse;
                this.usingAuth      = true;
            }

            // build NetMessage

            string actionId = System.Guid.NewGuid().ToString();

            NetAuthentication netAuth = new NetAuthentication(authInfoToUse.Token, authInfoToUse.UserAuthenticationType);

            if ((authInfoToUse.Roles != null) && (authInfoToUse.Roles.Count != 0))
            {
                netAuth.Roles = authInfoToUse.Roles;
            }
            if (authInfoToUse.UserId != null)
            {
                netAuth.UserId = authInfoToUse.UserId;
            }
            netAuth.ActionId = actionId;

            NetAction netAction = new NetAction(NetAction.ActionType.AUTH);

            netAction.AuthenticationMessage = netAuth;
            NetMessage msg = new NetMessage(netAction);

            // build waitable object
            WaitMessageAccepted waitMsgAccepted = new WaitMessageAccepted();
            AcceptRequest       acceptRequest   = new AcceptRequest(actionId, waitMsgAccepted, 7000);

            //send message
            HandleOutgoingMessage(msg, acceptRequest);

            // wait for response
            lock (waitMsgAccepted.SyncObject)
            {
                Monitor.Wait(waitMsgAccepted.SyncObject);
            }
            if (waitMsgAccepted.WaitResult != WaitMessageAccepted.Result.Accepted)
            {
                log.Error("Authenticatation failed. Reason: " + waitMsgAccepted.WaitResult);
                return(false);
            }

            log.Info("Authenticated");

            return(true);
        }
Пример #36
0
        /// <summary>
        /// Create user access
        /// </summary>
        /// <returns>access id</returns>
        public string CreateUserAccess(string userTitle, string userName, string userFirstname, string userPhoneNumber, string backUrl)
        {
            try
            {
                //#3- Ouverture d'un acces pour utilisateur
                //Data from certificate
                UserDN userDN = new UserDN()
                {
                    countryName = "FR",
                    organizationName = "UPSIDEO",
                    organizationalUnitName = "0002 538 768 003",
                    //emailAddress = "<Ne pas valoriser>",
                    commonName = "UPSIDEO", //<Prénom Nom>
                };

                SignatureInfo signatureInfo = new SignatureInfo()
                {
                    title = userTitle,
                    lastName = (!string.IsNullOrEmpty(userName)) ? userName : "******",
                    firstName = (!string.IsNullOrEmpty(userFirstname)) ? userFirstname : " ",
                    userDN = userDN
                };

                AuthenticationInfo authenticationInfo = new AuthenticationInfo()
                {
                    phoneNumber = this.GetCorrectDictaoMobile(userPhoneNumber),
                };

                string userId = System.Guid.NewGuid().ToString();

                PersonalInfo personalInfo = new PersonalInfo()
                {
                    userId = userId,
                    signatureInfo = signatureInfo,
                    authenticationInfo = authenticationInfo                    
                };

                //string consent = "J'ai bien lu les documents ci-contre que j'accepte de signer selon les termes des conditions générales et de la convention de preuve. J'ai connaissance du fait que la signature des documents au moyen d'une signature électronique manifeste mon consentement aux droits et obligations qui en découlent, au même titre qu'une signature manuscrite. J'accepte la ${TermAndConditionsUrl}."; // et la convention de preuve
                //Appendix doc
                List<string> appendixDocs = new List<string>();
                for (int i = 1; i <= AppendixCount; i++)
                {
                    appendixDocs.Add(string.Format("{0}{1}", APPENDIX, i));
                }

                createUserAccess createUserAccess = new createUserAccess()
                {
                    transactionId = TransactionId,
                    userInfo = personalInfo,
                    timeout = (long)3600000, //ms
                    userType = userId,
                    //authorizedDocTypes = new List<string>() { DocumentTypes.CONTRACT.ToString(), DocumentTypes.APPENDIX1.ToString(), DocumentTypes.APPENDIX2.ToString(), DocumentTypes.APPENDIX3.ToString() }.ToArray(), //TODO => list of appendixes : 3 appendixes
                    authorizedDocTypes = new List<string>() { DocumentTypes.CONTRACT.ToString() }.Concat(appendixDocs).ToArray(),
                    metadata = null
                };

                createUserAccessResponse createUserAccessResponse = _TransactionPortClient.createUserAccess(createUserAccess);
                string accessId = createUserAccessResponse.accessId;

                return accessId;
            }
            catch (Exception ex)
            {
                //string errorMessage = "Il est impossible de signer électroniquement votre document car le numéro de mobile indiqué n'est pas valide.";
                string errorMessage = ex.Message;

                if (!string.IsNullOrEmpty(errorMessage) && !errorMessage.Contains("mobile"))
                {
                    errorMessage = "Une erreur inattendue est survenue lors de la signature. Veuillez réessayer ultérieurement.";
                }
                              
                throw new Exception(errorMessage);
            }
        }
Пример #37
0
 public void Fetch(string remote, IEnumerable <string> refSpecs, AuthenticationInfo auth, string?logMessage) =>
 RepositoryExtensions.RunSafe(() =>
                              Commands.Fetch((Repository)RepositoryInstance, remote, refSpecs, GetFetchOptions(auth), logMessage));