Exemple #1
0
 public Config(Apis api, string username, string password, string server)
 {
     Api      = api;
     Username = username;
     Password = password;
     Server   = server;
 }
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddHttpClient("BlazorApp.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
            .AddHttpMessageHandler <BaseAddressAuthorizationMessageHandler>();

            // Supply HttpClient instances that include access tokens when making requests to the server project
            builder.Services.AddTransient(sp => sp.GetRequiredService <IHttpClientFactory>().CreateClient("BlazorApp.ServerAPI"));

            builder.Services.AddApiAuthorization();

            Apis apis = new Apis();

            Configuration.GetSection("Apis").Bind(apis);
            var oidcApi = apis.Single(a => a.Key == "OidcProvider").Value;

            builder.Services.AddOidcAuthentication(options => {
                options.ProviderOptions.Authority    = $"https://{oidcApi.Host}:{oidcApi.HttpsPort}";
                options.ProviderOptions.ClientId     = "BlazorApp.Client";
                options.ProviderOptions.ResponseType = "code";
                options.ProviderOptions.DefaultScopes.Add("roles");
            });



            await builder.Build().RunAsync();
        }
 public TkbTuanTruongForm(MainForm main, DateTime ngay)
 {
     this.main = main;
     apis      = main.Apis;
     this.date = ngay;
     InitializeComponent();
 }
Exemple #4
0
 public LabelConfig()
 {
     Apis.Add(_GetLabelConfigBySkuno.FunctionName, _GetLabelConfigBySkuno);
     Apis.Add(_AlertLabelConfig.FunctionName, _AlertLabelConfig);
     Apis.Add(_RemoveLabelConfig.FunctionName, _RemoveLabelConfig);
     Apis.Add(_GetLabelTypes.FunctionName, _GetLabelTypes);
 }
Exemple #5
0
        /// <summary>
        /// 群消息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns>0不拦截 1拦截消息</returns>
        public override int GroupMsgProcess(GroupMsg msg, long CurrentQQ)
        {
            Console.WriteLine($"GroupMsgProcess {CurrentQQ}\n" + JsonConvert.SerializeObject(msg));
            if (msg.FromGroupId != 516141713)
            {
                return(0);
            }
            if (msg.MsgType == MsgType.PicMsg)
            {
                var picContent = msg.GetPic();
                Apis.SendGroupMsg(msg.FromGroupId,
                                  picContent.Content + CodeUtils.At(msg.FromUserId) +
                                  CodeUtils.Pic_Http(picContent.FriendPic.FirstOrDefault().Url));
            }
            else if (msg.MsgType == MsgType.VoiceMsg)
            {
                var voiceContent = msg.GetVoice();
                Apis.SendGroupMsg(msg.FromGroupId, voiceContent.Content + CodeUtils.Voice_Http(voiceContent.Url));
            }
            else
            {
                Apis.SendGroupMsg(msg.FromGroupId, msg.Content + CodeUtils.At(msg.FromUserId));
            }

            Apis.RevokeMsg(new RevokeMsgReq
            {
                GroupID = msg.FromGroupId, MsgRandom = msg.MsgRandom, MsgSeq = msg.MsgRandom
            });
            return(0);
        }
Exemple #6
0
        public static void DeleteOAuthLink(int userId)
        {
            var clientUserId = GetOAuthClientUserId(userId);

            try
            {
                using (var conn = GetSqlConnection())
                {
                    using (var command =
                               new SqlCommand($"[{databaseOwner}].[te_OAuth_RemoveLink]", conn)
                    {
                        CommandType = CommandType.StoredProcedure
                    })
                    {
                        command.Parameters.Add("@ClientType", SqlDbType.NVarChar).Value   = "saml";
                        command.Parameters.Add("@ClientUserId", SqlDbType.NVarChar).Value = clientUserId;
                        command.Parameters.Add("@UserId", SqlDbType.Int).Value            = userId;
                        conn.Open();
                        command.ExecuteScalar();
                    }
                }
            }
            catch (Exception ex)
            {
                Apis.Get <IEventLog>()
                .Write($"Could not delete OAuth Link for user {userId}. {ex}",
                       new EventLogEntryWriteOptions()
                {
                    Category = "SAML", EventId = 6022, EventType = "Error"
                });
            }
        }
