示例#1
0
        public override void Connect()
        {
            // get or compute identity
            if (string.IsNullOrEmpty(ts3FullClientData.Identity))
            {
                identity = Ts3Crypt.GenerateNewIdentity();
                ts3FullClientData.Identity       = identity.PrivateKeyString;
                ts3FullClientData.IdentityOffset = identity.ValidKeyOffset;
            }
            else
            {
                var identityResult = Ts3Crypt.LoadIdentityDynamic(ts3FullClientData.Identity, ts3FullClientData.IdentityOffset);
                if (!identityResult.Ok)
                {
                    Log.Error("The identity from the config file is corrupted. Remove it to generate a new one next start; or try to repair it.");
                    return;
                }
                identity = identityResult.Value;
                if (ts3FullClientData.Identity != identity.PrivateKeyString)
                {
                    ts3FullClientData.Identity = identity.PrivateKeyString;
                }
                if (ts3FullClientData.IdentityOffset != identity.ValidKeyOffset)
                {
                    ts3FullClientData.IdentityOffset = identity.ValidKeyOffset;
                }
            }

            // check required security level
            if (ts3FullClientData.IdentityLevel == "auto")
            {
            }
            else if (int.TryParse(ts3FullClientData.IdentityLevel, out int targetLevel))
            {
                UpdateIndentityToSecurityLevel(targetLevel);
            }
            else
            {
                Log.Warn("Invalid value for QueryConnection::IdentityLevel, enter a number or \"auto\".");
            }

            // get or compute password
            if (!string.IsNullOrEmpty(ts3FullClientData.ServerPassword) &&
                ts3FullClientData.ServerPasswordAutoHash &&
                !ts3FullClientData.ServerPasswordIsHashed)
            {
                ts3FullClientData.ServerPassword         = Ts3Crypt.HashPassword(ts3FullClientData.ServerPassword);
                ts3FullClientData.ServerPasswordIsHashed = true;
            }

            tsFullClient.QuitMessage     = QuitMessages[Util.Random.Next(0, QuitMessages.Length)];
            tsFullClient.OnErrorEvent   += TsFullClient_OnErrorEvent;
            tsFullClient.OnConnected    += TsFullClient_OnConnected;
            tsFullClient.OnDisconnected += TsFullClient_OnDisconnected;
            ConnectClient();
        }
示例#2
0
        public Identify(string serverId, string sessionId, string token, string userId) : base(VoicePacketType.Identify)
        {
            IdentityData id = new IdentityData()
            {
                server_id  = serverId,
                session_id = sessionId,
                token      = token,
                user_id    = userId
            };

            this.data = id;
        }
示例#3
0
        private bool CheckUserBuyer(string AuthToken)
        {
            IdentityWSSoapClient ws   = new IdentityWSSoapClient();
            IdentityData         Data = ws.GetIdentity(new Security {
                BinarySecurityToken = AuthToken
            });

            if (Data == null || Data.Role != UserRole.BUYER)
            {
                return(false);
            }
            return(true);
        }
示例#4
0
        private bool ValidateClientIdentity(string token, long userId)
        {
            IdentityWSSoapClient ws       = new IdentityWSSoapClient();
            IdentityData         identity = ws.GetIdentity(new IdentityWS.Security {
                BinarySecurityToken = token
            });
            DataAccessSoapClient dataWS = new DataAccessSoapClient();
            User target = dataWS.FindUser(new DataAccessWS.Security {
                BinarySecurityToken = token
            }, userId);

            return(identity != null && target != null &&
                   identity.Username.Equals(target.Username) && identity.Role.ToString().Equals(target.Role.ToString()));
        }
