Example #1
0
        public async Task <ActionResult> Login([FromBody] LoginViewModel login, CancellationToken ct = default(CancellationToken))
        {
            ApplicationUser user = _userManager.Users.SingleOrDefault(u => u.UserName == login.UserName);

            ClaimsIdentity identity = await _getIdentity.GetClaimsIdentity(user, login.Password);

            if (identity == null)
            {
                return(Unauthorized(Errors.AddErrorToModelState(ErrorCodes.Login, ErrorDescriptions.LoginFailure, ModelState)));
            }

            // Remove existing refresh tokens
            await _userManager.RemoveAuthenticationTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken);

            // Generate a new Token
            string newRefreshToken = await _userManager.GenerateUserTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken);

            // Issue new refresh token to the user
            await _userManager.SetAuthenticationTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken, newRefreshToken);

            ApplicationToken token = await Token.GenerateJwt(user.UserName, identity, this._jwtFactory, this._jwtOptions, this._jsonSerializerSettings);

            Utilities.CookieUtility.GenerateHttpOnlyCookie(Response, TokenOptionsStrings.ApplicationToken, token);

            return(new OkObjectResult(token));
        }
Example #2
0
        public void GenerateTokenWithExpirationDate()
        {
            const string expected         = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBLZXkiOiJTb25hdGEiLCJ1c2VyIjoiZ2Fld3lubiIsImV4cCI6IjE5ODMtMDctMTNUMDA6MDA6MDAifQ.rLdO_8rujN-d61KLWTjWzosb3U8aQ2EXCPkhF3VCy9M";
            var          applicationToken = new ApplicationToken("Sonata", "gaewynn", new DateTime(1983, 7, 13));

            Assert.Equal(expected, applicationToken.WriteToken());
        }
Example #3
0
        private void FillComponentArray(ApplicationToken appToken)
        {
            GameObject targetGameObject = appToken.Target as GameObject;

            if (targetGameObject != null)
            {
                MonoBehaviour[] list = targetGameObject.GetComponents <MonoBehaviour>();
                monos = new List <MonoBehaviour>();
                foreach (MonoBehaviour mb in list)
                {
                    ITokenEvents tokenEvent = mb as ITokenEvents;
                    if (tokenEvent != null)
                    {
                        monos.Add(mb);
                    }
                }
                appToken.targetComponents = monos.ToArray();

                FillComponentNameArray(appToken);
            }
            else
            {
                ComponentsNames = new string[0];
            }
        }
Example #4
0
        public ApplicationToken Create(ApplicationTokenViewModel toCreate)
        {
            if (string.IsNullOrEmpty(toCreate.Name))
            {
                throw new EntityValidationException("Token Name cannot be blank!");
            }
            if (!ApplicationExists(toCreate.ApplicationId))
            {
                throw new EntityValidationException("Application does not exist!");
            }

            if (_db.ApplicationTokens.Active()
                .Any(at => at.ApplicationId == toCreate.ApplicationId && at.Name == toCreate.Name))
            {
                throw new EntityValidationException("A token with this name already exists for this application.");
            }

            var token = new ApplicationToken()
            {
                Name          = toCreate.Name,
                ApplicationId = toCreate.ApplicationId,
                Active        = true
            };

            _db.ApplicationTokens.Add(token);
            _db.SaveChanges();

            return(Get(token.ApplicationTokenId));
        }
Example #5
0
        public void GenerateTokenWithoutExpirationDate()
        {
            const string expected         = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBLZXkiOiJTb25hdGEiLCJ1c2VyIjoiZ2Fld3lubiJ9.PZS5CvHf1ArU-7iQakVBokeEfUh8DKqMv08nnrXgBPM";
            var          applicationToken = new ApplicationToken("Sonata", "gaewynn");

            Assert.Equal(expected, applicationToken.WriteToken());
        }
 public static ApplicationTokenDto Map(ApplicationToken entity)
 {
     return entity == null ? null : new ApplicationTokenDto
                                        {
                                            IsEnabled = entity.IsEnabled,
                                            AppName = entity.AppName
                                        };
 }
        private void FillComponentNameArray(ApplicationToken appToken)
        {
            ComponentsNames = new string[appToken.targetComponents.Length];

            for (int i = 0; i < appToken.targetComponents.Length; i++)
            {
                ITokenEvents c = (ITokenEvents)appToken.targetComponents[i];
                ComponentsNames[i] = c.GetType().ToString();
            }
        }