Exemple #7
0
        private bool IsValidReturnUrl(string returnUrl)
        {
            var apiCoreUrls = Apis.Get <ICoreUrls>();

            if (!string.IsNullOrEmpty(returnUrl) &&
                !(
                    returnUrl.IndexOf("MessageID") != -1 ||
                    returnUrl.IndexOf(apiCoreUrls.Banned()) != -1 ||
                    returnUrl.IndexOf(apiCoreUrls.NotFound()) != -1 ||
                    returnUrl.IndexOf("changepassword") != -1 ||
                    returnUrl.IndexOf("emailforgottenpassword") != -1 ||
                    returnUrl.IndexOf("/samlauthn") != -1 ||
                    returnUrl.IndexOf("/samlresponse") != -1 ||
                    returnUrl.IndexOf("/oauth") != -1 ||
                    returnUrl.IndexOf("/login") != -1 ||
                    returnUrl.IndexOf("/logout") != -1 ||
                    returnUrl.IndexOf("/samllogout") != -1
                    )
                )
            {
                return(true);
            }

            return(false);
        }
Exemple #8
0
        public static string GetTokenData(string tokenKey)
        {
            try
            {
                using (var conn = GetSqlConnection())
                {
                    var sql =
                        $"SELECT EncryptedData FROM [{databaseOwner}].[db_SamlTempTokenData] WHERE TokenKey = @TokenKey";

                    var command = new SqlCommand(sql, conn)
                    {
                        CommandType = CommandType.Text
                    };

                    command.Parameters.Add("@TokenKey", SqlDbType.UniqueIdentifier).Value = Guid.Parse(tokenKey);
                    conn.Open();

                    return((string)command.ExecuteScalar());
                }
            }
            catch (Exception ex)
            {
                Apis.Get <IEventLog>().Write("Error reading from db_SamlTempTokenData; I dont think its installed. " + ex, new EventLogEntryWriteOptions()
                {
                    Category = "SAML", EventId = 6022, EventType = "Error"
                });
                return(string.Empty);
            }
        }
Exemple #9
0
 public TkbHocKyTieuDoanForm(MainForm frm, string tieuDoan)
 {
     main          = frm;
     apis          = frm.Apis;
     this.tieuDoan = tieuDoan;
     InitializeComponent();
 }
Exemple #10
0
 public HocKyForm(MainForm main)
 {
     this.apis = main.Apis;
     hocKy     = main.HocKy;
     this.main = main;
     InitializeComponent();
 }
Exemple #11
0
 public SkuSeries()
 {
     this.Apis.Add(_FetchCurrentSeries.FunctionName, _FetchCurrentSeries);
     this.Apis.Add(_DeleteSeriesById.FunctionName, _DeleteSeriesById);
     this.Apis.Add(_AddNewSeries.FunctionName, _AddNewSeries);
     Apis.Add(_UpdateSeries.FunctionName, _UpdateSeries);
 }
        /// <summary>
        /// 私聊消息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns>0不拦截 1拦截消息</returns>
        public override int FriendMsgProcess(FriendMsg msg, long CurrentQQ)
        {
            Console.WriteLine($"FriendMsgProcess {CurrentQQ}\n" + JsonConvert.SerializeObject(msg));
            switch (msg.MsgType)
            {
            case MsgType.PicMsg:
            {
                var picContent = msg.GetPic();
                Apis.SendFriendMsg(msg.FromUin,
                                   picContent.Content + CodeUtils.Pic_Http(picContent.FriendPic.FirstOrDefault().Url));
                break;
            }

            case MsgType.VoiceMsg:
            {
                var voiceContent = msg.GetVoice();
                Apis.SendFriendMsg(msg.FromUin, voiceContent.Content + CodeUtils.Voice_Http(voiceContent.Url));
                break;
            }

            default:
                Apis.SendFriendMsg(msg.FromUin, msg.Content);
                break;
            }

            return(0);
        }
