示例#1
0
 private void AssertUserTenantMatchesInput(UserTenantModel userTenant)
 {
     Assert.NotNull(userTenant);
     userTenant = new UserTenantModel(this.someUserTenantInput);
     Assert.Equal(userTenant.Name, userTenant.Name);
     Assert.Equal(userTenant.RoleList, userTenant.RoleList);
     Assert.Equal(userTenant.Roles, userTenant.Roles);
     Assert.Equal(userTenant.TenantId, userTenant.TenantId);
     Assert.Equal(userTenant.Type, userTenant.Type);
     Assert.Equal(userTenant.UserId, userTenant.UserId);
 }
示例#2
0
        public async Task <UserTenantModel> PutAsync(string userId, [FromBody] UserTenantModel update)
        {
            UserTenantInput input = new UserTenantInput
            {
                UserId = userId,
                Tenant = this.GetTenantId(),
                Roles  = update.Roles,
            };

            return(await this.container.UpdateAsync(input));
        }
示例#3
0
        public async Task <UserTenantModel> PostAsync(string userId, [FromBody] UserTenantModel model)
        {
            UserTenantInput input = new UserTenantInput
            {
                UserId = userId,
                Tenant = this.GetTenantId(),
                Roles  = model.Roles,
                Name   = model.Name,
                Type   = model.Type,
            };

            return(await this.container.CreateAsync(input));
        }
示例#4
0
        public async Task <UserTenantModel> PostAsync(string userId, [FromBody] UserTenantModel model)
        {
            UserTenantInput input = new UserTenantInput
            {
                UserId      = userId,
                Tenant      = this.GetTenantId(),
                Roles       = model.Roles,
                Name        = model.Name,
                Type        = string.IsNullOrWhiteSpace(model.Type) ? "Member" : model.Type,
                CreatedTime = DateTime.UtcNow,
                CreatedBy   = !string.IsNullOrWhiteSpace(model.CreatedBy) ? model.CreatedBy : this.GetCreatedBy(),
            };

            return(await this.container.CreateAsync(input));
        }
示例#5
0
        public async Task <ActionResult> PostAsync([FromHeader(Name = "Authorization")] string authHeader, [FromRoute] string tenant)
        {
            if (authHeader == null || !authHeader.StartsWith("Bearer"))
            {
                throw new NoAuthorizationException("No Bearer Token Authorization Header was passed.");
            }

            // Extract Bearer token
            string encodedToken = authHeader.Substring("Bearer ".Length).Trim();
            var    jwtHandler   = new JwtSecurityTokenHandler();

            if (!this.jwtHelper.TryValidateToken("IoTPlatform", encodedToken, this.HttpContext, out JwtSecurityToken jwt))
            {
                throw new NoAuthorizationException("The given token could not be read or validated.");
            }

            if (jwt?.Claims?.Count(c => c.Type == "sub") == 0)
            {
                throw new NoAuthorizationException("Not allowed access. No User Claims");
            }

            // Create a userTenantInput for the purpose of finding if the user has access to the space
            UserTenantInput tenantInput = new UserTenantInput
            {
                UserId = jwt?.Claims?.Where(c => c.Type == "sub").First()?.Value,
                Tenant = tenant,
            };
            UserTenantModel tenantResult = await this.userTenantContainer.GetAsync(tenantInput);

            if (tenantResult != null)
            {
                // Everything checks out so you can mint a new token
                var tokenString = jwtHandler.WriteToken(await this.jwtHelper.GetIdentityToken(jwt.Claims.Where(c => new List <string>()
                {
                    "sub", "name", "email"
                }.Contains(c.Type)).ToList(), tenant, jwt.Audiences.First(), jwt.ValidTo));

                return(this.StatusCode(200, tokenString));
            }
            else
            {
                throw new NoAuthorizationException("Not allowed access to this tenant.");
            }
        }