示例#5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    string       cs = _config.GetConnectionString("Default");
                    IdentityData id = new IdentityData();
                    id.AddUser(cs, Input.Name.ToString(), user.Id);
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
示例#6
0
 public void Configure(IApplicationBuilder app)
 {
     app.UseHttpsRedirection();
     app.UseStaticFiles();
     app.UseRouting();
     app.UseDeveloperExceptionPage();
     app.UseSession();
     app.UseAuthorization();
     app.UseAuthentication();
     app.UseMvc(routes =>
     {
         routes.MapRoute(null,
                         template: "admin",
                         defaults: new { controller = "Admin", action = "Home" });
         routes.MapRoute(null,
                         template: "{category:alpha}",
                         defaults: new { controller = "Product", action = "Index", page = 1 });
         routes.MapRoute(null,
                         template: "{category}/page{page}",
                         defaults: new { controller = "Product", action = "Index" });
         routes.MapRoute(null,
                         template: "page{page}",
                         defaults: new { controller = "Product", action = "Index" });
         routes.MapRoute(null,
                         template: "admin/products/{scope:alpha}",
                         defaults: new { controller = "Admin", action = "ProductList" });
         routes.MapRoute(null,
                         template: "admin/products",
                         defaults: new { controller = "Admin", action = "ProductList" });
         routes.MapRoute(null,
                         template: "admin/products/{productId:int}/edit",
                         defaults: new { controller = "Admin", action = "ProductEdit" });
         routes.MapRoute(null,
                         template: "admin/products/{productId:int}",
                         defaults: new { controller = "Admin", action = "ProductView" });
         routes.MapRoute(null,
                         template: "admin/products/{scope:alpha}/{productId}/delete",
                         defaults: new { controller = "Admin", action = "ProductDelete" });
         routes.MapRoute(null,
                         template: "admin/products/{productId}/delete",
                         defaults: new { controller = "Admin", action = "ProductDelete" });
         routes.MapRoute(null,
                         template: "product/{productId:int}",
                         defaults: new { controller = "Product", action = "ProductPage" });
         routes.MapRoute(null, "{controller=Product}/{action=Index}");
     });
     ProductData.EnsureCreated(app);
     IdentityData.EnsureCreated(app);
 }
示例#7
0
        public static async Task <string> GetEndSessionUrl(HttpClient http, IdentityData data)
        {
            StringContent content = new StringContent(JsonConvert.SerializeObject(data));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = await http.PostAsync("api/Identity/EndSessionUrl", content);

            if (response.IsSuccessStatusCode)
            {
                return(await response.Content.ReadAsStringAsync());
            }
            else
            {
                return(null);
            }
        }
示例#8
0
        public override void Connect()
        {
            // get or compute identity
            if (string.IsNullOrEmpty(ts3FullClientData.Identity))
            {
                identity = Ts3Crypt.GenerateNewIdentity();
                ts3FullClientData.Identity       = identity.PrivateKeyString;
                ts3FullClientData.IdentityOffset = identity.ValidKeyOffset;
            }
            else
            {
                identity = Ts3Crypt.LoadIdentity(ts3FullClientData.Identity, ts3FullClientData.IdentityOffset);
            }

            // check required security level
            if (ts3FullClientData.IdentityLevel == "auto")
            {
            }
            else if (int.TryParse(ts3FullClientData.IdentityLevel, out int targetLevel))
            {
                if (Ts3Crypt.GetSecurityLevel(identity) < targetLevel)
                {
                    Log.Info("Calculating up to required security level: {0}", targetLevel);
                    Ts3Crypt.ImproveSecurity(identity, targetLevel);
                    ts3FullClientData.IdentityOffset = identity.ValidKeyOffset;
                }
            }
            else
            {
                Log.Warn("Invalid value for QueryConnection::IdentityLevel, enter a number or \"auto\".");
            }


            // get or compute password
            if (!string.IsNullOrEmpty(ts3FullClientData.ServerPassword) &&
                ts3FullClientData.ServerPasswordAutoHash &&
                !ts3FullClientData.ServerPasswordIsHashed)
            {
                ts3FullClientData.ServerPassword         = Ts3Crypt.HashPassword(ts3FullClientData.ServerPassword);
                ts3FullClientData.ServerPasswordIsHashed = true;
            }

            tsFullClient.QuitMessage     = QuitMessages[Util.Random.Next(0, QuitMessages.Length)];
            tsFullClient.OnErrorEvent   += TsFullClient_OnErrorEvent;
            tsFullClient.OnDisconnected += TsFullClient_OnDisconnected;
            ConnectClient();
        }
示例#9
0
        private IHttpActionResult ValidateUserCanBeDeleted(string authToken)
        {
            IdentityWSSoapClient ws       = new IdentityWSSoapClient();
            IdentityData         identity = ws.GetIdentity(new IdentityWS.Security {
                BinarySecurityToken = authToken
            });
            DataAccessSoapClient dataWS = new DataAccessSoapClient();

            OrderData[] orders = dataWS.FindOrdersByUsername(new DataAccessWS.Security {
                BinarySecurityToken = authToken
            }, identity.Username);
            if (orders != null && orders.Length > 0)
            {
                return(BadRequest("User cannot be removed since he/she has registered orders"));
            }
            return(null);
        }