Exemple #13
0
        public void GetUserDetailInfoTest()
        {
            UserBaseInfoResp   res1 = Apis.GetUserBaseInfo("wantcnm.Tang");
            UserDetailInfoResp res  = Apis.GetUserDetailInfo(res1);

            Assert.Fail();
        }
Exemple #14
0
        public static void SaveEncryptedSamlToken(Guid tokenKey, string encryptedData)
        {
            try
            {
                using (var conn = GetSqlConnection())
                {
                    var sql = $"INSERT INTO [{databaseOwner}].[db_SamlTempTokenData]" +
                              "(TokenKey" +
                              ", EncryptedData)" +
                              "VALUES" +
                              "(@TokenKey" +
                              ",@EncryptedData)";

                    var myCommand = new SqlCommand(sql, conn)
                    {
                        CommandType = CommandType.Text
                    };

                    myCommand.Parameters.Add("@TokenKey", SqlDbType.UniqueIdentifier).Value = tokenKey;
                    myCommand.Parameters.Add("@EncryptedData", SqlDbType.NVarChar).Value    = encryptedData;

                    conn.Open();
                    myCommand.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                Apis.Get <IEventLog>().Write("Error inserting token into the db_SamlTempTokenData table. " + ex, new EventLogEntryWriteOptions()
                {
                    Category = "SAML", EventId = 6023, EventType = "Error"
                });
            }
        }
Exemple #15
0
 static SampleRestServer()
 {
     Apis.Add(Http.Method.Get, "/plaintext", Api.HelloWorld, WriteResponseForHelloWorld);
     Apis.Add(Http.Method.Get, "/time", Api.GetTime, WriteResponseForGetTime);
     Apis.Add(Http.Method.Get, "/json", Api.GetJson, WriteResponseForGetJson);
     Apis.Add(Http.Method.Post, "/jsonpost", Api.PostJson, WriteResponseForPostJson); // post body along the lines of: "{ "Count" = 3 }"
 }
Exemple #16
0
 public PackConfigAPI()
 {
     Apis.Add(_GetPackConfigBySKUNO.FunctionName, _GetPackConfigBySKUNO);
     Apis.Add(_AlertPackConfig.FunctionName, _AlertPackConfig);
     Apis.Add(_GetPackType.FunctionName, _GetPackType);
     Apis.Add(_GetTransportType.FunctionName, _GetTransportType);
 }
Exemple #17
0
        public HttpResponseMock GetResponseMock(string url, string method)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            if (string.IsNullOrEmpty(method))
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (Apis == null)
            {
                throw new InvalidOperationException($"Try to get fake response for url {url} but apis config not loaded");
            }

            var apiCfg = Apis.Where(a => 
 TemplateMatcher.Match(new Uri(a.Url), new Uri(url)) 
&& a.Responses != null) 
.SelectMany(a => a.Responses) 
.SingleOrDefault(a => a.Active
 && (string.Equals(a.Method ?? DefaultMethod, method, StringComparison.InvariantCultureIgnoreCase)));

            if (apiCfg == null)
            {
                return(new HttpResponseMock());
            }

            return(apiCfg);
        }
        public async Task <PagedQuery <ApiResourceDTO> > SearchAsync(SearchDTO search)
        {
            var query = from api in Apis
                        .Include(x => x.UserClaims)
                        .Include(o => o.Secrets)
                        .Include(o => o.Scopes)
                        .ThenInclude(s => s.UserClaims)
                        orderby api.Name
                        select api;

            if (!string.IsNullOrWhiteSpace(search.Search))
            {
                query = from obj in query
                        where obj.Name.Contains(search.Search)
                        orderby obj.Name
                        select obj;
            }

            var items = await query.Select(s => s.ToDTO()).ToListAsync();

            var result = new PagedQuery <ApiResourceDTO>
            {
                Count = search.Count,
                Items = items,
                Start = search.Start,
                Total = items.Count()
            };

            return(result);
        }