Example #8
0
        public void TokenContainsAllInformationWithExpirationDate()
        {
            var applicationToken  = new ApplicationToken("Sonata", "gaewynn", new DateTime(1983, 7, 13));
            var serializedToken   = applicationToken.WriteToken();
            var deserializedToken = ApplicationToken.ReadToken(serializedToken);

            Assert.Equal("Sonata", deserializedToken.ApplicationKey);
            Assert.Equal("gaewynn", deserializedToken.UserName);
            Assert.Equal(new DateTime(1983, 7, 13), deserializedToken.ExpirationDate);
        }
Example #9
0
        public void TokenContainsAllInformationWithTimeStampAsExpirationDate()
        {
            const string token            = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBLZXkiOiJTb25hdGEiLCJ1c2VyIjoiZ2Fld3lubiIsImV4cCI6MTgzODk3MTkyNX0.0uFixMQZJKlSHAu-zJoxZbJS2bx7fCiK6a10vszdon4";
            var          applicationToken = ApplicationToken.ReadToken(token);

            Assert.Equal("Sonata", applicationToken.ApplicationKey);
            Assert.Equal("gaewynn", applicationToken.UserName);
            Assert.NotNull(applicationToken.ExpirationDate);
            Assert.Equal(new DateTime(2028, 4, 10), applicationToken.ExpirationDate.Value.Date);
        }
Example #10
0
        private void FillComponentNameArray(ApplicationToken appToken)
        {
            ComponentsNames = new string[appToken.targetComponents.Length];

            for (int i = 0; i < appToken.targetComponents.Length; i++)
            {
                ITokenEvents c = (ITokenEvents)appToken.targetComponents[i];
                ComponentsNames[i] = c.GetType().ToString();
            }
        }
        public static ApplicationTokenViewModel ToViewModel(this ApplicationToken token)
        {
            var vm = new ApplicationTokenViewModel()
            {
                ApplicationId      = token.ApplicationId,
                ApplicationTokenId = token.ApplicationTokenId,
                Name = token.Name
            };

            return(vm);
        }
Example #12
0
        public static string GenerateToken(int userId)
        {
            var at = new ApplicationToken
            {
                Token  = Guid.NewGuid().ToString(),
                UserId = userId
            };

            ApplicationQuery.UpdateToken(at);

            return(at.Token);
        }
        public static ApplicationTokenDetails ToModel(this ApplicationToken token)
        {
            var result = new ApplicationTokenDetails();

            result.Token         = token.Token;
            result.ID            = token.ID;
            result.ApplicationID = token.ApplicationID;
            result.OriginHost    = token.OriginHost;
            result.IsExpired     = token.ExpiredAt.HasValue;

            return(result);
        }
Example #14
0
        public static async Task <ApplicationToken> GenerateJwt(string userId,
                                                                ClaimsIdentity identity,
                                                                IJwtFactory jwtFactory,
                                                                JwtIssuerOptions jwtOptions)
        {
            ApplicationToken accessToken = new ApplicationToken
            {
                access_token = await jwtFactory.GenerateEncodedToken(userId, identity),
                expires_in   = (long)jwtOptions.ValidFor.TotalSeconds
            };

            return(accessToken);
        }