示例#10
0
        private async Task LoadAsync(IdentityUser user)
        {
            string       cs       = _config.GetConnectionString("Default");
            IdentityData id       = new IdentityData();
            var          userName = await _userManager.GetUserNameAsync(user);

            var UsersName   = id.GetUser(cs, user.Id.ToString()).FirstOrDefault().UserName.ToString();
            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;
            UserName = UsersName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
示例#11
0
        public Ts3Client(ConfBot config, TsFullClient ts3FullClient, Id id)
        {
            this.id = id;

            this.ts3FullClient = ts3FullClient;
            ts3FullClient.OnEachTextMessage += ExtendedTextMessage;
            ts3FullClient.OnErrorEvent      += TsFullClient_OnErrorEvent;
            ts3FullClient.OnConnected       += TsFullClient_OnConnected;
            ts3FullClient.OnDisconnected    += TsFullClient_OnDisconnected;
            ts3FullClient.OnEachClientMoved += (s, e) =>
            {
                UpdateReconnectChannel(e.ClientId, e.TargetChannelId);
                if (AloneRecheckRequired(e.ClientId, e.TargetChannelId))
                {
                    IsAloneRecheck();
                }
            };
            ts3FullClient.OnEachClientEnterView += (s, e) =>
            {
                UpdateReconnectChannel(e.ClientId, e.TargetChannelId);
                if (AloneRecheckRequired(e.ClientId, e.TargetChannelId))
                {
                    IsAloneRecheck();
                }
                else if (AloneRecheckRequired(e.ClientId, e.SourceChannelId))
                {
                    IsAloneRecheck();
                }
            };
            ts3FullClient.OnEachClientLeftView += (s, e) =>
            {
                UpdateReconnectChannel(e.ClientId, e.TargetChannelId);
                if (AloneRecheckRequired(e.ClientId, e.TargetChannelId))
                {
                    IsAloneRecheck();
                }
                else if (AloneRecheckRequired(e.ClientId, e.SourceChannelId))
                {
                    IsAloneRecheck();
                }
            };

            this.config = config;
            identity    = null;
        }
示例#12
0
        private async Task <bool> listOrders(Message message)
        {
            string[] parts = message.Text.Split(new char[0]);
            if (parts.Length != 2)
            {
                await BotClient.SendTextMessageAsync(message.Chat.Id, "Listorders command format: /listorders authToken");

                return(false);
            }
            else
            {
                string authToken              = parts[1];
                IdentityWSSoapClient iWS      = new IdentityWSSoapClient();
                IdentityData         identity = null;
                try
                {
                    identity = iWS.GetIdentity(new identityWS.Security {
                        BinarySecurityToken = authToken
                    });
                }
                catch (Exception ex)
                {
                    await BotClient.SendTextMessageAsync(message.Chat.Id, "An error occurred " + ex.Message);

                    return(false);
                }
                if (identity != null)
                {
                    DataAccessSoapClient ws     = new DataAccessSoapClient();
                    OrderData[]          orders = ws.FindOrdersByUsername(new DataAccessWS.Security {
                        BinarySecurityToken = authToken
                    }, identity.Username);
                    string response = "";
                    foreach (var o in orders)
                    {
                        response += "{" + o.OrderNumber + "} " + o.DateCreated.ToShortDateString() +
                                    " [" + o.State.ToString() + "]\n";
                    }
                    await BotClient.SendTextMessageAsync(message.Chat.Id, response);

                    return(true);
                }
                return(false);
            }
        }
示例#13
0
 public ConnectionDataFull(
     string address,
     IdentityData identity,
     TsVersionSigned?versionSign     = null,
     string?username                 = null,
     Password?serverPassword         = null,
     string?defaultChannel           = null,
     Password?defaultChannelPassword = null,
     Id?logId = null)
     : base(address, logId)
 {
     Identity               = identity;
     VersionSign            = versionSign ?? (Tools.IsLinux ? TsVersionSigned.VER_LIN_3_X_X : TsVersionSigned.VER_WIN_3_X_X);
     Username               = username ?? "TSLibUser";
     ServerPassword         = serverPassword ?? Password.Empty;
     DefaultChannel         = defaultChannel ?? string.Empty;
     DefaultChannelPassword = defaultChannelPassword ?? Password.Empty;
 }
示例#14
0
        public Identify(string token, string gameName = null, int shardId = 0, int shardNumber = 1) : base(GatewayPacketType.Identify)
        {
            IdentityData id = new IdentityData()
            {
                token = token,
                shard = new int[] { shardId, shardNumber }
            };

            if (gameName != null)
            {
                id.presence.game = new IdentityGame()
                {
                    name = gameName
                };
            }

            this.data = id;
        }
示例#15
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // Расширяющий метод, который отображает ошибки и исключения
            app.UseDeveloperExceptionPage();
            // Код 404
            app.UseStatusCodePages();
            // Поддержка папки wwwroot
            app.UseStaticFiles();
            app.UseSession();
            app.UseIdentity();
            // Роуты
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: null,
                    template: "{category}/Page{page:int}",
                    defaults: new { controller = "Project", action = "ProjectList" }
                    );

                routes.MapRoute(
                    name: null,
                    template: "Page{page:int}",
                    defaults: new { controller = "Project", action = "ProjectList", page = 1 }
                    );

                routes.MapRoute(
                    name: null,
                    template: "{category}",
                    defaults: new { controller = "Project", action = "ProjectList", page = 1 }
                    );

                routes.MapRoute(
                    name: null,
                    template: "",
                    defaults: new { controller = "Project", action = "ProjectList", page = 1 });

                routes.MapRoute(name: null, template: "{controller}/{action}/{id?}");
            });

            // Метод, который гарантирует наличие в БД тестовой информации(установленно и сконфигурированно)
            EFData.EFDbData(app);
            IdentityData.EnsurePopulated(app);
            EFHomeData.EnsurePopulated(app);
        }