Exemple #19
0
        public static Guid?GetCookieInvitationKey()
        {
            try
            {
                HttpCookie returnUrlCookie = HttpContext.Current.Request.Cookies[ReturnUrlCookieName];
                if (returnUrlCookie != null && returnUrlCookie.Values[InvitationKeyParameterName] != null &&
                    !string.IsNullOrEmpty(returnUrlCookie.Values[InvitationKeyParameterName]))
                {
                    var paresedGuid = Guid.Parse(returnUrlCookie.Values[InvitationKeyParameterName]);
                    if (paresedGuid != Guid.Empty)
                    {
                        return(paresedGuid);
                    }
                }
            }
            catch (Exception ex)
            {
                Apis.Get <IEventLog>().Write("ERROR trying to extract Invitation from cookie:" + ex.ToString(), new EventLogEntryWriteOptions()
                {
                    Category = "SAML", EventId = 6019, EventType = "Error"
                });
            }

            return(null);
        }
Exemple #20
0
        public void Validate()
        {
            if (Apis == null || !Apis.Any())
            {
                throw new Exception("No apis configured");
            }

            if (Apis.Any(a => string.IsNullOrEmpty(a.Url)))
            {
                throw new Exception("At least one api has no url configured");
            }

            var responses = Apis.Where(a => a.Responses != null).SelectMany(a => a.Responses).ToList();

            if (string.IsNullOrEmpty(DefaultMethod) &&
                (!responses.Any() || responses.Any(r => string.IsNullOrEmpty(r.Method))))
            {
                throw new Exception("At least one api has no http method configured");
            }

            if (string.IsNullOrEmpty(DefaultResponse) &&
                (!responses.Any() ||
                 responses.Any(r => !r.HasFile && !r.HasFiles && !r.HasWebException && !r.HasCustomException && string.IsNullOrEmpty(r.Response))))
            {
                throw new Exception("At least one api has no response configured");
            }
        }
Exemple #21
0
        private void ParseForumContext(PageContext context)
        {
            var appKey    = context.GetTokenValue("ForumApp");
            var forumsApi = Apis.Get <IForums>();
            var groupsApi = Apis.Get <IGroups>();

            if (appKey != null)
            {
                var groupItem = context.ContextItems.GetAllContextItems().FirstOrDefault(a => a.ContentTypeId == groupsApi.ContentTypeId);
                if (groupItem != null)
                {
                    /**workaround until **/
                    var forums = forumsApi.List(new ForumsListOptions {
                        GroupId = int.Parse(groupItem.Id), PageSize = 200
                    });
                    var forum = forums.FirstOrDefault(f => f.Url.Contains(appKey.ToString())); // forumsApi.Get(new ForumsGetOptions() { GroupId = int.Parse(groupItem.Id), Key = appKey.ToString() });
                    if (forum != null)
                    {
                        var contextItem = new ContextItem()
                        {
                            TypeName          = "Forum",
                            ApplicationId     = forum.ApplicationId,
                            ApplicationTypeId = forumsApi.ApplicationTypeId,
                            ContainerId       = forum.Group.ApplicationId,
                            ContainerTypeId   = groupsApi.ContentTypeId,
                            ContentId         = forum.ApplicationId,
                            ContentTypeId     = forumsApi.ApplicationTypeId,
                            Id = forum.Id.ToString()
                        };

                        context.ContextItems.Put(contextItem);
                    }
                }
            }
        }