Example #15
0
        public async Task <ActionResult> Refresh()
        {
            // Retrieve the application_token from cookies
            string expiredJwt = Request.Cookies.SingleOrDefault(cookie => cookie.Key == TokenOptionsStrings.ApplicationToken).Value;

            ClaimsPrincipal principal = this._token.GetPrincipalFromExpiredToken(expiredJwt);

            string userName = principal.Identity.Name;

            ApplicationUser user = _userManager.Users.SingleOrDefault(u => u.UserName == userName);

            if (user == null)
            {
                return(BadRequest(Errors.AddErrorToModelState(ErrorCodes.UserNotFound, ErrorDescriptions.UserNotFoundFailure, ModelState)));
            }

            string refreshToken = await _userManager.GetAuthenticationTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken);

            // if the refresh token is invalid, I don't have a nice way of handling it on the client. For now we will ignore and assume its always valid
            // Validate Refresh Token is still valid
            //bool isValid = await _userManager.VerifyUserTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken, refreshToken);
            //if (!isValid)
            //{
            //  return BadRequest(Errors.AddErrorToModelState(ErrorCodes.RefreshToken, ErrorDescriptions.RefreshTokenFailure, ModelState));
            //}

            ClaimsIdentity identity = await _getIdentity.GenerateClaimsIdentity(user);

            if (identity == null)
            {
                return(BadRequest(Errors.AddErrorToModelState(ErrorCodes.RefreshToken, ErrorDescriptions.RefreshTokenFailure, ModelState)));
            }

            // Remove old refresh token from the database
            await _userManager.RemoveAuthenticationTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken);

            // Generate a new one
            string newRefreshToken = await _userManager.GenerateUserTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken);

            // Set it in the database
            await _userManager.SetAuthenticationTokenAsync(user, TokenOptionsStrings.RefreshTokenProvider, TokenOptionsStrings.RefreshToken, newRefreshToken);

            // Generate new jwt
            ApplicationToken token = await Token.GenerateJwt(user.UserName, identity, this._jwtFactory, this._jwtOptions, this._jsonSerializerSettings);

            CookieUtility.RemoveCookie(Response, TokenOptionsStrings.ApplicationToken);

            CookieUtility.GenerateHttpOnlyCookie(Response, TokenOptionsStrings.ApplicationToken, token);

            return(new OkObjectResult(token));
        }
Example #16
0
        private void DispatchEventToSubscribers(List <Delegate> subscribers, int?invokerTokenClass, ApplicationTokenEventArgs e)
        {
            foreach (Delegate subscriber in subscribers)
            {
                ApplicationToken applicationToken = subscriber.Target as ApplicationToken;
                int subscriberTokenClass          = applicationToken.TokenClass;

                if (invokerTokenClass == subscriberTokenClass)
                {
                    EventHandler <ApplicationTokenEventArgs> subscriberHandler = subscriber as EventHandler <ApplicationTokenEventArgs>;
                    subscriberHandler(this, e);
                }
            }
        }
Example #17
0
        public async Task <ActionResult> Login([FromBody] ApplicationUserViewModel user, CancellationToken ct = default(CancellationToken))
        {
            ApplicationUser appUser = _userManager.Users.SingleOrDefault(u => u.Email == user.Email);

            ClaimsIdentity identity = await _getIdentity.GetClaimsIdentity(appUser, user.Password);

            if (identity == null)
            {
                return(Unauthorized(Errors.AddErrorToModelState(ErrorCodes.Login, ErrorDescriptions.LoginFailure, ModelState)));
            }

            ApplicationToken token = await Token.GenerateJwt(appUser.Id, identity, this._jwtFactory, this._jwtOptions);

            return(new OkObjectResult(token));
        }
Example #18
0
        public async Task <ActionResult <bool> > RegisterUser([FromBody] ApplicationUserViewModel newUser, CancellationToken ct = default(CancellationToken))
        {
            newUser = await this._supervisor.CreateUserAsync(newUser);

            if (newUser == null)
            {
                return(BadRequest("Error occured creating user"));
            }

            ApplicationUser appUser = _userManager.Users.SingleOrDefault(u => u.Email == newUser.Email);

            ClaimsIdentity identity = await _getIdentity.GenerateClaimsIdentity(appUser);

            ApplicationToken token = await Token.GenerateJwt(appUser.Id, identity, this._jwtFactory, this._jwtOptions);

            return(new OkObjectResult(token));
        }
        public async Task <ApplicationToken> RetrieveToken()
        {
            ApplicationToken token = null;

            if (_memoryTokens.TryGetValue(_credential, out token))
            {
                if (!token.IsExpired())
                {
                    return(token);
                }
                _memoryTokens.Remove(_credential);
            }

            await RefreshTokenAsync();

            return(await RetrieveToken());
        }