示例#16
0
 private static void CreateDbIfNotExists(IHost host)
 {
     using (var scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         try
         {
             var context     = services.GetRequiredService <EventContext>();
             var userManager = services.GetRequiredService <UserManager <EventsUser> >();
             var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();
             IdentityData.SeedData(context, userManager, roleManager);
         }
         catch (Exception ex)
         {
             var logger = services.GetRequiredService <ILogger <Program> >();
             logger.LogError(ex, "An error occurred creating the DB.");
         }
     }
 }
示例#17
0
 private IHttpActionResult ValidateClientIsSeller(string token)
 {
     try
     {
         IdentityWSSoapClient ws       = new IdentityWSSoapClient();
         IdentityData         identity = ws.GetIdentity(new IdentityWS.Security {
             BinarySecurityToken = token
         });
         if (identity != null && identity.Role != IdentityWS.UserRole.SELLER)
         {
             return(Unauthorized());
         }
     }
     catch (FaultException ex)
     {
         return(BadRequest("Invalid security token"));
     }
     return(null);
 }
示例#18
0
        public E <string> Connect()
        {
            // get or compute identity
            var identityConf = config.Connect.Identity;

            if (string.IsNullOrEmpty(identityConf.PrivateKey))
            {
                identity = TsCrypt.GenerateNewIdentity();
                identityConf.PrivateKey.Value = identity.PrivateKeyString;
                identityConf.Offset.Value     = identity.ValidKeyOffset;
            }
            else
            {
                var identityResult = TsCrypt.LoadIdentityDynamic(identityConf.PrivateKey.Value, identityConf.Offset.Value);
                if (!identityResult.Ok)
                {
                    Log.Error("The identity from the config file is corrupted. Remove it to generate a new one next start; or try to repair it.");
                    return("Corrupted identity");
                }
                identity = identityResult.Value;
                identityConf.PrivateKey.Value = identity.PrivateKeyString;
                identityConf.Offset.Value     = identity.ValidKeyOffset;
            }

            // check required security level
            if (identityConf.Level.Value >= 0 && identityConf.Level.Value <= 160)
            {
                UpdateIndentityToSecurityLevel(identityConf.Level.Value);
            }
            else if (identityConf.Level.Value != -1)
            {
                Log.Warn("Invalid config value for 'Level', enter a number between '0' and '160' or '-1' to adapt automatically.");
            }
            config.SaveWhenExists();

            reconnectCounter          = 0;
            lastReconnect             = null;
            ts3FullClient.QuitMessage = Tools.PickRandom(config.LeaveMessages.Value.Split('_'));
            ts3FullClient.CustomPing  = config.Ping;
            ClearAllCaches();
            return(ConnectClient());
        }
示例#19
0
        public async Task <string> EndSessionUrl([FromBody] IdentityData data)
        {
            using (HttpClient client = httpClientFactory.CreateClient())
            {
                DiscoveryResponse disco = await client.GetDiscoveryDocumentAsync(Utils.Linked.Identity);

                if (disco.IsError)
                {
                    return(null);
                }

                var    ru  = new RequestUrl(disco.EndSessionEndpoint);
                string url = ru.CreateEndSessionUrl(
                    idTokenHint: data.IdentityToken,
                    state: data.State,
                    postLogoutRedirectUri: Utils.ClientIdentityEndSessionRedirectUri
                    );
                return(url);
            }
        }
示例#20
0
        public async Task <bool> Login(string code, string sessionState)
        {
            if (Identity != null)
            {
                return(false);
            }
            IdentityData id = await HostServer.Login(http, code);

            if (id == null)
            {
                return(false);
            }
            else
            {
                Identity       = id;
                Identity.State = sessionState;
                base.NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
                return(true);
            }
        }