Exemple #22
0
        public static void DeleteTokenData(string tokenKey)
        {
            try
            {
                using (var conn = GetSqlConnection())
                {
                    var sql =
                        $"DELETE FROM [{databaseOwner}].[db_SamlTempTokenData] WHERE TokenKey = @TokenKey";

                    var command = new SqlCommand(sql, conn)
                    {
                        CommandType = CommandType.Text
                    };

                    command.Parameters.Add("@TokenKey", SqlDbType.UniqueIdentifier).Value = Guid.Parse(tokenKey);
                    conn.Open();
                    command.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                Apis.Get <IEventLog>().Write("Error deleting from db_SamlTokenData; I dont think its installed. " + ex, new EventLogEntryWriteOptions()
                {
                    Category = "SAML", EventId = 6024, EventType = "Error"
                });
            }
        }
Exemple #23
0
        private async void GiangVien_Load(object sender, EventArgs e)
        {
            Apis apis = new Apis(jwt);

            giangViens = await apis.GetGiangViens();

            gridGiangViens.DataSource = giangViens;
        }
Exemple #24
0
        public void Initialize()
        {
            _usersApi    = Apis.Get <IUsers>();
            _eventLogApi = Apis.Get <IEventLog>();

            SamlEvents.Instance.AfterAuthenticate += Instance_AfterAuthenticate;
            SamlEvents.Instance.AfterCreate       += Instance_AfterCreate;
        }
        public XepTietHocForm(MainForm main)
        {
            this.main  = main;
            this.apis  = main.Apis;
            this.HocKy = main.HocKy;

            InitializeComponent();
        }
 public TraCuuTheoLopForm(MainForm main, DateTime dt)
 {
     InitializeComponent();
     this.apis = main.Apis;
     hocKy     = main.HocKy;
     SetDate(dt);
     txtLop.Focus();
 }
Exemple #27
0
 /// <summary>
 /// Указывает тип соединения, платформу и язык, которые будут использоваться при загрузке данных
 /// </summary>
 /// <param name="httpvalue"> Http или HttpS</param>
 /// <param name="apivalue">API или WS</param>
 /// <param name="_platform">Для какой платформы считывать данные</param>
 /// <param name="_languege">язык данных</param>
 public static void SetOption(HTTPs httpvalue, Apis apivalue, string _platform, string _languege)
 {
     https    = httpvalue;
     api      = apivalue;
     platform = _platform;
     languege = _languege;
     url      = https.ToString() + "://" + api.ToString() + ".warframestat.us/" + platform;
 }
Exemple #28
0
        public async Task OnGetAsync()
        {
            Apis = await _apiManager.LoadApisAsync();

            ApiDescriptions = _provider.ApiDescriptionGroups.Items.SelectMany(x => x.Items)
                              .Where(x => Apis.Any(api => api.Name.Equals(x.RelativePath, StringComparison.OrdinalIgnoreCase)))
                              .ToList();
        }
 public MESMessageConfig()
 {
     this.Apis.Add(FGetAllMESMessage.FunctionName, FGetAllMESMessage);
     this.Apis.Add(FUpdateMESMessage.FunctionName, FUpdateMESMessage);
     this.Apis.Add(FAddMESMessage.FunctionName, FAddMESMessage);
     this.Apis.Add(FDeleteMESMessageByID.FunctionName, FDeleteMESMessageByID);
     Apis.Add(_GetDetail.FunctionName, _GetDetail);
 }
        public async Task <ApiResourceDTO> AddAsync(ApiResourceDTO dto)
        {
            var entity = dto.ToEntity();
            await Apis.AddAsync(entity);

            await Context.SaveChangesAsync();

            return(entity.ToDTO());
        }
 /// <summary>
 /// Deletes the bucket object from the Google Cloud Storage bucket.
 /// </summary>
 public void DeleteObject(Apis.Storage.v1.Data.Object bucketObject)
 {
     _bucketService.Objects.Delete(bucketObject.Bucket, bucketObject.Name).Execute();
 }
 /// <summary>
 /// Adjusts the ACL for an uploaded object so that a SQL instance can access it.
 /// </summary>
 public void AdjustAcl(Apis.Storage.v1.Data.Object bucketObject, string instanceEmail)
 {
     ObjectAccessControl body = new ObjectAccessControl();
     body.Bucket = bucketObject.Bucket;
     body.Entity = "user-" + instanceEmail;
     body.Role = "OWNER";
     body.Object__ = bucketObject.Name;
     ObjectAccessControlsResource.InsertRequest aclRequest =
         _bucketService.ObjectAccessControls.Insert(body, bucketObject.Bucket, bucketObject.Name);
     try
     {
         aclRequest.Execute();
     }
     catch (Exception e)
     {
         DeleteObject(bucketObject);
         _bucketService.Buckets.Delete(bucketObject.Bucket).Execute();
         throw e;
     }
 }