示例#6
0
        private async Task CleanupUserSettingsIfUserHasNoOtherTenants(UserTenantModel userTenantModel)
        {
            if (userTenantModel != null)
            {
                bool userHasOtherTenants = await this.DoesUserHaveAnyOtherTenants(userTenantModel.UserId);

                if (!userHasOtherTenants)
                {
                    UserSettingsInput settingsInput = new UserSettingsInput();
                    settingsInput.UserId = userTenantModel.UserId;
                    UserSettingsListModel userSettings = await this.settingsContainer.GetAllAsync(settingsInput);

                    if (userSettings != null && userSettings.Models != null)
                    {
                        foreach (UserSettingsModel settingsModel in userSettings.Models)
                        {
                            settingsInput.UserId     = settingsModel.UserId;
                            settingsInput.SettingKey = settingsModel.SettingKey;
                            await this.settingsContainer.DeleteAsync(settingsInput);
                        }
                    }
                }
            }
        }
示例#7
0
 public async Task <UserTenantModel> UserClaimsPostAsync([FromBody] UserTenantModel model)
 {
     return(await this.PostAsync(this.GetClaimsUserId(), model));
 }
示例#8
0
 public async Task <UserTenantModel> UserClaimsPutAsync([FromBody] UserTenantModel update)
 {
     return(await this.PutAsync(this.GetClaimsUserId(), update));
 }
示例#9
0
        public async Task <JwtSecurityToken> GetIdentityToken(List <Claim> claims, string tenant, string audience, DateTime?expiration)
        {
            // add iat claim
            var timeSinceEpoch = DateTime.UtcNow.ToEpochTime();

            claims.Add(new Claim("iat", timeSinceEpoch.ToString(), ClaimValueTypes.Integer));

            var userId = claims.First(t => t.Type == "sub").Value;

            // Create a userTenantInput for the purpose of finding the full tenant list associated with this user
            UserTenantInput tenantInput = new UserTenantInput
            {
                UserId = userId,
            };
            UserTenantListModel tenantsModel = await this.userTenantContainer.GetAllAsync(tenantInput);

            List <UserTenantModel> tenantList = tenantsModel.Models;

            // User did not specify the tenant to log into so get the default or last used
            if (string.IsNullOrEmpty(tenant))
            {
                // authState has no tenant, so we should use either the User's last used tenant, or the first tenant available to them
                // Create a UserSettingsInput for the purpose of finding the LastUsedTenant setting for this user
                this.logger.LogInformation("User did not specify Tenant so default/last used tenant is set.");
                UserSettingsInput settingsInput = new UserSettingsInput
                {
                    UserId     = userId,
                    SettingKey = "LastUsedTenant",
                };
                UserSettingsModel lastUsedSetting = await this.userSettingsContainer.GetAsync(settingsInput);

                // Has last used tenant and it is in the list
                if (lastUsedSetting != null && tenantList.Count(t => t.TenantId == lastUsedSetting.Value) > 0)
                {
                    tenant = lastUsedSetting.Value;
                }

                if (string.IsNullOrEmpty(tenant) && tenantList.Count > 0)
                {
                    tenant =
                        tenantList.First()
                        .TenantId;     // Set the tenant to the first tenant in the list of tenants for this user
                }
            }

            // If User not associated with Tenant then dont add claims return token without
            if (tenant != null)
            {
                UserTenantInput input = new UserTenantInput
                {
                    UserId = userId,
                    Tenant = tenant,
                };
                UserTenantModel tenantModel = await this.userTenantContainer.GetAsync(input);

                // Add Tenant
                claims.Add(new Claim("tenant", tenantModel.TenantId));

                // Add Roles
                tenantModel.RoleList.ForEach(role => claims.Add(new Claim("role", role)));

                // Settings Update LastUsedTenant
                UserSettingsInput settingsInput = new UserSettingsInput
                {
                    UserId     = claims.Where(c => c.Type == "sub").First().Value,
                    SettingKey = "LastUsedTenant",
                    Value      = tenant,
                };

                // Update if name is not the same
                await this.userSettingsContainer.UpdateAsync(settingsInput);

                if (tenantModel.Name != claims.Where(c => c.Type == "name").First().Value)
                {
                    input.Name = claims.Where(c => c.Type == "name").First().Value;
                    await this.userTenantContainer.UpdateAsync(input);
                }
            }

            DateTime expirationDateTime = expiration ?? DateTime.Now.AddDays(30);

            // add all tenants they have access to
            claims.AddRange(tenantList.Select(t => new Claim("available_tenants", t.TenantId)));

            // Token to String so you can use it in your client
            var token = this.MintToken(claims, audience, expirationDateTime);

            return(token);
        }