示例#21
0
        public Ts3Full(Ts3FullClientData tfcd) : base(ClientType.Full)
        {
            tsFullClient = (Ts3FullClient)tsBaseClient;

            ts3FullClientData     = tfcd;
            tfcd.PropertyChanged += Tfcd_PropertyChanged;

            sendTick = TickPool.RegisterTick(AudioSend, sendCheckInterval, false);
            encoder  = new AudioEncoder(SendCodec)
            {
                Bitrate = ts3FullClientData.AudioBitrate * 1000
            };
            audioTimer = new PreciseAudioTimer(encoder.SampleRate, encoder.BitsPerSample, encoder.Channels);
            isStall    = false;
            stallCount = 0;
            identity   = null;

            Util.Init(ref channelSubscriptionsSetup);
            Util.Init(ref clientSubscriptionsSetup);
            subscriptionSetupChanged = true;
        }
示例#22
0
        public Ts3Client(ConfBot config)
        {
            Util.Init(out clientDbNames);
            Util.Init(out clientbuffer);

            TsFullClient = new Ts3FullClient(EventDispatchType.DoubleThread);
            TsFullClient.OnClientLeftView  += ExtendedClientLeftView;
            TsFullClient.OnClientEnterView += ExtendedClientEnterView;
            TsFullClient.OnTextMessage     += ExtendedTextMessage;
            TsFullClient.OnErrorEvent      += TsFullClient_OnErrorEvent;
            TsFullClient.OnConnected       += TsFullClient_OnConnected;
            TsFullClient.OnDisconnected    += TsFullClient_OnDisconnected;

            int ScaleBitrate(int value) => Math.Min(Math.Max(1, value), 255) * 1000;

            this.config = config;
            this.config.Audio.Bitrate.Changed += (s, e) => encoderPipe.Bitrate = ScaleBitrate(e.NewValue);

            ffmpegProducer = new FfmpegProducer(config.GetParent().Tools.Ffmpeg);
            stallCheckPipe = new StallCheckPipe();
            volumePipe     = new VolumePipe();
            Volume         = config.Audio.Volume.Default;
            encoderPipe    = new EncoderPipe(SendCodec)
            {
                Bitrate = ScaleBitrate(config.Audio.Bitrate)
            };
            timePipe = new PreciseTimedPipe {
                ReadBufferSize = encoderPipe.PacketSize
            };
            timePipe.Initialize(encoderPipe);
            TargetPipe = new CustomTargetPipe(TsFullClient);
            mergePipe  = new PassiveMergePipe();

            mergePipe.Add(ffmpegProducer);
            mergePipe.Into(timePipe).Chain <CheckActivePipe>().Chain(stallCheckPipe).Chain(volumePipe).Chain(encoderPipe).Chain(TargetPipe);

            identity = null;
        }
示例#23
0
        public Ts3Client(ConfBot config, Ts3FullClient tsFullClient, Id id)
        {
            this.id = id;
            Util.Init(out clientDbNames);
            Util.Init(out clientbuffer);
            dbIdCache = new LruCache <string, ulong>(1024);

            this.tsFullClient = tsFullClient;
            tsFullClient.OnEachTextMessage += ExtendedTextMessage;
            tsFullClient.OnErrorEvent      += TsFullClient_OnErrorEvent;
            tsFullClient.OnConnected       += TsFullClient_OnConnected;
            tsFullClient.OnDisconnected    += TsFullClient_OnDisconnected;

            int ScaleBitrate(int value) => Util.Clamp(value, 1, 255) * 1000;

            this.config = config;
            this.config.Audio.Bitrate.Changed += (s, e) => encoderPipe.Bitrate = ScaleBitrate(e.NewValue);

            ffmpegProducer = new FfmpegProducer(config.GetParent().Tools.Ffmpeg, id);
            stallCheckPipe = new StallCheckPipe();
            volumePipe     = new VolumePipe();
            Volume         = config.Audio.Volume.Default;
            encoderPipe    = new EncoderPipe(SendCodec)
            {
                Bitrate = ScaleBitrate(config.Audio.Bitrate)
            };
            timePipe = new PreciseTimedPipe {
                ReadBufferSize = encoderPipe.PacketSize
            };
            timePipe.Initialize(encoderPipe, id);
            TargetPipe = new CustomTargetPipe(tsFullClient);
            mergePipe  = new PassiveMergePipe();

            mergePipe.Add(ffmpegProducer);
            mergePipe.Into(timePipe).Chain <CheckActivePipe>().Chain(stallCheckPipe).Chain(volumePipe).Chain(encoderPipe).Chain(TargetPipe);

            identity = null;
        }
示例#24
0
 private IHttpActionResult ValidateSeller(string token, string username)
 {
     try
     {
         IdentityWSSoapClient ws       = new IdentityWSSoapClient();
         IdentityData         identity = ws.GetIdentity(new IdentityWS.Security {
             BinarySecurityToken = token
         });
         if (identity == null)
         {
             return(Unauthorized());
         }
         if (!identity.Username.Equals(username))
         {
             return(Unauthorized());
         }
     }
     catch (FaultException ex)
     {
         return(BadRequest("Invalid security token"));
     }
     return(null);
 }