Example #20
0
        public ApplicationToken CreateNewToken(int id, int tokenId, LoggedInUserDetails user)
        {
            // Check whehter organisation is not active
            if (!user.Organization.IsActive)
            {
                throw new BaseException(
                          "Your organization is inactive. Please check if your organization has approved Legal Officer. For more details contact DataLinker administrator.");
            }

            // Check whether application belongs to a user
            _security.CheckAccessToApplication(user, id);

            // Get application token
            var appToken = _tokens.FirstOrDefault(i => i.ID == tokenId);

            // Check whether app token not found
            if (appToken == null)
            {
                throw new BaseException("Unable to find service host.");
            }

            // Generate new token
            var generatedToken = TokensHelper.GenerateToken();
            var result         = new ApplicationToken()
            {
                ApplicationID = appToken.ApplicationID,
                OriginHost    = appToken.OriginHost,
                Token         = generatedToken,
                CreatedAt     = GetDate,
                CreatedBy     = user.ID.Value
            };

            // Save token
            _tokens.Add(result);

            // Setup expiration details for old token
            appToken.ExpiredAt = GetDate;
            appToken.ExpiredBy = user.ID.Value;

            // Save changes
            _tokens.Update(appToken);

            // Return result
            return(result);
        }
 public void InitModels()
 {
     organization = new Organization
     {
         ID       = 1,
         IsActive = true
     };
     application = new Application
     {
         ID             = 1,
         IsProvider     = false,
         OrganizationID = organization.ID
     };
     appToken = new ApplicationToken
     {
         ApplicationID = application.ID,
         ID            = 1,
         Token         = "token"
     };
     otherApplication = new Application
     {
         ID             = 2,
         IsProvider     = false,
         OrganizationID = organization.ID
     };
     userOrgMember = new User
     {
         ID             = 1,
         IsSysAdmin     = false,
         OrganizationID = organization.ID
     };
     userNotOrgMember = new User
     {
         ID             = 2,
         IsSysAdmin     = false,
         OrganizationID = 2
     };
     softwareStatement = new SoftwareStatement
     {
         ApplicationID = application.ID,
         ID            = 1,
         Content       = "statement"
     };
 }
        public void UpdateToken(ApplicationToken at)
        {
//            Db().Execute(@"
//DELETE FROM [dbo].[ApplicationToken]
//WHERE UserId = @0;", at.UserId);

            Db().Execute(@"
INSERT INTO [dbo].[ApplicationToken]
           ([Token]
           ,[Active]
           ,[UserID]
           ,[CreatedDate]
           ,[ExpirationDate])
     VALUES
           (@0
           ,1
           ,@1
           ,GETDATE()
           ,DATEADD(hh, 10, GETDATE()))", at.Token, at.UserId);
        }
Example #23
0
        public override void OnInspectorGUI()
        {
            ApplicationToken appToken = (ApplicationToken)target;

            //DrawDefaultInspector();

            EditorGUILayout.BeginVertical();
            appToken.TokenClass = EditorGUILayout.IntField("Token Class", appToken.TokenClass);

            appToken.Target = EditorGUILayout.ObjectField("Target", appToken.Target, typeof(GameObject), true);
            if (appToken.Target != null)
            {
                FillComponentArray(appToken);
            }

            appToken.selectedComponent = EditorGUILayout.Popup("Token Events", appToken.selectedComponent, ComponentsNames);
            //appToken.SetTokenEventsFunctions();

            EditorGUILayout.EndVertical();
        }
        private void FillComponentArray(ApplicationToken appToken)
        {
            GameObject targetGameObject = appToken.Target as GameObject;

            if (targetGameObject != null)
            {
                MonoBehaviour[] list = targetGameObject.GetComponents<MonoBehaviour>();
                monos = new List<MonoBehaviour>();
                foreach (MonoBehaviour mb in list)
                {
                    ITokenEvents tokenEvent = mb as ITokenEvents;
                    if (tokenEvent != null)
                    {
                        monos.Add(mb);
                    }
                }
                appToken.targetComponents = monos.ToArray();

                FillComponentNameArray(appToken);
            }
            else
                ComponentsNames = new string[0];
        }
Example #25
0
        public void AddHost(int id, string host, LoggedInUserDetails user)
        {
            // Check whether organisation is not active
            if (!user.Organization.IsActive)
            {
                throw new BaseException(
                          "Your organization is inactive. Please check if your organization has approved Legal Officer. For more details contact DataLinker administrator.");
            }

            // Check whether host is a valid uri
            var isValidUrl = Uri.TryCreate(host, UriKind.Absolute, out var result);

            // Check whether url scheme specified
            var urlWithScheme = isValidUrl && (result.Scheme == Uri.UriSchemeHttp || result.Scheme == Uri.UriSchemeHttps);

            if (!urlWithScheme)
            {
                throw new BaseException($"Invalid host '{result}'");
            }

            // Get application
            var application = _security.CheckAccessToApplication(user, id);

            // Setup new application token
            var appToken = new ApplicationToken
            {
                ApplicationID = application.ID,
                OriginHost    = host,
                Token         = TokensHelper.GenerateToken(),
                CreatedAt     = GetDate,
                CreatedBy     = user.ID.Value
            };

            // Add new token
            _tokens.Add(appToken);
        }
Example #26
0
        public Application Create(string url, NewApplicationDetails model, LoggedInUserDetails user)
        {
            // Check whether user has access
            if (user.IsSysAdmin)
            {
                throw new BaseException("Admin can not create an application.");
            }

            // Check whether organisation is active
            if (!user.Organization.IsActive)
            {
                throw new BaseException(
                          "Your organization is inactive. Please check if your organization has approved Legal Officer. For more details contact DataLinker administrator.");
            }

            // Check whether application name already used within the organisation
            if (IsApplicationExistsForThisOrganization(model.Name, string.Empty, user))
            {
                throw new BaseException("Application name already in use.");
            }

            // Check whether hosts provided
            if (string.IsNullOrEmpty(model.OriginHosts))
            {
                throw new BaseException("You should define at least one host.");
            }

            // TODO: check whether all required data provided[Failed when auth tab was now shown in create provider app]

            // Setup application model
            var application = new Application
            {
                Name        = model.Name,
                Description = model.Description,
                PublicID    = Guid.NewGuid(),
                IsProvider  = model.IsProvider,
                IsIntroducedAsIndustryGood = model.IsIntroducedAsIndustryGood,
                OrganizationID             = user.Organization.ID,
                CreatedAt = GetDate,
                IsActive  = !model.IsIntroducedAsIndustryGood,
                CreatedBy = user.ID.Value
            };

            // Add application
            _applications.Add(application);

            if (application.IsProvider)
            {
                // Setup application authentication
                var appAuth = new ApplicationAuthentication
                {
                    ApplicationID         = application.ID,
                    WellKnownUrl          = string.IsNullOrEmpty(model.WellKnownUrl) ? string.Empty : model.WellKnownUrl,
                    Issuer                = string.IsNullOrEmpty(model.Issuer) ? string.Empty : model.Issuer,
                    JwksUri               = string.IsNullOrEmpty(model.JwksUri) ? string.Empty : model.JwksUri,
                    AuthorizationEndpoint = model.AuthorizationEndpoint,
                    TokenEndpoint         = model.TokenEndpoint,
                    RegistrationEndpoint  = model.RegistrationEndpoint,
                    UserInfoEndpoint      = string.Empty,
                    EndSessionEndpoint    = string.Empty,
                    CheckSessionIFrame    = string.Empty,
                    RevocationEndpoint    = string.Empty,
                    CreatedAt             = GetDate,
                    CreatedBy             = user.ID.Value
                };

                // Add application authentication
                _authentications.Add(appAuth);
            }

            foreach (var host in model.OriginHosts.Split(','))
            {
                var appToken = new ApplicationToken()
                {
                    ApplicationID = application.ID,
                    OriginHost    = host,
                    Token         = TokensHelper.GenerateToken(),
                    CreatedAt     = GetDate,
                    CreatedBy     = user.ID.Value
                };

                // Add token
                _tokens.Add(appToken);
            }

            // Send verification request to admin for industry good application
            if (application.IsIntroducedAsIndustryGood)
            {
                _notifications.Admin.NewIndustryGoodApplicationInBackground(url, application.OrganizationID);
            }

            return(application);
        }
 public static void Reset()
 {
     ApplicationToken.Reset();
 }
 public static void Setup(string symetricSecurityKey)
 {
     ApplicationToken.Setup(symetricSecurityKey);
 }
Example #29
0
 public static void GenerateHttpOnlyCookie(HttpResponse response, string cookieName, ApplicationToken token)
 {
     response.Cookies.Append(cookieName, token.access_token, _cookieOptions);
 }
Example #30
0
        public void Init()
        {
            sysAdmin = new User
            {
                Email          = "*****@*****.**",
                ID             = 1,
                IsActive       = true,
                IsSysAdmin     = true,
                OrganizationID = 2
            };

            otherOrganization = new Organization
            {
                ID       = 3,
                Name     = "OrgName3",
                IsActive = true
            };

            user = new User
            {
                Email          = "*****@*****.**",
                ID             = 2,
                IsSysAdmin     = false,
                OrganizationID = 2
            };

            otherUser = new User
            {
                Email          = "*****@*****.**",
                ID             = 3,
                IsSysAdmin     = false,
                OrganizationID = otherOrganization.ID
            };

            organization = new Organization
            {
                ID       = 2,
                Name     = "OrgName2",
                IsActive = true
            };


            activeService = new Application
            {
                OrganizationID             = organization.ID,
                IsActive                   = true,
                Name                       = "activeService",
                PublicID                   = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID                         = 1,
                IsIntroducedAsIndustryGood = true,
                IsProvider                 = true
            };

            consumerApplication = new Application
            {
                OrganizationID = 2,
                IsActive       = true,
                Name           = "active applications",
                PublicID       = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID             = 4,
                IsProvider     = false
            };

            notActiveService = new Application
            {
                OrganizationID = 2,
                IsActive       = false,
                Name           = "notActiveService",
                PublicID       = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID             = 2,
                IsProvider     = false
            };

            otherService = new Application
            {
                OrganizationID = 3,
                IsActive       = true,
                Name           = "otherService",
                PublicID       = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID             = 3,
                IsProvider     = false
            };

            dataSchema = new DataSchema
            {
                ID   = 1,
                Name = "Schema1"
            };

            providerEndpoint = new ProviderEndpoint
            {
                ApplicationId  = activeService.ID,
                ID             = 1,
                DataSchemaID   = dataSchema.ID,
                IsIndustryGood = true,
                Description    = "Description"
            };

            licenseTemplate = new LicenseTemplate
            {
                ID        = 1,
                LicenseID = 1,
                Status    = (int)TemplateStatus.Active
            };

            _organizationLicense = new OrganizationLicense
            {
                ID                 = 1,
                Status             = (int)PublishStatus.Published,
                ProviderEndpointID = providerEndpoint.ID,
                DataSchemaID       = providerEndpoint.DataSchemaID,
                LicenseTemplateID  = licenseTemplate.ID
            };
            applicationToken = new ApplicationToken
            {
                ID            = 1,
                ApplicationID = activeService.ID,
                Token         = "token"
            };

            appService                       = new Mock <IApplicationsService>();
            _userService                     = new Mock <IUserService>();
            orgService                       = new Mock <IOrganizationService>();
            schemaService                    = new Mock <IDataSchemaService>();
            endpointService                  = new Mock <IProviderEndpointService>();
            licenseTemplateService           = new Mock <ILicenseTemplatesService>();
            sectionService                   = new Mock <ILicenseSectionService>();
            clauseService                    = new Mock <ILicenseClauseService>();
            clauseTemplateService            = new Mock <ILicenseClauseTemplateService>();
            endpointLicClauseService         = new Mock <IOrganizationLicenseClauseService>();
            licenseService                   = new Mock <IOrganizationLicenseService>();
            notificationService              = new Mock <INotificationService>();
            applicationTokenService          = new Mock <IService <ApplicationToken> >();
            applicationAuthenticationService = new Mock <IService <ApplicationAuthentication> >();
            configService                    = new Mock <IConfigurationService>();
            licenseContentBuilder            = new Mock <ILicenseContentBuilder>();
            adminNotificationService         = new Mock <IAdminNotificationService>();
            // Notification service
            notificationService.Setup(i => i.Admin).Returns(adminNotificationService.Object);
            configService.SetupProperty(p => p.ManageApplicationsPageSize, 5);
            var mockUrl = new Mock <UrlHelper>();

            // Setup application token service
            applicationTokenService.Setup(i => i.Get(applicationToken.ID)).Returns(applicationToken);
            applicationTokenService.Setup(i => i.Add(It.IsAny <ApplicationToken>())).Returns(true);
            applicationTokenService.Setup(i => i.Update(It.IsAny <ApplicationToken>())).Returns(true);
            // Schema service
            schemaService.Setup(p => p.Get(dataSchema.ID)).Returns(dataSchema);
            schemaService.Setup(p => p.Get(10)).Returns(new DataSchema {
                ID = 10, IsIndustryGood = false
            });
            schemaService.Setup(p => p.GetPublishedSchemas()).Returns(new List <DataSchema> {
                dataSchema, new DataSchema {
                    ID = 10, IsIndustryGood = false
                }
            });

            // Endpoint service
            endpointService.Setup(p => p.Get(It.IsAny <Expression <Func <ProviderEndpoint, bool> > >()))
            .Returns(new List <ProviderEndpoint> {
                providerEndpoint
            });
            endpointService.Setup(p => p.Get(providerEndpoint.ID)).Returns(providerEndpoint);

            licenseService.Setup(p => p.Get(It.IsAny <Expression <Func <OrganizationLicense, bool> > >()))
            .Returns(new List <OrganizationLicense> {
                _organizationLicense
            });

            // License template service
            licenseTemplateService.Setup(p => p.GetAll(false)).Returns(new List <LicenseTemplate> {
                licenseTemplate
            });
            licenseTemplateService.Setup(p => p.GetPublishedGlobalLicense()).Returns(licenseTemplate);

            // Application service
            appService.Setup(p => p.GetApplicationsFor((int)user.OrganizationID))
            .Returns(new List <Application> {
                activeService, notActiveService
            });
            appService.Setup(p => p.GetAllApplications())
            .Returns(new List <Application> {
                activeService, otherService, notActiveService
            });
            appService.Setup(p => p.Get(activeService.ID)).Returns(activeService);
            appService.Setup(p => p.Get(notActiveService.ID)).Returns(notActiveService);
            appService.Setup(p => p.Get(otherService.ID)).Returns(otherService);
            appService.Setup(p => p.Get(consumerApplication.ID)).Returns(consumerApplication);
            appService.Setup(p => p.GetAuthenticationFor(activeService.ID)).Returns(new ApplicationAuthentication());

            // Organization service
            orgService.Setup(p => p.Get(organization.ID)).Returns(organization);
            orgService.Setup(p => p.Get(otherOrganization.ID)).Returns(otherOrganization);

            var context = new Mock <ControllerContext>();

            context.Setup(m => m.HttpContext.Request.Form).Returns(new FormCollection());
            context.Setup(m => m.HttpContext.Request.Url).Returns(new Uri("http://test.com"));
            context.Setup(m => m.HttpContext.Request.Browser).Returns(new Mock <HttpBrowserCapabilitiesBase>().Object);

            controller = new ApplicationsController(appService.Object, applicationTokenService.Object,
                                                    applicationAuthenticationService.Object, _userService.Object,
                                                    orgService.Object, schemaService.Object, endpointService.Object,
                                                    licenseService.Object, configService.Object,
                                                    notificationService.Object);
            controller.ControllerContext = context.Object;
            controller.Url = mockUrl.Object;
        }
Example #31
0
 public void Setup()
 {
     user = new User();
     applicationToken = new ApplicationToken();
 }