示例#25
0
 private IHttpActionResult ValidateOwnerProduct(string token, long productId)
 {
     try
     {
         IdentityWSSoapClient ws       = new IdentityWSSoapClient();
         IdentityData         identity = ws.GetIdentity(new IdentityWS.Security {
             BinarySecurityToken = token
         });
         if (identity == null)
         {
             return(Unauthorized());
         }
         DataAccessSoapClient dataWS = new DataAccessSoapClient();
         var binding = dataWS.ChannelFactory.Endpoint.Binding as BasicHttpBinding;
         binding.MaxReceivedMessageSize = int.MaxValue;
         Product target = dataWS.FindProduct(new DataAccessWS.Security {
             BinarySecurityToken = token
         }, productId);
         if (target == null)
         {
             return(NotFound());
         }
         User owner = dataWS.FindUser(new DataAccessWS.Security {
             BinarySecurityToken = token
         }, target.seller_id);
         if (!owner.Username.Equals(identity.Username))
         {
             return(Unauthorized());
         }
     }
     catch (FaultException ex)
     {
         return(BadRequest("Invalid security token"));
     }
     return(null);
 }
        private void InitializeDatabases(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                context.Database.Migrate();
                if (!context.Clients.Any())
                {
                    foreach (var client in IdentityData.GetClients())
                    {
                        context.Clients.Add(client.ToEntity());
                    }
                    context.SaveChanges();
                }

                if (!context.IdentityResources.Any())
                {
                    foreach (var resource in IdentityData.GetIdentityResources())
                    {
                        context.IdentityResources.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }

                if (!context.ApiResources.Any())
                {
                    foreach (var resource in IdentityData.GetApiResources())
                    {
                        context.ApiResources.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }
            }
        }
示例#27
0
 public Identity(IdentityData obj, bool alreadyEncrypted = false)
 {
     BuildDomainModel(this, obj, _map, alreadyEncrypted);
 }
示例#28
0
 public void Logout()
 {
     Identity = null;
     base.NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
 }
        /// <summary>
        /// Generate default admin user / role
        /// </summary>
        private static async Task EnsureSeedIdentityData <TUser, TRole>(UserManager <TUser> userManager,
                                                                        RoleManager <TRole> roleManager, IdentityData identityDataConfiguration)
            where TUser : IdentityUser, new()
            where TRole : IdentityRole, new()
        {
            // adding roles from seed
            foreach (var r in identityDataConfiguration.Roles)
            {
                if (!await roleManager.RoleExistsAsync(r.Name))
                {
                    var role = new TRole
                    {
                        Name = r.Name
                    };

                    var result = await roleManager.CreateAsync(role);

                    if (result.Succeeded)
                    {
                        foreach (var claim in r.Claims)
                        {
                            await roleManager.AddClaimAsync(role, new System.Security.Claims.Claim(claim.Type, claim.Value));
                        }
                    }
                }
            }

            // adding users from seed
            foreach (var user in identityDataConfiguration.Users)
            {
                var identityUser = new TUser
                {
                    UserName       = user.Username,
                    Email          = user.Email,
                    EmailConfirmed = true
                };

                var userByUserName = await userManager.FindByNameAsync(user.Username);

                var userByEmail = await userManager.FindByEmailAsync(user.Email);

                // User is already exists in database
                if (userByUserName != default || userByEmail != default)
                {
                    continue;
                }

                // if there is no password we create user without password
                // user can reset password later, because accounts have EmailConfirmed set to true
                var result = !string.IsNullOrEmpty(user.Password)
                ? await userManager.CreateAsync(identityUser, user.Password)
                : await userManager.CreateAsync(identityUser);

                if (result.Succeeded)
                {
                    foreach (var claim in user.Claims)
                    {
                        await userManager.AddClaimAsync(identityUser, new System.Security.Claims.Claim(claim.Type, claim.Value));
                    }

                    foreach (var role in user.Roles)
                    {
                        await userManager.AddToRoleAsync(identityUser, role);
                    }
                }
            }
        }
示例#30
0
        static void Main(string[] args)
        {
            IList<AuthenticationTemplateData> templates = (from atd in (IEnumerable<AuthenticationTemplateData>)RepositoryFactory.AuthenticationTemplateRepository.GetAllAuthenticationTemplates()
                                                           where atd.AuthenticationUnitCode != "P1"
                                                           select atd).ToList();

            Random rndGroup = new Random();
            Random rndTemplate = new Random();
            Guid adminId = Guid.Empty;

            for (int i = 0; i < 100000; i++)
            {
                Console.WriteLine("Adding Identity " + i);
                IdentityData identity = new IdentityData()
                {
                    CountryCode = "US",
                    FirstName = "Scott" + i,
                    LastName = "Sickles" + i,
                    FullName = "Scott" + i + " Sickles" + i,
                    IdentityCode = i % 10 == 0 ? "E" : "C",
                    SourceId = i.ToString(),
                    GroupId = rndGroup.Next(26) + 1
                };
                identity.Uid = RepositoryFactory.IdentityRepository.Add(identity);
                Audit.AuditEvent(Audit.EventTypes.AddIdentity, string.Format("Identity {0} has been added.", identity.Uid), Guid.Empty);

                LoginData login1 = new LoginData()
                {
                    IdentityId = identity.Uid,
                    ApplicationCode = "T24",
                    LoginName = "AUTHOR",
                    Password = "******",
                    RoleCode = "T24USER",
                    T24Id = i.ToString()
                };
                login1.Id = RepositoryFactory.LoginRepository.Add(login1);
                Audit.AuditEvent(Audit.EventTypes.AddLogin, string.Format("Login {0} has been added for Identity {1}.", login1.Id, identity.Uid), Guid.Empty);

                LoginData login2 = new LoginData()
                {
                    IdentityId = identity.Uid,
                    ApplicationCode = "LA",
                    LoginName = "system",
                    Password = "******",
                    RoleCode = "LAUSER",
                    T24Id = i.ToString()
                };
                login2.Id = RepositoryFactory.LoginRepository.Add(login2);
                Audit.AuditEvent(Audit.EventTypes.AddLogin, string.Format("Login {0} has been added for Identity {1}.", login2.Id, identity.Uid), Guid.Empty);

                EnrollmentData enroll1 = new EnrollmentData()
                {
                    IdentityId = identity.Uid,
                    AdministratorId = adminId,
                    AuthenticationTypeCode = "FP"
                };
                enroll1.Uid = RepositoryFactory.EnrollmentRepository.Add(enroll1);
                Audit.AuditEvent(Audit.EventTypes.AddEnrollment, string.Format("Enrollment {0} has been added for Identity {1}.", enroll1.Uid, identity.Uid), Guid.Empty);
                //now add the templates to go along with the enrollment
                List<int> temps1 = new List<int>();
                for (int j = 0; j < 10; j++)
                {
                    int tempIndex;
                    do
                    {
                        tempIndex = rndTemplate.Next(templates.Count - 1);
                    } while (temps1.Contains(tempIndex));
                    temps1.Add(tempIndex);
                    AuthenticationTemplateData temp = new AuthenticationTemplateData()
                    {
                        AuthenticationUnitCode = templates[tempIndex].AuthenticationUnitCode,
                        EnrollmentId = enroll1.Uid,
                        Score = templates[tempIndex].Score,
                        Template = templates[tempIndex].Template
                    };
                    temp.Uid = RepositoryFactory.AuthenticationTemplateRepository.Add(temp);
                    Audit.AuditEvent(Audit.EventTypes.AddAuthenticationTemplate, string.Format("Authentication Template {0} has been added for Enrollment {1}.", temp.Uid, enroll1.Uid), Guid.Empty);
                }

                if (i % 5 == 0)
                {
                    EnrollmentData enroll2 = new EnrollmentData()
                    {
                        IdentityId = identity.Uid,
                        AdministratorId = adminId,
                        AuthenticationTypeCode = "FP"
                    };
                    enroll2.Uid = RepositoryFactory.EnrollmentRepository.Add(enroll2);
                    Audit.AuditEvent(Audit.EventTypes.AddEnrollment, string.Format("Enrollment {0} has been added for Identity {1}.", enroll2.Uid, identity.Uid), Guid.Empty);
                    //now add the templates to go along with the enrollment
                    List<int> temps2 = new List<int>();
                    for (int j = 0; j < 10; j++)
                    {
                        int tempIndex;
                        do
                        {
                            tempIndex = rndTemplate.Next(templates.Count - 1);
                        } while (temps2.Contains(tempIndex));
                        temps2.Add(tempIndex);
                        AuthenticationTemplateData temp = new AuthenticationTemplateData()
                        {
                            AuthenticationUnitCode = templates[tempIndex].AuthenticationUnitCode,
                            EnrollmentId = enroll2.Uid,
                            Score = templates[tempIndex].Score,
                            Template = templates[tempIndex].Template
                        };
                        temp.Uid = RepositoryFactory.AuthenticationTemplateRepository.Add(temp);
                        Audit.AuditEvent(Audit.EventTypes.AddAuthenticationTemplate, string.Format("Authentication Template {0} has been added for Enrollment {1}.", temp.Uid, enroll2.Uid), Guid.Empty);
                    }
                }

                //every fifth identity added becomes the enrollment officer for the next 5
                if (i % 5 == 0) adminId = identity.Uid;
            }
        }
示例#31
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Resources.VaultTarget, "set"))
            {
                try
                {
                    IdentityData MSI   = new IdentityData();
                    Vault        vault = RecoveryServicesClient.GetVault(this.ResourceGroupName, this.Name);

                    if (ParameterSetName == AzureRSVaultAddMSIdentity)
                    {
                        if (IdentityType == MSIdentity.SystemAssigned)
                        {
                            if (IdentityId != null)
                            {
                                throw new ArgumentException(Resources.InvalidParameterIdentityId);
                            }

                            if (vault.Identity != null && vault.Identity.Type.ToLower().Contains("userassigned"))
                            {
                                MSI.Type = MSIdentity.SystemAssigned.ToString() + "," + MSIdentity.UserAssigned.ToString();
                            }
                            else
                            {
                                MSI.Type = MSIdentity.SystemAssigned.ToString();
                            }
                        }
                        else if (IdentityType == MSIdentity.None)
                        {
                            MSI.Type = MSIdentity.None.ToString();
                        }
                        else if (IdentityType == MSIdentity.UserAssigned)
                        {
                            if (IdentityId == null)
                            {
                                throw new ArgumentException(Resources.IdentityIdRequired);
                            }

                            if (vault.Identity != null && vault.Identity.Type.ToLower().Contains("systemassigned"))
                            {
                                MSI.Type = MSIdentity.SystemAssigned.ToString() + "," + MSIdentity.UserAssigned.ToString();
                            }
                            else
                            {
                                MSI.Type = MSIdentity.UserAssigned.ToString();
                            }

                            MSI.UserAssignedIdentities = new Dictionary <string, UserIdentity>();
                            foreach (string userIdentityId in IdentityId)
                            {
                                MSI.UserAssignedIdentities.Add(userIdentityId, new UserIdentity());
                            }
                        }
                    }
                    else
                    {
                        if (RemoveSystemAssigned.IsPresent)
                        {
                            if (IdentityId != null || RemoveUserAssigned.IsPresent)
                            {
                                throw new ArgumentException(Resources.InvalidIdentityRemove);
                            }

                            if (vault.Identity != null && vault.Identity.Type.ToLower().Contains("systemassigned"))
                            {
                                if (vault.Identity.Type.ToLower().Contains("userassigned"))
                                {
                                    MSI.Type = MSIdentity.UserAssigned.ToString();
                                }
                                else
                                {
                                    MSI.Type = MSIdentity.None.ToString();
                                }
                            }
                        }
                        else if (RemoveUserAssigned.IsPresent)
                        {
                            if (IdentityId == null)
                            {
                                throw new ArgumentException(Resources.IdentityIdRequired);
                            }

                            foreach (string identity in IdentityId)
                            {
                                if (!vault.Identity.UserAssignedIdentities.ContainsKey(identity))
                                {
                                    throw new ArgumentException(String.Format(Resources.InvalidIdentityId, identity));
                                }
                            }

                            if (vault.Identity != null && vault.Identity.Type.ToLower().Contains("userassigned"))
                            {
                                if (vault.Identity.Type.ToLower().Contains("systemassigned"))
                                {
                                    if (vault.Identity.UserAssignedIdentities.Keys.Count == IdentityId.Length)
                                    {
                                        MSI.Type = MSIdentity.SystemAssigned.ToString();
                                    }
                                    else
                                    {
                                        MSI.Type = MSIdentity.SystemAssigned.ToString() + "," + MSIdentity.UserAssigned.ToString();
                                    }
                                }
                                else
                                {
                                    if (vault.Identity.UserAssignedIdentities.Keys.Count == IdentityId.Length)
                                    {
                                        MSI.Type = MSIdentity.None.ToString();
                                    }
                                    else
                                    {
                                        MSI.Type = MSIdentity.UserAssigned.ToString();
                                    }
                                }

                                if (MSI.Type != "SystemAssigned" && MSI.Type != "None")
                                {
                                    MSI.UserAssignedIdentities = new Dictionary <string, UserIdentity>();
                                    foreach (string userIdentityId in IdentityId)
                                    {
                                        MSI.UserAssignedIdentities.Add(userIdentityId, null);
                                    }
                                }
                            }
                        }
                        else
                        {
                            throw new ArgumentException(Resources.InvalidParameterSet);
                        }
                    }

                    PatchVault patchVault = new PatchVault();
                    patchVault.Identity = MSI;
                    vault = RecoveryServicesClient.UpdateRSVault(this.ResourceGroupName, this.Name, patchVault);
                    WriteObject(new ARSVault(vault));
                }
                catch (Exception exception)
                {
                    WriteExceptionError(exception);
                }
            }
        }