Inheritance: System.Web.UI.Page
コード例 #1
0
 //检测当前用户是否有当前页面权限
 private bool CheckPageAuth(Auth.AuthContext ctx)
 {
     try
     {
         NHExt.Runtime.Proxy.AgentInvoker invoker = new NHExt.Runtime.Proxy.AgentInvoker();
         string proxy = NHExt.Runtime.Cfg.GetCfg<string>("PageAuthProxy");//配置文件
         if (!string.IsNullOrEmpty(proxy))
         {
             invoker.AssemblyName = proxy;
             invoker.DllName = proxy.Substring(0, proxy.LastIndexOf(".")) + ".dll";
         }
         else
         {
             invoker.AssemblyName = "IWEHAVE.ERP.Auth.ServiceBP.Agent.GetPageAuthByGUIDBPProxy";
             invoker.DllName = "IWEHAVE.ERP.Auth.ServiceBP.Agent.dll";
         }
         invoker.AppendField(new NHExt.Runtime.Proxy.PropertyField() { FieldName = "PageGUID", FieldValue = this.PageGuid });
         invoker.SourcePage = this.PageGuid;
         return invoker.Do<bool>();
     }
     catch (NHExt.Runtime.Exceptions.BizException ex)
     {
         NHExt.Runtime.Logger.LoggerHelper.Error(ex, NHExt.Runtime.Logger.LoggerInstance.BizLogger);
     }
     catch (NHExt.Runtime.Exceptions.RuntimeException ex)
     {
         NHExt.Runtime.Logger.LoggerHelper.Error(ex, NHExt.Runtime.Logger.LoggerInstance.RuntimeLogger);
     }
     catch (Exception ex)
     {
         NHExt.Runtime.Logger.LoggerHelper.Error(ex, NHExt.Runtime.Logger.LoggerInstance.RuntimeLogger);
     }
     return false;
 }
コード例 #2
0
    protected void submit_Click(object sender, EventArgs e)
    {
        Auth auth = new Auth();
        SQLDB db = new SQLDB();

        string netname_user = "";
        string user = User.Identity.Name.ToUpper();
        if (user.Contains("\\"))
            netname_user = user.Substring(user.IndexOf('\\') + 1, user.Length - user.IndexOf('\\') - 1);
        if (db.isAccessAllowed(netname_user))
        {
            string netname = Netname.Text.ToUpper();
            string login = Login.Text.ToUpper();
            string password = Password.Text;
            if (netname.Length < 3)
            {
                MessageBox.Show("Сотрудник не найден!");
                return;
            }
            Employee employee = auth.Authentication(netname, login, password);
            if (employee != null)
                Response.Redirect("Default.aspx?netname=" + employee.Netname);
            else
                MessageBox.Show("Сотрудник не найден!");
        }
        else
        {
            MessageBox.Show("У вас недостаточно прав доступа для входа!");
        }
    }
コード例 #3
0
ファイル: ListService.cs プロジェクト: vivlong/EventListWS
 public void ListJobNo(Auth auth, List_JobNo request, List_JobNo_Logic list_JobNo_Logic, CommonResponse ecr, string[] token, string uri)
 {
     if (auth.AuthResult(token, uri))
     {
         List<job> JobList = new List<job>();
         HashSet<string> hsResult = list_JobNo_Logic.GetList(request);
         if (hsResult.Count > 0)
         {
             ecr.meta.code = 200;
             ecr.meta.message = "OK";
         }
         else
         {
             ecr.meta.code = 612;
             ecr.meta.message = "The specified resource does not exist";
         }
         foreach (string strJobNo in hsResult)
         {
             job j = new job();
             j.JobNo = strJobNo;
             j.ContainerCounts = list_JobNo_Logic.GetCount(request.PhoneNumber, strJobNo).ToString();
             JobList.Add(j);
         }
         ecr.data.results = JobList;
     }
     else
     {
         ecr.meta.code = 401;
         ecr.meta.message = "Unauthorized";
     }
 }
コード例 #4
0
ファイル: JsonHandler.cs プロジェクト: exosite-labs/clronep
 internal static string getRequest(string parentkey, string id, string proc, object[] args, bool connect_as)
 {
     if (proc == "writegroup")
     {
         List<object> newArgs = new List<object>();
         foreach (Dictionary<string, object> dict in args)
         {
             foreach (KeyValuePair<string, object> kvp in dict)
             {
                 object[] formattingArray = new object[2];
                 formattingArray[0] = kvp.Key;
                 formattingArray[1] = kvp.Value;
                 newArgs.Add(formattingArray);
             }
             args[0] = newArgs.ToArray();
         }
     }
     Call call = new Call { id = 1, procedure = proc, arguments = args };
     Call[] calls = new Call[] { call };
     Auth auth;
     if (connect_as)
     {
         auth = new Auth { cik = parentkey, client_id = id };
     }
     else
     {
         auth = new Auth { cik = parentkey, resource_id = id };
     }
     Request req = new Request { auth = auth, calls = calls };
     return JsonConvert.SerializeObject(req, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
 }
コード例 #5
0
 public Platform(string appKey, string appSecret, string serverUrl, string appName = "", string appVersion = "")
 {
     this.appKey = appKey;
     this.appSecret = appSecret;
     this.ServerUrl = serverUrl;
     Auth = new Auth();
     _client = new HttpClient { BaseAddress = new Uri(this.ServerUrl) };
     SetUserAgentHeader(appName, appVersion);
 }
コード例 #6
0
ファイル: SyncClient.cs プロジェクト: Guiedo/SunDofus
        public void SendTicket(string key, Auth.AuthClient client)
        {
            var datas = new object[] { key, client.Account.ID, client.Account.Pseudo, client.Account.Question,
                client.Account.Answer, client.Account.Level, string.Join(",", client.Account.Characters[Server.ID].ToArray()),
                client.Account.SubscriptionTime(), string.Join("+", Entities.Requests.GiftsRequests.GetGiftsByAccountID(client.Account.ID)),
                string.Join("+", client.Account.Friends), string.Join("+", client.Account.Enemies) };

            Send(new Packets.PTransfer().GetPacket(datas));
        }
コード例 #7
0
ファイル: FormAbout.cs プロジェクト: northspb/p2pproxy
 public FormAbout(P2pProxyApp app, Auth state)
 {
     InitializeComponent();
     _app = app;
     labelVersion.Text = labelVersion.Text + Application.ProductVersion;
     labelUser.Text = labelUser.Text + state.Login;
     labelBalance.Text = labelBalance.Text + state.balance + "р.";
     textUdn.Text = _app.Device.Udn.ToString();
 }
コード例 #8
0
ファイル: auth.ashx.cs プロジェクト: nirgle/irception.org
        public void ProcessRequest(HttpContext context)
        {
            string json;

            try
            {
                var requestBody = context.Request.Form["RequestBody"];
                var requestParams = API.GetAuthRequestParams(requestBody);
                var repo = new Repository();

                if (repo.HaveAuth(requestParams.NetworkID, requestParams.Nick, requestParams.Username, requestParams.Host))
                {
                    json = JsonConvert.SerializeObject(new
                    {
                        success = true,
                        alreadyAuthenticated = true
                    });
                }
                else
                {
                    // Create a new auth record for the user, give him the UID for the web
                    Auth auth = new Auth
                    {
                        FKNetworkID = requestParams.NetworkID,
                        Nick = requestParams.Nick,
                        Username = requestParams.Username,
                        Host = requestParams.Host,
                        SUID = Utils.Get32ByteUID(),
                        DateIssued = DateTime.UtcNow
                    };

                    repo.AddAuth(auth);
                    repo.SaveChanges();

                    json = JsonConvert.SerializeObject(new
                    {
                        success = true,
                        ID = auth.AuthID,
                        SUID = auth.SUID
                    });
                }
            }
            catch (Exception ex)
            {
                json = JsonConvert.SerializeObject(new
                {
                    success = false,
                    error = "There was an exception: " + ex.Message
                });
            }

            SetNoCaching(context);
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
        }
コード例 #9
0
        /// <summary>The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. Overridable so you can provide your own Auth implementation.</summary>
        ///
        /// <exception cref="Unauthorized">Thrown when an unauthorized error condition occurs.</exception>
        ///
        /// <param name="authService">The authentication service.</param>
        /// <param name="session">    The session.</param>
        /// <param name="request">    The request.</param>
        ///
        /// <returns>An object.</returns>
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var httpReq = authService.RequestContext.Get<IHttpRequest>();
            var basicAuth = httpReq.GetBasicAuthUserAndPassword();
            if (basicAuth == null)
                throw HttpError.Unauthorized("Invalid BasicAuth credentials");

            var userName = basicAuth.Value.Key;
            var password = basicAuth.Value.Value;

            return Authenticate(authService, session, userName, password, request.Continue);
        }
コード例 #10
0
ファイル: Authorization.cs プロジェクト: SparkDevNetwork/Rock
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthRule"/> class.
 /// </summary>
 /// <param name="auth">The auth.</param>
 public AuthRule( Auth auth )
     : this()
 {
     Id = auth.Id;
     EntityId = auth.EntityId;
     AllowOrDeny = auth.AllowOrDeny == "A" ? 'A' : 'D';
     SpecialRole = auth.SpecialRole;
     PersonId = auth.PersonAlias != null ? auth.PersonAlias.PersonId : ( int? ) null;
     PersonAliasId = auth.PersonAliasId;
     GroupId = auth.GroupId;
     Order = auth.Order;
 }
コード例 #11
0
        /// <summary>The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. Overridable so you can provide your own Auth implementation.</summary>
        ///
        /// <param name="authService">.</param>
        /// <param name="session">    .</param>
        /// <param name="request">    .</param>
        ///
        /// <returns>An object.</returns>
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = Init(authService, ref session, request);

            var error = authService.RequestContext.Get<IHttpRequest>().QueryString["error"];
            var hasError = !error.IsNullOrEmpty();
            if (hasError)
            {
                Log.Error("Facebook error callback. {0}".Fmt(authService.RequestContext.Get<IHttpRequest>().QueryString));
                return authService.Redirect(session.ReferrerUrl);
            }

            var code = authService.RequestContext.Get<IHttpRequest>().QueryString["code"];
            var isPreAuthCallback = !code.IsNullOrEmpty();
            if (!isPreAuthCallback)
            {
                var preAuthUrl = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}"
                    .Fmt(AppId, this.CallbackUrl.UrlEncode(), string.Join(",", Permissions));

                authService.SaveSession(session, SessionExpiry);
                return authService.Redirect(preAuthUrl);
            }

            var accessTokenUrl = this.AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}"
                .Fmt(AppId, this.CallbackUrl.UrlEncode(), AppSecret, code);

            try
            {
                var contents = accessTokenUrl.GetStringFromUrl();
                var authInfo = HttpUtility.ParseQueryString(contents);
                tokens.AccessTokenSecret = authInfo["access_token"];
                session.IsAuthenticated = true;
                authService.SaveSession(session, SessionExpiry);
                OnAuthenticated(authService, session, tokens, authInfo.ToDictionary());

                //Haz access!
                return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));
            }
            catch (WebException we)
            {
                var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"));
                }
            }

            //Shouldn't get here
            return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
        }
コード例 #12
0
		// GET: Authorize/Authorize
		public async Task<ActionResult> Index(string redirect)
		{
			var auth = new Auth();

			var requestTokenCookie = Request.Cookies[Auth.RequestTokenCookieId];
			var requestTokenSecretCookie = Request.Cookies[Auth.RequestTokenSecretCookieId];
			var requestToken = Auth.GetTokenFromCookies(requestTokenCookie, requestTokenSecretCookie);

			var accessToken = await auth.TumblrAuthClient.GetAccessTokenAsync(requestToken, Request.QueryString.ToString());
			Auth.StoreAccessTokenCookie(accessToken, Response);

			var redirectTo = HttpUtility.UrlDecode(redirect);
			return Redirect(redirectTo);
		}
コード例 #13
0
ファイル: LoginUI.cs プロジェクト: Jarisha/Social-Slots
 void LoginPressed()
 {
     ConnectionProxy.CreateConnection(HOSTS[selectedHostIdx], PORTS[selectedHostIdx], () => {
         Debug.Log ("Callback from connect");
         var auth = new Auth(nameInput.text.Trim());
         Debug.Log ("Calling auth");
         ConnectionProxy.Connection.SendMessage(auth, (jdata) => {
             ContentManager.Instance.ReadPlayerInfo(jdata);
             // We use a boolean to mark the transition instead of transitioning directly
             // since the connection is not necessarily working on the main thread.
             m_shouldTransition = true;
         });
     });
 }
コード例 #14
0
 //检测当前用户是否有当前页面权限
 private bool CheckPageAuth(Auth.AuthContext ctx)
 {
     try
     {
         NHExt.Runtime.Proxy.AgentInvoker invoker = new NHExt.Runtime.Proxy.AgentInvoker();
         invoker.AssemblyName = "IWEHAVE.ERP.AuthBP.Agent.GetPageAuthByGUIDBPProxy";
         invoker.DllName = "IWEHAVE.ERP.AuthBP.Agent.dll";
         invoker.AppendField(new NHExt.Runtime.Proxy.PropertyField() { FieldName = "PageGUID", FieldValue = this.PageGuid });
         invoker.SourcePage = this.PageGuid;
         return invoker.Do<bool>();
     }
     catch (Exception ex)
     {
         NHExt.Runtime.Logger.LoggerHelper.Error(ex, NHExt.Runtime.Logger.LoggerInstance.BizLogger);
     }
     return false;
 }
コード例 #15
0
ファイル: AuthProvider.cs プロジェクト: jmaucher/SStack
        /// <summary>
        /// Remove the Users Session
        /// </summary>
        /// <param name="service"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual object Logout(IServiceBase service, Auth request)
        {
            var session = service.GetSession();
            var referrerUrl = (request != null ? request.Continue : null)
                ?? session.ReferrerUrl
                ?? service.RequestContext.GetHeader("Referer")
                ?? this.CallbackUrl;

            session.OnLogout(service);

            service.RemoveSession();

            if (service.RequestContext.ResponseContentType == ContentType.Html && !String.IsNullOrEmpty(referrerUrl))
                return service.Redirect(referrerUrl.AddHashParam("s", "-1"));

            return new AuthResponse();
        }
コード例 #16
0
ファイル: SyncClient.cs プロジェクト: T4NK/SunDofus
        public void SendTicket(string key, Auth.AuthClient client)
        {
            var Builder = new StringBuilder();
            {
                Builder.Append("ANTS|");
                Builder.Append(key).Append("|");
                Builder.Append(client.Account.ID).Append("|");
                Builder.Append(client.Account.Pseudo).Append("|");
                Builder.Append(client.Account.Question).Append("|");
                Builder.Append(client.Account.Answer).Append("|");
                Builder.Append(client.Account.Level).Append("|");
                Builder.Append(string.Join(",", client.Account.Characters[Server.ID].ToArray())).Append("|");
                Builder.Append(client.Account.SubscriptionTime()).Append("|");
                Builder.Append(string.Join("+", Entities.Requests.GiftsRequests.GetGiftsByAccountID(client.Account.ID)));
            }

            Send(Builder.ToString());
        }
コード例 #17
0
ファイル: AuthModel.cs プロジェクト: jakelauer/Vanilla
		public async Task PopulateModel(HttpRequestBase request, HttpResponseBase response)
		{
			this.Request = request;
			this.Response = response;

			this.PopulateAuthTokens(Request);

			if (this.IsAuthenticated())
			{
				var tumbleApi = new TumblrApi(Request);
				CurrentUser = await tumbleApi.GetUserInfo();
			}
			else
			{
				var auth = new Auth();
				var authUrl = await auth.GetAuthRequestUrl(Request, Response);
				this.AuthUrl = authUrl.ToString();
			}
		}
コード例 #18
0
ファイル: DoneService.cs プロジェクト: vivlong/EventListWS
 public void initial(Auth auth, Update_Done request, Update_Done_Logic eventdoneLogic, CommonResponse ecr, string[] token, string uri)
 {
     if (auth.AuthResult(token, uri))
     {
         if (eventdoneLogic.UpdateDone(request) > 0)
         {
             eventdoneLogic.InsertContainerNo(request);
             ecr.meta.code = 200;
             ecr.meta.message = "OK";
         }
         else
         {
             ecr.meta.code = 612;
             ecr.meta.message = "The specified resource does not exist";
         }
     }
     else
     {
         ecr.meta.code = 401;
         ecr.meta.message = "Unauthorized";
     }
 }
コード例 #19
0
 protected void submit_Click(object sender, EventArgs e)
 {
     Auth auth = new Auth();
     SQLDB db = new SQLDB();
     string netname = Netname.Text.ToUpper();
     string login = Login.Text.ToUpper();
     string password = Password.Text;
     string tab_num = auth.Authentication(netname, login, password);
     if (tab_num != null)
     {
         List<Role> roles = auth.getRoles(tab_num);
         Person pers = new Person(null, login, password, tab_num, auth.getRoles(tab_num));
         Session["User"] = pers;
         if (roles != null)
         {
             db.insertLogon(tab_num, DateTime.Now, Request.UserHostAddress, Request.UserAgent);
             Response.Redirect("TimeTable.aspx?role=" + roles[0].RoleID);
         }
         else MessageBox.Show("Вам не присвоена роль!");
     }
     else MessageBox.Show("Неправильный логин или пароль!");
 }
コード例 #20
0
ファイル: ListService.cs プロジェクト: vivlong/EventListWS
 public void ListJmjm6(Auth auth, List_Jmjm6 request, List_Jmjm6_Logic list_Jmjm6_Logic, CommonResponse ecr, string[] token, string uri)
 {
     if (auth.AuthResult(token, uri))
     {
         ecr.data.results = list_Jmjm6_Logic.GetList(request);
         if (ecr.data.results != null)
         {
             ecr.meta.code = 200;
             ecr.meta.message = "OK";
         }
         else
         {
             ecr.meta.code = 612;
             ecr.meta.message = "The specified resource does not exist";
         }
     }
     else
     {
         ecr.meta.code = 401;
         ecr.meta.message = "Unauthorized";
     }
 }
コード例 #21
0
 protected void Page_Init(object sender, EventArgs e)
 {
     // авторизация Windows
     Auth auth = new Auth();
     SQLDB db = new SQLDB();
     string netname = "";
     string user = User.Identity.Name.ToUpper();
     if (user.Contains("\\"))
         netname = user.Substring(user.IndexOf('\\') + 1, user.Length - user.IndexOf('\\') - 1);
     string tab_num = auth.Authentication(netname, "", "");
     //string tab_num = auth.Authentication(user, "", "");
     if (tab_num != null)
     {
         List<Role> roles = auth.getRoles(tab_num);
         Person pers = new Person(user, null, null, tab_num, roles);
         Session["User"] = pers;
         if (roles != null)
         {
             db.insertLogon(tab_num, DateTime.Now, Request.UserHostAddress, Request.UserAgent);
             Response.Redirect("TimeTable.aspx?role=" + roles[0].RoleID);
         }
         else MessageBox.Show("Вам не присвоена роль! ");
     }
 }
コード例 #22
0
        private async Task Bootstrap()
        {
            await this.CheckForUpdates(true, false, false);

            #region UI
            Updater.MainWindow = this;
            this.Header.Text   = "LEAGUESHARP " + Assembly.GetExecutingAssembly().GetName().Version;

            this.Browser.Visibility             = Visibility.Hidden;
            this.TosBrowser.Visibility          = Visibility.Hidden;
            this.GeneralSettingsItem.IsSelected = true;

            #region ColumnWidth

            PropertyDescriptor pd = DependencyPropertyDescriptor.FromProperty(
                DataGridColumn.ActualWidthProperty,
                typeof(DataGridColumn));

            foreach (var column in this.InstalledAssembliesDataGrid.Columns)
            {
                pd.AddValueChanged(column, this.ColumnWidthPropertyChanged);
            }

            this.ColumnCheck.Width    = Config.Instance.ColumnCheckWidth;
            this.ColumnName.Width     = Config.Instance.ColumnNameWidth;
            this.ColumnType.Width     = Config.Instance.ColumnTypeWidth;
            this.ColumnVersion.Width  = Config.Instance.ColumnVersionWidth;
            this.ColumnLocation.Width = Config.Instance.ColumnLocationWidth;

            #endregion

            this.NewsTabItem.Visibility       = Visibility.Hidden;
            this.AssembliesTabItem.Visibility = Visibility.Hidden;
            this.SettingsTabItem.Visibility   = Visibility.Hidden;
            this.AssemblyDB.Visibility        = Visibility.Hidden;
            this.DataContext = this;

            #region ContextMenu.DevMenu

            this.DevMenu.Visibility      = Config.Instance.ShowDevOptions ? Visibility.Visible : Visibility.Collapsed;
            this.Config.PropertyChanged += (o, args) =>
            {
                if (args.PropertyName == "ShowDevOptions")
                {
                    this.DevMenu.Visibility = Config.Instance.ShowDevOptions
                                                      ? Visibility.Visible
                                                      : Visibility.Collapsed;
                }
            };

            #endregion

            Updater.MainWindow = this;

            #endregion

            #region login

            //Try to login with the saved credentials.
            if (!Auth.Login(Config.Instance.Username, Config.Instance.Password).Item1)
            {
                await this.ShowLoginDialog();
            }
            else
            {
                this.OnLogin(Config.Instance.Username);
            }

            if (Config.Instance.FirstRun)
            {
                Config.SaveAndRestart();
            }

            #endregion

            #region update

            await this.CheckForUpdates(false, true, false);

            await Updater.UpdateBlockedRepos();

            await Updater.UpdateRepositories();

            await Updater.UpdateWebService();

            Utility.Log(LogStatus.Info, "Bootstrap", "Update Complete", Logs.MainLog);

            #endregion

            #region ToS

            if (!Config.Instance.TosAccepted)
            {
                this.RightWindowCommands.Visibility = Visibility.Collapsed;
                this.TosButton_OnClick(null, null);
            }
            else
            {
                this.AssemblyButton_OnClick(null, null);
            }

            // wait for tos accept
            await Task.Factory.StartNew(
                () =>
            {
                while (Config.Instance.TosAccepted == false)
                {
                    Thread.Sleep(100);
                }
            });

            #endregion

            #region assembly compile

            var allAssemblies = new List <LeagueSharpAssembly>();

            foreach (var profile in Config.Instance.Profiles)
            {
                allAssemblies.AddRange(profile.InstalledAssemblies);
            }

            allAssemblies = allAssemblies.Distinct().ToList();

            GitUpdater.ClearUnusedRepos(allAssemblies);
            await this.PrepareAssemblies(allAssemblies, Config.Instance.FirstRun || Config.Instance.UpdateOnLoad, true);

            Utility.Log(LogStatus.Info, "Bootstrap", "Compile Complete", Logs.MainLog);

            #endregion

            // injection, randomizer, remoting
            this.InitSystem();
            Utility.Log(LogStatus.Info, "Bootstrap", "System Initialisation Complete", Logs.MainLog);

            this.MainTabControl.SelectedIndex = 2;
        }
コード例 #23
0
        /// <summary>
        /// Get info for ALL  of the user's sections
        /// This include the user's sections as well as sections shared with this user by others.
        /// </summary>
        /// <param name="debug">Run the code under the debugger</param>
        /// <param name="provider"></param>
        /// <param name="apiRoute"></param>
        /// <returns>The converted HTTP response message</returns>
        public static async Task <List <ApiBaseResponse> > GetAllSections(bool debug, AuthProvider provider, string apiRoute)
        {
            if (debug)
            {
                Debugger.Launch();
                Debugger.Break();
            }

            var client = new HttpClient();

            // Note: API only supports JSON response.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Not adding the Authentication header would produce an unauthorized call and the API will return a 401
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
                                                                                       await Auth.GetAuthToken(provider));

            // Prepare an HTTP GET request to the Sections endpoint
            var createMessage = new HttpRequestMessage(HttpMethod.Get, apiRoute + "sections");

            HttpResponseMessage response = await client.SendAsync(createMessage);

            return(await TranslateListOfSectionsResponse(response));
        }
コード例 #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/common/authorize/css/authorize.less"));

            Login    = "";
            Password = "";
            HashId   = "";

            //Account link control
            AccountLinkControl accountLink = null;

            if (SetupInfo.ThirdPartyAuthEnabled && AccountLinkControl.IsNotEmpty)
            {
                accountLink                = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                accountLink.Visible        = true;
                accountLink.ClientCallback = "authCallback";
                accountLink.SettingsView   = false;
                signInPlaceholder.Controls.Add(accountLink);
            }

            //top panel
            var master = Page.Master as BaseTemplate;

            if (master != null)
            {
                master.TopStudioPanel.DisableProductNavigation = true;
                master.TopStudioPanel.DisableSearch            = true;
                master.TopStudioPanel.DisableVideo             = true;
            }

            Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization);

            pwdReminderHolder.Controls.Add(LoadControl(PwdTool.Location));

            var msg = Request["m"];

            if (!string.IsNullOrEmpty(msg))
            {
                ErrorMessage = msg;
            }

            if (IsPostBack && !SecurityContext.IsAuthenticated)
            {
                var tryByHash   = false;
                var smsLoginUrl = string.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && accountLink != null)
                    {
                        HashId = Request["__EVENTARGUMENT"];
                    }

                    if (!string.IsNullOrEmpty(Request["login"]))
                    {
                        Login = Request["login"].Trim();
                    }
                    else if (string.IsNullOrEmpty(HashId))
                    {
                        throw new InvalidCredentialException("login");
                    }

                    if (!string.IsNullOrEmpty(Request["pwd"]))
                    {
                        Password = Request["pwd"];
                    }
                    else if (string.IsNullOrEmpty(HashId))
                    {
                        throw new InvalidCredentialException("password");
                    }


                    var counter = (int)(cache.Get("loginsec/" + Login) ?? 0);
                    if (++counter % 5 == 0)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                    cache.Insert("loginsec/" + Login, counter, DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

                    smsLoginUrl = SmsLoginUrl(accountLink);
                    if (string.IsNullOrEmpty(smsLoginUrl))
                    {
                        if (string.IsNullOrEmpty(HashId))
                        {
                            var cookiesKey = SecurityContext.AuthenticateMe(Login, Password);
                            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                        }
                        else
                        {
                            Guid userId;
                            tryByHash = TryByHashId(accountLink, HashId, out userId);
                            var cookiesKey = SecurityContext.AuthenticateMe(userId);
                            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                        }
                    }
                }
                catch (InvalidCredentialException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = tryByHash ? Resource.LoginWithAccountNotFound : Resource.InvalidUsernameOrPassword;
                    return;
                }
                catch (System.Security.SecurityException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = Resource.ErrorDisabledProfile;
                    return;
                }
                catch (Exception ex)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = ex.Message;
                    return;
                }

                if (!string.IsNullOrEmpty(smsLoginUrl))
                {
                    Response.Redirect(smsLoginUrl);
                }

                var refererURL = (string)Session["refererURL"];
                if (string.IsNullOrEmpty(refererURL))
                {
                    Response.Redirect("~/");
                }
                else
                {
                    Session["refererURL"] = null;
                    Response.Redirect(refererURL);
                }
            }

            ProcessConfirmedEmailCondition();
        }
コード例 #25
0
ファイル: AuthProvider.cs プロジェクト: jmaucher/SStack
 public abstract bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null);
コード例 #26
0
        /// <summary>
        /// Authenticate the user request.
        /// </summary>
        /// <returns>Returns the error object if there's an issue, otherwise returns null</returns>
        /// <remarks>
        /// If the operation is not authorized, this function adds the appropriate headers to the response to request credentials from the client.
        /// </remarks>
        public override errordetail Authenticate()
        {
            errordetail         currentException = null;
            WebHeaderCollection headers          = Context.Headers;
            string authStr = headers["Authorization"];

            if (string.IsNullOrEmpty(authStr))
            {
                //
                // No credentials.  Typical for a first-request.  Send back a 401 so the client can respond with credentials.
                //
                Set401AuthenticationHeaders(Context, false);
                return(ResponseNoCredentialsFoundInRequest);
            }

            authStr = authStr.Substring(7);

            ListDictionary reqInfo = new ListDictionary();

            string[] elems = authStr.Split(new char[] { ',' });
            foreach (string elem in elems)
            {
                // form key="value"
                string[] parts = elem.Split(new char[] { '=' }, 2);
                if (parts.Length > 1)
                {
                    string key = parts[0].Trim(new char[] { ' ', '\"' });
                    string val = parts[1].Trim(new char[] { ' ', '\"' });
                    reqInfo.Add(key, val);
                }
            }

            string username = (string)reqInfo["username"];

            string password = "";

            //
            // Get the password based upon the username.
            //
            bool bOk = username != null && Auth.GetPassword(username, out password);

            if (!bOk)
            {
                //
                // Username not found.
                //
                return(ResponseCredentialsReceivedButUnknownUser);
            }

            //get the realm from the config file
            string realm = Realm;

            // calculate the Digest hashes

            // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
            string A1 = String.Format("{0}:{1}:{2}", (string)reqInfo["username"], realm, password);

            // H(A1) = MD5(A1)
            string HA1 = GetMD5HashBinHex(A1);

            // A2 = Method ":" digest-uri-value
            string A2 = String.Format("{0}:{1}", Context.Method, (string)reqInfo["uri"]);   // JB:  app.Request.HttpMethod

            // H(A2)
            string HA2 = GetMD5HashBinHex(A2);

            string unhashedDigest;

            if (reqInfo["qop"] != null)
            {
                unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
                                               HA1,
                                               (string)reqInfo["nonce"],
                                               (string)reqInfo["nc"],
                                               (string)reqInfo["cnonce"],
                                               (string)reqInfo["qop"],
                                               HA2);
            }
            else
            {
                unhashedDigest = String.Format("{0}:{1}:{2}",
                                               HA1,
                                               (string)reqInfo["nonce"],
                                               HA2);
            }

            string hashedDigest = GetMD5HashBinHex(unhashedDigest);

            bool isNonceStale = !IsValidNonce((string)reqInfo["nonce"]);

            //
            // If the result of their hash is equal to the result of our hash, then this
            // is a valid request from a partner
            //
            if (isNonceStale)
            {
                Set401AuthenticationHeaders(Context, true);
                return(ResponseDigestStaleNonce);
            }
            else if ((string)reqInfo["response"] != hashedDigest)
            {
                Set401AuthenticationHeaders(Context, false);
                return(ResponseCredentialsReceivedButBadPassword);
            }
            else
            {
                //
                // We're golden!
                //
                Username = username;
            }

            return(currentException);
        }
コード例 #27
0
        public void registerUser(string username, string email, string pwd, string accType)
        {
            byte[] IV = null;
            Tuple <string, string> pwdAndSalt = Auth.hash(pwd);
            RijndaelManaged        cipher     = new RijndaelManaged();

            cipher.GenerateIV();
            IV = cipher.IV;

            StripeConfiguration.ApiKey = "sk_test_51Hnjg6K2AIXSM7wrvlwz0S8eQSrtxjb7irpnIhvWGSKSsbWJzUymiC3tHbwxYQCumbmK5gC06kRIw7wr1eHEpj6D00CDgHmOpO";
            Customer              cust    = new Customer();
            CustomerService       serv    = new CustomerService();
            CustomerCreateOptions options = new CustomerCreateOptions
            {
                Description = username,
                Balance     = 5000
            };

            cust = serv.Create(options);

            User user = new User(username, email, pwdAndSalt.Item1, pwdAndSalt.Item2, "", accType, Convert.ToBase64String(IV), Auth.encrypt(cust.Id, IV));

            user.AddUser();
            Session["success"] = "Registered successfully";
            Response.Redirect("~/Views/auth/login.aspx");
        }
コード例 #28
0
        public static UserInfo GetUserByThirdParty(LoginProfile loginProfile)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (loginProfile.AuthorizationError != "Canceled at provider")
                    {
                        throw new Exception(loginProfile.AuthorizationError);
                    }
                    return(ASC.Core.Users.Constants.LostUser);
                }

                if (string.IsNullOrEmpty(loginProfile.EMail))
                {
                    throw new Exception(Resource.ErrorNotCorrectEmail);
                }

                var userInfo = new UserInfo();

                Guid userId;
                if (TryGetUserByHash(loginProfile.HashId, out userId))
                {
                    userInfo = CoreContext.UserManager.GetUsers(userId);
                }
                if (!CoreContext.UserManager.UserExists(userInfo.ID))
                {
                    userInfo = CoreContext.UserManager.GetUserByEmail(loginProfile.EMail);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            CoreContext.UserManager.DeleteUser(userInfo.ID);
                            userInfo = ASC.Core.Users.Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    var spam = HttpContext.Current.Request["spam"];
                    if (spam != "on")
                    {
                        try
                        {
                            const string _databaseID = "com";
                            using (var db = DbManager.FromHttpContext(_databaseID))
                            {
                                db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                                   .InColumnValue("email", userInfo.Email.ToLowerInvariant())
                                                   .InColumnValue("reason", "personal")
                                                   );
                                LogManager.GetLogger("ASC.Web").Debug(String.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetLogger("ASC.Web").Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
                        }
                    }
                    StudioNotifyService.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                Auth.ProcessLogout();
                throw;
            }
        }
コード例 #29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Models.DailyGospel dailyGospel;
                var dailyGospelService = new DailyGospelService();

                if (Page.RouteData.Values["gospel-id"] != null)
                {
                    int id;
                    if (int.TryParse(Page.RouteData.Values["gospel-id"].ToString(), out id))
                    {
                        dailyGospel = dailyGospelService.Find(id);
                    }
                    else if (Page.RouteData.Values["gospel-id"].ToString().Length > 1)
                    {
                        dailyGospel =
                            dailyGospelService.FindByDate(Convert.ToDateTime(Page.RouteData.Values["gospel-id"]));
                    }
                    else
                    {
                        dailyGospel = dailyGospelService.FindByDate(DateTime.UtcNow);
                    }
                }

                else
                {
                    var date = Request["date"] != null?Convert.ToDateTime(Request["date"]) : DateTime.UtcNow;

                    dailyGospel = GetReading(date);
                }

                GospelID.Value          = dailyGospel.Id.ToString();
                SourceContent.InnerHtml = dailyGospel.Source;
                GospelDate.InnerHtml    = dailyGospel.DateOfGospel.DayOfWeek + ", " +
                                          dailyGospel.DateOfGospel.ToString("MMMM dd, yyyy");
                FRTitle.InnerHtml        = dailyGospel.FirstReadingTitle;
                FRContent.InnerHtml      = dailyGospel.FirstReadingContent;
                RPTitle.InnerHtml        = dailyGospel.ResponsorialPsalmTitle;
                RPContent.InnerHtml      = dailyGospel.ResponsorialPsalmContent;
                SRTitle.InnerHtml        = dailyGospel.SecondReadingTitle;
                SRContent.InnerHtml      = dailyGospel.SecondReadingContent;
                VBGTitle.InnerHtml       = dailyGospel.VerseBeforeGospelTitle;
                VBGContent.InnerHtml     = dailyGospel.VerseBeforeGospelContent;
                DGospelTitle.InnerHtml   = dailyGospel.GospelTitle;
                DGospelContent.InnerHtml = dailyGospel.GospelContent;

                SecondReading.Attributes.Add("style",
                                             dailyGospel.SecondReadingTitle == "" ? "display:none" : "display:block");

                SecondReading.Attributes.Add("style",
                                             dailyGospel.SecondReadingContent == "" ? "display:none" : "display:block");

                VerseBeforeGospel.Attributes.Add("style",
                                                 dailyGospel.VerseBeforeGospelTitle == "" ? "display:none" : "display:block");

                VerseBeforeGospel.Attributes.Add("style",
                                                 dailyGospel.VerseBeforeGospelContent == "" ? "display:none" : "display:block");



                DateTime dateParam;

                dateParam = Request["date"] != null?Convert.ToDateTime(Request["date"]) : DateTime.UtcNow;

                var verse = GetVerse(dateParam);
                var quote = GetQuote(dateParam);

                //TextBox1.Text = DateTime.Now.ToString().Split(' ')[0] + " " + DateTime.Now.ToString().Split(' ')[1];
                HttpUtility.HtmlEncode(BibleQuote.InnerHtml = verse.BibleVerseContent);
                HttpUtility.HtmlEncode(BibleVerse.InnerHtml = verse.ChapterTitle);

                RelQuote.InnerHtml = quote.Quote;
                Author.InnerHtml   = quote.Author;


                var service = new DailyGospelReflectionService();

                if (!service.UserHasReflection(Auth.user().Id, dailyGospel.Id))
                {
                    return;
                }

                var reflection = service.GetUserReflection(Auth.user().Id, dailyGospel.Id);
                GReflectTitle.Value   = reflection.Title;
                GReflectContent.Value = reflection.ReflectionContent;
            }
        }
コード例 #30
0
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            Browser.Visibility             = Visibility.Hidden;
            TosBrowser.Visibility          = Visibility.Hidden;
            DataContext                    = this;
            GeneralSettingsItem.IsSelected = true;

            #region ContextMenu.DevMenu

            DevMenu.Visibility      = Config.Instance.ShowDevOptions ? Visibility.Visible : Visibility.Collapsed;
            Config.PropertyChanged += (o, args) =>
            {
                if (args.PropertyName == "ShowDevOptions")
                {
                    DevMenu.Visibility = Config.Instance.ShowDevOptions ? Visibility.Visible : Visibility.Collapsed;
                }
            };

            #endregion

            #region ToS

            if (!Config.Instance.TosAccepted)
            {
                RightWindowCommands.Visibility = Visibility.Collapsed;
            }
            else
            {
                MainTabControl.SelectedIndex = 1;
            }

            #endregion

            if (!File.Exists(Directories.CoreFilePath))
            {
                MessageBox.Show(string.Format("Couldn't find {0}", Path.GetFileName(Directories.CoreFilePath)));
                Environment.Exit(0);
            }

            Updater.MainWindow = this;
            CheckForUpdates(true, true, false);

            Updater.GetRepositories(
                delegate(List <string> list)
            {
                if (list.Count > 0)
                {
                    Config.Instance.KnownRepositories.Clear();
                    foreach (var repo in list)
                    {
                        Config.Instance.KnownRepositories.Add(repo);
                    }
                }
            });

            //Try to login with the saved credentials.
            if (!Auth.Login(Config.Instance.Username, Config.Instance.Password).Item1)
            {
                ShowLoginDialog();
            }
            else
            {
                OnLogin(Config.Instance.Username);
            }

            Config.Instance.FirstRun = false;


            foreach (var gameSetting in Config.Instance.Settings.GameSettings)
            {
                gameSetting.PropertyChanged += GameSettingOnPropertyChanged;
            }
            NewsTabItem.Visibility       = Visibility.Hidden;
            AssembliesTabItem.Visibility = Visibility.Hidden;
            SettingsTabItem.Visibility   = Visibility.Hidden;
        }
コード例 #31
0
        public void CreateUptokenTest()
        {
            var mac = new Mac(AccessKey, SecretKey);
            // 简单上传凭证
            var putPolicy = new PutPolicy
            {
                Scope = Bucket
            };
            var upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            Console.WriteLine(upToken);

            // 自定义凭证有效期(示例2小时)
            putPolicy = new PutPolicy
            {
                Scope = Bucket
            };
            putPolicy.SetExpires(7200);
            upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Console.WriteLine(upToken);

            // 覆盖上传凭证
            putPolicy = new PutPolicy
            {
                Scope = $"{Bucket}:qiniu.png"
            };
            upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Console.WriteLine(upToken);

            // 自定义上传回复(非callback模式)凭证
            putPolicy = new PutPolicy
            {
                Scope      = Bucket,
                ReturnBody = "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fsiz\":$(fsize),\"bucket\":\"$(bucket)\",\"name\":\"$(x:name)\"}"
            };
            upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Console.WriteLine(upToken);

            // 带回调业务服务器的凭证(application/json)
            putPolicy = new PutPolicy
            {
                Scope            = Bucket,
                CallbackUrl      = "http://api.example.com/qiniu/upload/callback",
                CallbackBody     = "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fsiz\":$(fsize),\"bucket\":\"$(bucket)\",\"name\":\"$(x:name)\"}",
                CallbackBodyType = "application/json"
            };
            upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Console.WriteLine(upToken);

            // 带回调业务服务器的凭证(application/x-www-form-urlencoded)
            putPolicy = new PutPolicy
            {
                Scope        = Bucket,
                CallbackUrl  = "http://api.example.com/qiniu/upload/callback",
                CallbackBody = "key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)"
            };
            upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Console.WriteLine(upToken);

            // 带数据处理的凭证
            putPolicy = new PutPolicy();
            var saveMp4Entry  = Base64.UrlSafeBase64Encode(Bucket + ":avthumb_test_target.mp4");
            var saveJpgEntry  = Base64.UrlSafeBase64Encode(Bucket + ":vframe_test_target.jpg");
            var avthumbMp4Fop = "avthumb/mp4|saveas/" + saveMp4Entry;
            var vframeJpgFop  = "vframe/jpg/offset/1|saveas/" + saveJpgEntry;
            var fops          = string.Join(";", avthumbMp4Fop, vframeJpgFop);

            putPolicy.Scope               = Bucket;
            putPolicy.PersistentOps       = fops;
            putPolicy.PersistentPipeline  = "video-pipe";
            putPolicy.PersistentNotifyUrl = "http://api.example.com/qiniu/pfop/notify";
            upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Console.WriteLine(upToken);
        }
コード例 #32
0
        public RequiredDocumentationResponse GetRequiredDocumentsList()
        {
            int assessmentId = Auth.AssessmentForUser();

            return((new RequiredDocumentationManager()).GetRequiredDocuments(assessmentId));
        }
コード例 #33
0
        public static List <Models.MusicalInspiration> GetMusic(string moods)
        {
            var service = new MusicalInspirationService();

            return(service.GetAll(moods, Auth.user().Id));
        }
コード例 #34
0
        protected void Page_Load(object sender, EventArgs e)
        {
            InitDefaultPage();
            if (listNoRedirect.Contains(Path.GetFileNameWithoutExtension(Request.FilePath).ToLower()))
            {
                SetTopMenuVisible(false);
                return;
            }

            var ocToken = Request.QueryString[QSToken];

            if (Session == null)
            {
                // No existing session, check if request from OC or ASP
                if (!string.IsNullOrWhiteSpace(ocToken))
                {
                    // OC request, create or 404.
                    var userInfo = Auth.GetOCRecord(ocToken);
                    if (userInfo.IsValid)
                    {
                        SessionHandler.BeginSession(userInfo.UserName, Request, userInfo);
                        InitOCPage(Session[SKeys.User] as User, userInfo);
                    }
                    else
                    {
                        ProgramLog.LogError(null, "SiteMaster", "Page_Load", "Unable to authenticate user.");
                        Response.Redirect(Path404);
                    }
                }
                else
                {
                    // ASP request, redirect to login
                    RedirectToLogin("A");
                }
            }
            else
            {
                if (!IsExistingSessionValid())
                {
                    if (!string.IsNullOrWhiteSpace(ocToken))
                    {
                        // OC request, create or 404.
                        var userInfo = Auth.GetOCRecord(ocToken);
                        if (userInfo.IsValid)
                        {
                            SessionHandler.BeginSession(userInfo.UserName, Request, userInfo);
                            InitOCPage(Session[SKeys.User] as User, userInfo);
                        }
                        else
                        {
                            Response.Redirect(Path404);
                        }
                    }
                    else
                    {
                        RedirectToLogin("S");
                    }
                }
                else
                {
                    var user        = Session[SKeys.User] as User;
                    var isOCSession = Session[SKeys.IsOCSession] as bool?;
                    if (isOCSession == true)
                    {
                        if (!string.IsNullOrWhiteSpace(ocToken))
                        {
                            // OC session + OC request -> maintain existing session
                            var userInfo = Auth.GetOCRecord(ocToken);
                            if (userInfo.IsValid)
                            {
                                // Check the userinfo against the existing session info. If match, then good.
                                if (user.UserName == userInfo.UserName)
                                {
                                    InitOCPage(user, userInfo);
                                }
                                else
                                {
                                    // Remove OC session, redirect to 404.
                                    Session.Abandon();
                                    Response.Redirect(Path404);
                                }
                            }
                            else
                            {
                                // Invalid info, Remove OC session, redirect to 404.
                                Session.Abandon();
                                Response.Redirect(Path404);
                            }
                        }
                        else
                        {
                            // OC Session + ASP request -> Remove OC session, redirect to login.
                            Session.Abandon();
                            RedirectToLogin("OA");
                        }
                    }
                    else
                    {
                        // ASP session, token doesn't matter, setup page as usual.
                        RedirectAppIfNotAllowed(user, PathDefault);
                        SetupUserPage(user);
                    }
                }
            }
        }
コード例 #35
0
        /// <summary>
        /// Starts the bot.
        /// </summary>
        private async Task Start()
        {
            // Create Discord client.
            client = new NinjaCatDiscordClient();

            // Create command service and map.
            var commands   = new CommandService();
            var commandMap = new ServiceCollection();

            // Load commands from assembly.
            await commands.AddModulesAsync(Assembly.GetEntryAssembly());

            // Certain things are to be done when the bot joins a guild.
            client.JoinedGuild += async(guild) =>
            {
                // Pause for 5 seconds.
                await Task.Delay(TimeSpan.FromSeconds(5));

                // Check to see if this is a bot farm.
                if (await CheckBotGuild(guild))
                {
                    return;
                }

                // Create variable for speaking channel mention.
                var speakingChannel = string.Empty;

                // Get speaking channel.
                var channel = client.GetSpeakingChannelForSocketGuild(guild);

                // Update server count.
                await UpdateSiteServerCountAsync();

                // Does the bot have permission to message? If not return.
                if (!channel.Guild.CurrentUser.GetPermissions(channel).SendMessages)
                {
                    return;
                }

                // Get the mention if speaking is enabled.
                if (channel != null)
                {
                    speakingChannel = channel.Mention;
                }

                // Bot is typing in default channel.
                await channel.TriggerTypingAsync();

                // Pause for realism.
                await Task.Delay(TimeSpan.FromSeconds(1));

                // Dev began Oct 2. 2016.
                // Is a speaking channel set?
                if (!string.IsNullOrEmpty(speakingChannel))
                {
                    // Select and send message.
                    switch (client.GetRandomNumber(2))
                    {
                    default:
                        await channel.SendMessageAsync($"{Constants.AboutMessage1}\n\n" +
                                                       $"By default, I'll speak in {speakingChannel}, but you can change it with the **{Constants.CommandPrefix}{Constants.SetChannelCommand}** command.");

                        break;

                    case 1:
                        await channel.SendMessageAsync($"{Constants.AboutMessage2}\n\n" +
                                                       $"I'll speak in {speakingChannel} by default, but it can be changed with the **{Constants.CommandPrefix}{Constants.SetChannelCommand}** command.");

                        break;
                    }
                }
                else
                {
                    // Select and send message.
                    switch (client.GetRandomNumber(2))
                    {
                    default:
                        await channel.SendMessageAsync(Constants.AboutMessage1);

                        break;

                    case 1:
                        await channel.SendMessageAsync(Constants.AboutMessage2);

                        break;
                    }
                }
            };

            // Update count on guild leave.
            client.LeftGuild += async(guild) => await UpdateSiteServerCountAsync();

            // Listen for messages.
            client.MessageReceived += async(message) =>
            {
                // Get the message and check to see if it is a user message.
                var msg = message as IUserMessage;
                if (msg == null)
                {
                    return;
                }

                // Keeps track of where the command begins.
                var pos = 0;

                // Attempt to parse a command.
                if (msg.HasStringPrefixLower(Constants.CommandPrefix, ref pos))
                {
                    var result = await commands.ExecuteAsync(new CommandContext(client, msg), msg.Content.Substring(pos));

                    if (!result.IsSuccess)
                    {
                        // Is the command just unknown? If so, return.
                        if (result.Error == CommandError.UnknownCommand)
                        {
                            return;
                        }

                        // Bot is typing.
                        await msg.Channel.TriggerTypingAsync();

                        // Pause for realism and send message.
                        await Task.Delay(TimeSpan.FromSeconds(0.75));

                        await msg.Channel.SendMessageAsync($"I'm sorry, but something happened. Error: {result.ErrorReason}");
                    }
                    return;
                }
            };

            // Log in to Discord. Token is stored in the Credentials class.
            await client.LoginAsync(TokenType.Bot, Credentials.DiscordToken);

            await client.StartAsync();

            // Check for bot guilds.
            foreach (var shard in client.Shards)
            {
#pragma warning disable 4014
                shard.Connected += async() =>
                {
                    foreach (var guild in shard.Guilds)
                    {
                        CheckBotGuild(guild);
                    }
                    await Task.CompletedTask;
                };
#pragma warning restore 4014
            }

            // Log in to Twitter.
            Auth.SetUserCredentials(Credentials.TwitterConsumerKey, Credentials.TwitterConsumerSecret,
                                    Credentials.TwitterAccessToken, Credentials.TwitterAccessSecret);

            // Create Twitter stream to follow @donasarkar.
            var donaUser = User.GetUserFromScreenName("windowsinsider");
            var stream   = Tweetinvi.Stream.CreateFilteredStream();
            stream.AddFollow(donaUser);

#if DEBUG
            // Used for testing tweets.
            var goldfishUser = User.GetUserFromScreenName("goldfishx64");
            stream.AddFollow(goldfishUser);
#endif

            // Listen for incoming tweets from Dona.
            stream.MatchingTweetReceived += async(s, e) =>
            {
                // Get tweet.
                var tweet = e.Tweet.RetweetedTweet ?? e.Tweet;

                // If the tweet is a reply or if it doesn't belong to a known user, ignore it.
                if (tweet.CreatedBy.Id != donaUser.Id || !string.IsNullOrEmpty(tweet.InReplyToScreenName))
                {
                    return;
                }

                // Log tweet.
                client.LogOutput($"TWEET: {tweet.FullText}");

                // Is it a no-build tweet from Dona?
                if ((tweet.FullText.ToLowerInvariant().Contains("no build") || tweet.FullText.ToLowerInvariant().Contains("no new build") ||
                     tweet.FullText.ToLowerInvariant().Contains("not releasing") || tweet.FullText.ToLowerInvariant().Contains("not flighting")) && tweet.Urls.Count == 0)
                {
                    // Log tweet.
                    client.LogOutput($"TWEET CONFIRMED: NO BUILDS TODAY");

                    // Send message to guilds.
                    foreach (var shard in client.Shards)
                    {
                        SendNoBuildsToShard(shard);
                    }
                }
                else
                {
                    // Try to get a blogs URL.
                    var fullUrl = string.Empty;
                    foreach (var url in tweet.Urls)
                    {
                        for (int t = 0; t < 3; t++)
                        {
                            // Create the HttpClient.
                            using (var httpClient = new HttpClient())
                            {
                                // Retry up to three times.
                                for (int i = 0; i < 3; i++)
                                {
                                    // Get full URL.
                                    var tempUrl  = url.ExpandedURL;
                                    var response = await httpClient.GetAsync(tempUrl);

                                    // If the response was a redirect, try again up to 10 times.
                                    var count = 10;
                                    while ((response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Moved) ||
                                           count < 10)
                                    {
                                        tempUrl  = response.Headers.Location.ToString();
                                        response = await httpClient.GetAsync(tempUrl);

                                        count++;
                                    }

                                    // Check to see if the full URL was gotten.
                                    if (response.RequestMessage.RequestUri.ToString().Contains("blogs.windows.com/windowsexperience") && response.RequestMessage.RequestUri.ToString().Contains("insider-preview-build"))
                                    {
                                        fullUrl = response.RequestMessage.RequestUri.ToString();
                                        break;
                                    }
                                    else
                                    {
                                        client.LogOutput($"URLFETCH ERROR: URL wasn't right.");
                                    }

                                    // Did the request fail? Log the error and retry.
                                    if (!response.IsSuccessStatusCode)
                                    {
                                        client.LogOutput($"URLFETCH ERROR: {response.StatusCode}");
                                    }
                                }
                            }

                            // Check to see if URL has what it takes. If not, retry in 5 minutes.
                            if (!string.IsNullOrEmpty(fullUrl) && fullUrl.Contains("blogs.windows.com/windowsexperience") && fullUrl.Contains("insider-preview-build"))
                            {
                                break;
                            }

                            // Clear URL.
                            fullUrl = string.Empty;

                            // Wait 10 minutes.
                            await Task.Delay(TimeSpan.FromMinutes(10));
                        }

                        // Check to see if URL has what it takes. If not, retry in 5 minutes.
                        if (!string.IsNullOrEmpty(fullUrl) && fullUrl.Contains("blogs.windows.com/windowsexperience") && fullUrl.Contains("insider-preview-build"))
                        {
                            break;
                        }

                        // Clear URL.
                        fullUrl = string.Empty;
                    }

                    // If URL is invalid, return.
                    if (string.IsNullOrWhiteSpace(fullUrl))
                    {
                        return;
                    }

                    // Get build numbers. If empty, ignore the tweet.
                    var build  = Regex.Match(fullUrl, @"\d{5,}").Value;
                    var buildM = Regex.Match(fullUrl, @"\d{5,}", RegexOptions.RightToLeft).Value;
                    if (string.IsNullOrWhiteSpace(build))
                    {
                        return;
                    }

                    // Log tweet.
                    client.LogOutput($"TWEET CONFIRMED: NEW BUILD");

                    // Create variables.
                    var ring     = string.Empty;
                    var platform = string.Empty;

                    // Check for fast or slow, or both.
                    if (tweet.FullText.ToLowerInvariant().Contains("fast") && tweet.FullText.ToLowerInvariant().Contains("slow"))
                    {
                        ring = " to both the Fast and Slow rings";
                    }
                    else if (tweet.FullText.ToLowerInvariant().Contains("fast"))
                    {
                        ring = " to the Fast ring" + (fullUrl.ToLowerInvariant().Contains("skip-ahead") ? " (Skip Ahead)" : "");
                    }
                    else if (tweet.FullText.ToLowerInvariant().Contains("slow"))
                    {
                        ring = " to the Slow ring";
                    }

                    // Check for PC or mobile, or both.
                    if (fullUrl.ToLowerInvariant().Contains("pc") && fullUrl.ToLowerInvariant().Contains("mobile") && fullUrl.ToLowerInvariant().Contains("server"))
                    {
                        platform = " for PC, Server, and Mobile";
                    }
                    else if (fullUrl.ToLowerInvariant().Contains("pc") && fullUrl.ToLowerInvariant().Contains("mobile"))
                    {
                        platform = " for both PC and Mobile";
                    }
                    else if (fullUrl.ToLowerInvariant().Contains("pc") && fullUrl.ToLowerInvariant().Contains("server"))
                    {
                        platform = " for both PC and Server";
                    }
                    else if (fullUrl.ToLowerInvariant().Contains("mobile") && fullUrl.ToLowerInvariant().Contains("server"))
                    {
                        platform = " for both Server and Mobile";
                    }
                    else if (fullUrl.ToLowerInvariant().Contains("pc"))
                    {
                        platform = " for PC";
                    }
                    else if (fullUrl.ToLowerInvariant().Contains("mobile"))
                    {
                        platform = " for Mobile";
                    }
                    else if (fullUrl.ToLowerInvariant().Contains("server"))
                    {
                        platform = " for Server";
                    }

                    // Send build to guilds.
                    foreach (var shard in client.Shards)
                    {
                        SendNewBuildToShard(shard, build, buildM, ring + platform, fullUrl);
                    }
                }
            };

            // Listen for stop.
            stream.StreamStopped += (s, e) =>
            {
                // Log error.
                client.LogOutput($"TWEET STREAM STOPPED: {e.Exception}");
            };

            // Create timer for POSTing server count.
            var serverCountTimer = new Timer(async(e) => await UpdateSiteServerCountAsync(), null, TimeSpan.FromMinutes(1), TimeSpan.FromHours(1));

            // Create timer for game play status of builds.
            var buildPlayTimer = new Timer(async(e) => await client.UpdateGameAsync(), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(30));

            // Start the stream.
            stream.StartStreamMatchingAllConditions();
        }
コード例 #36
0
        private static async Task Main()
        {
            Console.Write("Enter App ID: ");

            var appId = Console.ReadLine();

            Console.Write("Enter App Secret: ");

            var appSecret = Console.ReadLine();

            Console.Write("Enter App Redirect URL: ");

            var redirectUrl = Console.ReadLine();

            _app = new App(appId, appSecret, redirectUrl);

            Console.Write("Enter Connection Mode (Live or Demo): ");

            var connectionMode = Console.ReadLine();

            var mode = (Mode)Enum.Parse(typeof(Mode), connectionMode, true);

            var auth = new Auth(_app, mode: mode);

            System.Diagnostics.Process.Start("explorer.exe", $"\"{auth.AuthUri}\"");

            ShowDashLine();

            Console.WriteLine("Follow the authentication steps on your browser, then copy the authentication code from redirect" +
                              " URL and paste it here.");

            Console.WriteLine("The authentication code is at the end of redirect URL and it starts after '?code=' parameter.");

            ShowDashLine();

            Console.Write("Enter Authentication Code: ");

            var code = Console.ReadLine();

            var authCode = new AuthCode(code, _app);

            _token = TokenFactory.GetToken(authCode);

            Console.WriteLine("Access token generated");

            ShowDashLine();

            _client = new Client();

            _streamDisposables.Add(_client.Streams.MessageStream.Subscribe(OnMessageReceived));
            _streamDisposables.Add(_client.Streams.ErrorStream.Subscribe(OnError));

            _streamDisposables.Add(_client.Streams.ListenerExceptionStream.Subscribe(OnListenerException));

            _streamDisposables.Add(_client.Streams.SenderExceptionStream.Subscribe(OnSenderException));

            _streamDisposables.Add(_client.Streams.RefreshTokenResponseStream.Subscribe(OnRefreshTokenResponse));

            Console.WriteLine("Connecting Client...");

            await _client.Connect(mode);

            ShowDashLine();

            Console.WriteLine("Client successfully connected");

            ShowDashLine();

            Console.WriteLine("Sending App Auth Req...");

            Console.WriteLine("Please wait...");

            ShowDashLine();

            var applicationAuthReq = new ProtoOAApplicationAuthReq
            {
                ClientId     = _app.ClientId,
                ClientSecret = _app.Secret,
            };

            await _client.SendMessage(applicationAuthReq, ProtoOAPayloadType.ProtoOaApplicationAuthReq);

            await Task.Delay(5000);

            Console.WriteLine("You should see the application auth response message before entering any command");

            Console.WriteLine("For commands list and description use 'help' command");

            ShowDashLine();

            GetCommand();
        }
コード例 #37
0
        public ApiResult GetPhoto()
        {
            UserModel userModel = Auth.GetLoginUser(_httpContext);

            return(ApiResult.Success(userModel.HeadPhoto));
        }
コード例 #38
0
ファイル: LoginForm.cs プロジェクト: Naveigell/C-UAS
        public LoginForm()
        {
            InitializeComponent();

            auth = new Auth();
        }
コード例 #39
0
        public static DailyGospelReflection GetUserReflection(int gospelId)
        {
            var service = new DailyGospelReflectionService();

            return(service.GetUserReflection(Auth.user().Id, gospelId));
        }
コード例 #40
0
        /// <summary>
        ///  BETA Create a section group with a given name under a given notebookId
        /// </summary>
        /// <param name="debug">Run the code under the debugger</param>
        /// <param name="notebookId">parent notebook's Id</param>
        /// <param name="sectionName">name of the section group to create</param>
        /// <param name="provider"></param>
        /// <param name="apiRoute"></param>
        /// <remarks>Create section group using a application/json content type</remarks>
        /// <returns>The converted HTTP response message</returns>
        public static async Task <ApiBaseResponse> CreateSectionGroupInNotebook(bool debug, string notebookId, string sectionGroupName, AuthProvider provider, string apiRoute)
        {
            if (debug)
            {
                Debugger.Launch();
                Debugger.Break();
            }

            var client = new HttpClient();

            // Note: API only supports JSON response.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Not adding the Authentication header would produce an unauthorized call and the API will return a 401
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
                                                                                       await Auth.GetAuthToken(provider));

            // Prepare an HTTP POST request to the SectionGroups endpoint
            // The request body content type is application/json and requires a name property
            var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"notebooks/" + notebookId + "/sectiongroups")
            {
                Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionGroupName) + "' }", Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await client.SendAsync(createMessage);

            return(await HttpUtils.TranslateResponse(response));
        }
コード例 #41
0
 public MastodonClient(AppRegistration appRegistration, Auth accessToken)
     : this(appRegistration, accessToken, DefaultHttpClient.Instance)
 {
 }
コード例 #42
0
        public void LogoutTest()
        {
            IRestResponse response = new Auth().Logout();

            Assert.That(response.IsSuccessful);
        }
コード例 #43
0
ファイル: Authorization.cs プロジェクト: jkilgore/Rock-ChMS
        public static void CopyAuthorization( ISecured sourceEntity, ISecured targetEntity, int? personId )
        {
            using ( new Rock.Helpers.UnitOfWorkScope() )
            {
                // If there's no Authorizations object, create it
                if ( Authorizations == null )
                    Load();

                AuthService authService = new AuthService();

                // Delete the current authorizations for the target entity
                foreach(Auth auth in authService.GetAuthsByEntityTypeAndEntityId(targetEntity.AuthEntity, targetEntity.Id))
                    authService.DeleteAuth(auth);

                Dictionary<string, List<AuthRule>> newActions = new Dictionary<string, List<AuthRule>>();

                int order = 0;
                foreach ( KeyValuePair<string, List<AuthRule>> action in Authorizations[sourceEntity.AuthEntity][sourceEntity.Id] )
                    if (targetEntity.SupportedActions.Contains(action.Key))
                    {
                        newActions.Add( action.Key, new List<AuthRule>() );

                        foreach ( AuthRule rule in action.Value )
                        {
                            Auth auth = new Auth();
                            auth.EntityType = targetEntity.AuthEntity;
                            auth.EntityId = targetEntity.Id;
                            auth.Order = order;
                            auth.Action = action.Key;
                            auth.AllowOrDeny = rule.AllowOrDeny;
                            auth.UserOrRole = rule.UserOrRole;
                            auth.UserOrRoleName = rule.UserOrRoleName;

                            authService.AddAuth(auth);
                            authService.Save(auth, personId);

                            newActions[action.Key].Add( new AuthRule( rule.AllowOrDeny, rule.UserOrRole, rule.UserOrRoleName ) );

                            order++;
                        }
                    }

                if ( !Authorizations.ContainsKey( targetEntity.AuthEntity ) )
                    Authorizations.Add( targetEntity.AuthEntity, new Dictionary<int, Dictionary<string, List<AuthRule>>>() );

                Dictionary<int, Dictionary<string, List<AuthRule>>> entityType = Authorizations[targetEntity.AuthEntity];

                if ( !entityType.ContainsKey( targetEntity.Id ) )
                    entityType.Add( targetEntity.Id, new Dictionary<string, List<AuthRule>>() );

                entityType[targetEntity.Id] = newActions;
            }
        }
コード例 #44
0
        //============================ Récuperation de l'employé =============================//

        public void getclient(Auth client)
        {
            this.client    = (from recup in db.Auth where recup.Id == client.Id select recup).FirstOrDefault();
            user.Text      = client.user;
            user.IsEnabled = false;
        }
コード例 #45
0
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {
     return(Auth.IsAdmin());
 }
コード例 #46
0
        public void ShouldReturnAccessTokenValidGivenRestoredAuthData()
        {
            // Given
            var accessTokenExpireIn = DateTime.UtcNow.AddHours(1).Ticks/TimeSpan.TicksPerMillisecond;
            var refreshTokenExpireIn = DateTime.UtcNow.AddDays(7).Ticks / TimeSpan.TicksPerMillisecond;
            var data = new Dictionary<string, string>()
            {
                {"access_token", "ac1"},
                {"expires_in", "3598"},
                {"expire_time", accessTokenExpireIn.ToString()},
                {"refresh_token", "x"},
                {"refresh_token_expires_in", "604798"},
                {"refresh_token_expire_time", refreshTokenExpireIn.ToString()},
            };

            // When
            var auth = new Auth();
            auth.SetData(data);

            // Then expire_time should be set and token still valid
            var newData = auth.GetData();
            Assert.That(newData["expire_time"], Is.EqualTo(data["expire_time"]));
            Assert.That(auth.IsAccessTokenValid(), Is.EqualTo(true));
        }
コード例 #47
0
 private static void CreateAuth()
 {
     _auth = new Auth(GetConfig("securityKeySecret", ""),
                      GetConfig("securityKeyIssuer", ""));
 }
コード例 #48
0
ファイル: ToDoPage.xaml.cs プロジェクト: denaldo98/AppXamarin
        public ToDoPage()
        {
            InitializeComponent();
            Title = "To do list";

            vm = Resources["vm"] as AttivitaVM; //accedo alla risorsa tramite chiave

            ToolbarItem item = new ToolbarItem
            {
                Text            = "Contatti",
                IconImageSource = ImageSource.FromFile("example_icon.png"),
                Order           = ToolbarItemOrder.Secondary,
                Priority        = 0
            };

            item.Clicked += (sender, args) => {
                Navigation.PushAsync(new ContattiPage());
            };
            this.ToolbarItems.Add(item);


            ToolbarItem item2 = new ToolbarItem
            {
                Text     = "Faq",
                Order    = ToolbarItemOrder.Secondary,
                Priority = 0
            };

            item2.Clicked += (sender, args) => {
                Navigation.PushAsync(new FaqPage());
            };
            this.ToolbarItems.Add(item2);

            ToolbarItem item4 = new ToolbarItem
            {
                Text     = "Informativa Privacy",
                Order    = ToolbarItemOrder.Secondary,
                Priority = 0
            };

            item4.Clicked += (sender, args) => {
                Navigation.PushAsync(new PrivacyPage());
            };
            this.ToolbarItems.Add(item4);

            ToolbarItem item3 = new ToolbarItem
            {
                Text            = "Logout",
                IconImageSource = ImageSource.FromFile("example_icon.png"),
                Order           = ToolbarItemOrder.Secondary,
                Priority        = 0
            };

            item3.Clicked += async(sender, args) => {
                bool logout = await Auth.Logout();

                if (logout)
                {
                    Application.Current.Properties["logged"] = "false";
                    await Application.Current.SavePropertiesAsync();
                    await DisplayAlert("Attenzione!", "Il logout è stato eseguito, l'app verrà chiusa!", "Ok");

                    await System.Threading.Tasks.Task.Delay(1000);

                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                else
                {
                    await DisplayAlert("Attenzione!", "Non è stato possibile effettuare il logout", "Ok");
                }
            };
            this.ToolbarItems.Add(item3);
        }
コード例 #49
0
ファイル: AuthProvider.cs プロジェクト: jmaucher/SStack
 public abstract object Authenticate(IServiceBase authService, IAuthSession session, Auth request);
コード例 #50
0
ファイル: OAuthProvider.cs プロジェクト: Qasemt/NServiceKit
        /// <summary>
        /// The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally.
        /// Overridable so you can provide your own Auth implementation.
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="session"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = Init(authService, ref session, request);

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                OAuthUtils.RequestToken = tokens.RequestToken;
                OAuthUtils.RequestTokenSecret = tokens.RequestTokenSecret;
                OAuthUtils.AuthorizationToken = request.oauth_token;
                OAuthUtils.AuthorizationVerifier = request.oauth_verifier;

                if (OAuthUtils.AcquireAccessToken())
                {
                    tokens.AccessToken = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;
                    session.IsAuthenticated = true;
                    OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo);
                    authService.SaveSession(session, SessionExpiry);

                    //Haz access!
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));
                }

                //No Joy :(
                tokens.RequestToken = null;
                tokens.RequestTokenSecret = null;
                authService.SaveSession(session, SessionExpiry);
                return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                authService.SaveSession(session, SessionExpiry);

                //Redirect to OAuth provider to approve access
                return authService.Redirect(this.AuthorizeUrl
                    .AddQueryParam("oauth_token", tokens.RequestToken)
                    .AddQueryParam("oauth_callback", session.ReferrerUrl));
            }

            return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed"));
        }
コード例 #51
0
ファイル: OAuthProvider.cs プロジェクト: Qasemt/NServiceKit
        /// <summary>Determine if the current session is already authenticated with this AuthProvider.</summary>
        ///
        /// <param name="session">The session.</param>
        /// <param name="tokens"> The tokens.</param>
        /// <param name="request">The request.</param>
        ///
        /// <returns>true if authorized, false if not.</returns>
        public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null)
        {
            if (request != null)
            {
                if (!LoginMatchesSession(session, request.UserName)) return false;
            }

            return tokens != null && !string.IsNullOrEmpty(tokens.AccessTokenSecret);
        }
コード例 #52
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = Init(authService, ref session, request);

            var httpReq    = authService.RequestContext.Get <IHttpRequest>();
            var httpMethod = httpReq.HttpMethod;

            if (httpMethod == HttpMethod.Post)
            {
                var openIdUrl = httpReq.GetParam("OpenIdUrl") ?? base.AuthRealm;
                if (openIdUrl.IsNullOrEmpty())
                {
                    throw new ArgumentException("'OpenIdUrl' is required a required field");
                }

                try
                {
                    using (var openid = new OpenIdRelyingParty())
                    {
                        var openIdRequest = openid.CreateRequest(openIdUrl);

                        AddAttributeExchangeExtensions(openIdRequest);

                        // This is where you would add any OpenID extensions you wanted
                        // to include in the authentication request.
                        openIdRequest.AddExtension(CreateClaimsRequest(httpReq));

                        // Send your visitor to their Provider for authentication.
                        var openIdResponse = openIdRequest.RedirectingResponse;
                        var contentType    = openIdResponse.Headers[HttpHeaders.ContentType];
                        var httpResult     = new HttpResult(openIdResponse.ResponseStream, contentType)
                        {
                            StatusCode        = openIdResponse.Status,
                            StatusDescription = "Moved Temporarily",
                        };
                        foreach (string header in openIdResponse.Headers)
                        {
                            httpResult.Headers[header] = openIdResponse.Headers[header];
                        }
                        return(httpResult);
                    }
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(openIdUrl), ex);
                    return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")));
                }
            }

            if (httpMethod == HttpMethod.Get)
            {
                using (var openid = new OpenIdRelyingParty())
                {
                    var response = openid.GetResponse();
                    if (response != null)
                    {
                        switch (response.Status)
                        {
                        case AuthenticationStatus.Authenticated:

                            var authInfo = CreateAuthInfo(response);

                            // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
                            // with the OpenID Claimed Identifier as their username.
                            session.IsAuthenticated = true;
                            authService.SaveSession(session, SessionExpiry);
                            OnAuthenticated(authService, session, tokens, authInfo);

                            //Haz access!
                            return(authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")));

                        case AuthenticationStatus.Canceled:
                            return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "ProviderCancelled")));

                        case AuthenticationStatus.Failed:
                            return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")));
                        }
                    }
                }
            }

            //Shouldn't get here
            return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")));
        }
コード例 #53
0
 private void OnLoginClick()
 {
     Auth form = new Auth();
     form.ShowDialog();
 }
コード例 #54
0
        private IAuthenticatedUser GetAuthenticatedUser(Token token)
        {
            var credentials = Auth.SetUserCredentials(ConsumerKey, ConsumerSecret, token.Key, token.Secret);

            return(User.GetAuthenticatedUser(credentials));
        }
コード例 #55
0
ファイル: OAuth2Provider.cs プロジェクト: Qasemt/NServiceKit
        /// <summary>The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. Overridable so you can provide your own Auth implementation.</summary>
        ///
        /// <param name="authService">The authentication service.</param>
        /// <param name="session">    The session.</param>
        /// <param name="request">    The request.</param>
        ///
        /// <returns>An object.</returns>
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = this.Init(authService, ref session, request);

            var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl) };
            var authClient = new WebServerClient(authServer, this.ConsumerKey) {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            var authState = authClient.ProcessUserAuthorization();
            if (authState == null)
            {
                try
                {
                    var authReq = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl));
                    var authContentType = authReq.Headers[HttpHeaders.ContentType];
                    var httpResult = new HttpResult(authReq.ResponseStream, authContentType) { StatusCode = authReq.Status, StatusDescription = "Moved Temporarily" };
                    foreach (string header in authReq.Headers)
                    {
                        httpResult.Headers[header] = authReq.Headers[header];
                    }

                    foreach (string name in authReq.Cookies)
                    {
                        var cookie = authReq.Cookies[name];

                        if (cookie != null)
                        {
                            httpResult.SetSessionCookie(name, cookie.Value, cookie.Path);
                        }
                    }

                    authService.SaveSession(session, this.SessionExpiry);
                    return httpResult;
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
                }
            }

            var accessToken = authState.AccessToken;
            if (accessToken != null)
            {
                try
                {
                    tokens.AccessToken = accessToken;
                    tokens.RefreshToken = authState.RefreshToken;
                    tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
                    session.IsAuthenticated = true;
                    var authInfo = this.CreateAuthInfo(accessToken);
                    this.OnAuthenticated(authService, session, tokens, authInfo);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"));
                    }
                }
            }

            return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed"));
        }
コード例 #56
0
    private IEnumerator SimulateCoroutine()
    {
        UIManager.Instance.Prompt("Simulation started");
        uiTabGroup.SelectTab(simulationTabId);

        simulationStats = new SimulationStats();

        // Describes the currently simulated in-game time (in hours, from 0.00f to 24.00f)
        float inGameTime = 0.0f;

        while (inGameTime <= 24.0f)
        {
            SiteManager.Instance.trafficManager.SimulateAtTime(inGameTime);

            inGameTime += Time.deltaTime * simulationTimescale / 3600.0f;
            simulationStats.TotalSimulationTime += Time.deltaTime;

            if (inGameTime >= 3.0f && inGameTime <= 9.0f)
            {
                clockDayBackground.color = new Color(
                    clockDayBackground.color.r,
                    clockDayBackground.color.g,
                    clockDayBackground.color.b,
                    (inGameTime - 3.0f) / 6.0f
                    );

                clockNightBackground.color = new Color(
                    clockNightBackground.color.r,
                    clockNightBackground.color.g,
                    clockNightBackground.color.b,
                    (9.0f - inGameTime) / 6.0f
                    );
            }
            else if (inGameTime >= 15.0f && inGameTime <= 21.0f)
            {
                clockDayBackground.color = new Color(
                    clockDayBackground.color.r,
                    clockDayBackground.color.g,
                    clockDayBackground.color.b,
                    (21.0f - inGameTime) / 6.0f
                    );

                clockNightBackground.color = new Color(
                    clockNightBackground.color.r,
                    clockNightBackground.color.g,
                    clockNightBackground.color.b,
                    (inGameTime - 15.0f) / 6.0f
                    );
            }

            clockHand.rotation = Quaternion.Euler(0.0f, 0.0f, inGameTime * -30.0f);

            trafficQualitySlider.value = simulationStats.TrafficQuality;

            yield return(null);
        }

        while (simulationStats.NumVehiclesReachedExit != simulationStats.NumVehiclesSpawned)
        {
            simulationStats.TotalSimulationTime += Time.deltaTime;

            trafficQualitySlider.value = simulationStats.TrafficQuality;

            yield return(null);
        }

        uiTabGroup.SelectTab(defaultTabId);
        UIManager.Instance.Prompt("Simulation ended");

        OpenSimulationStats();

        Dictionary <string, string> postParams = new Dictionary <string, string>();

        postParams.Add(USERNAME_PARAM, SessionManager.Instance.Username);
        postParams.Add(SESSION_ID_PARAM, SessionManager.Instance.SessionId);
        postParams.Add(LEVEL_ID_PARAM, SessionManager.Instance.LevelId.ToString());
        postParams.Add(SCORE_PARAM, simulationStats.Score.ToString());
        StartCoroutine(Auth.AsyncPost(
                           SessionManager.Instance.host, ATTEMPT_RANK_DIR,
                           postParams, FetchRankCallback));
    }
コード例 #57
0
ファイル: OAuthProvider.cs プロジェクト: Qasemt/NServiceKit
        /// <summary>
        /// Sets the CallbackUrl and session.ReferrerUrl if not set and initializes the session tokens for this AuthProvider
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="session"></param>
        /// <param name="request"> </param>
        /// <returns></returns>
        protected IOAuthTokens Init(IServiceBase authService, ref IAuthSession session, Auth request)
        {
            if (request != null && !LoginMatchesSession(session, request.UserName))
            {
                //authService.RemoveSession();
                //session = authService.GetSession();
            }

            var requestUri = authService.RequestContext.AbsoluteUri;
            if (this.CallbackUrl.IsNullOrEmpty())
                this.CallbackUrl = requestUri;

            if (session.ReferrerUrl.IsNullOrEmpty())
                session.ReferrerUrl = (request != null ? request.Continue : null)
                    ?? authService.RequestContext.GetHeader("Referer");

            if (session.ReferrerUrl.IsNullOrEmpty() 
                || session.ReferrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0)
                session.ReferrerUrl = this.RedirectUrl 
                    ?? NServiceKitHttpHandlerFactory.GetBaseUrl()
                    ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1, StringComparison.Ordinal));

            var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == Provider);
            if (tokens == null)
                session.ProviderOAuthAccess.Add(tokens = new OAuthTokens { Provider = Provider });

            return tokens;
        }
コード例 #58
0
        public static StellarMessage Decode(IByteReader stream)
        {
            StellarMessage decodedStellarMessage = new StellarMessage();

            decodedStellarMessage.Discriminant = MessageType.Decode(stream);
            switch (decodedStellarMessage.Discriminant.InnerValue)
            {
            case MessageType.MessageTypeEnum.ERROR_MSG:
                decodedStellarMessage.Error = Error.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.HELLO:
                decodedStellarMessage.Hello = Hello.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.AUTH:
                decodedStellarMessage.Auth = Auth.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.DONT_HAVE:
                decodedStellarMessage.DontHave = DontHave.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.GET_PEERS:
                break;

            case MessageType.MessageTypeEnum.PEERS:
                int peerssize = XdrEncoding.DecodeInt32(stream);
                decodedStellarMessage.Peers = new PeerAddress[peerssize];
                for (int i = 0; i < peerssize; i++)
                {
                    decodedStellarMessage.Peers[i] = PeerAddress.Decode(stream);
                }
                break;

            case MessageType.MessageTypeEnum.GET_TX_SET:
                decodedStellarMessage.TxSetHash = Uint256.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.TX_SET:
                decodedStellarMessage.TxSet = TransactionSet.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.TRANSACTION:
                decodedStellarMessage.Transaction = TransactionEnvelope.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.GET_SCP_QUORUMSET:
                decodedStellarMessage.QSetHash = Uint256.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.SCP_QUORUMSET:
                decodedStellarMessage.QSet = SCPQuorumSet.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.SCP_MESSAGE:
                decodedStellarMessage.Envelope = SCPEnvelope.Decode(stream);
                break;

            case MessageType.MessageTypeEnum.GET_SCP_STATE:
                decodedStellarMessage.GetSCPLedgerSeq = Uint32.Decode(stream);
                break;
            }
            return(decodedStellarMessage);
        }
コード例 #59
0
        public IRPResponse GetIRPList()
        {
            int assessmentId = Auth.AssessmentForUser();

            return((new IRPManager()).GetIRPList(assessmentId));
        }
コード例 #60
0
        public static void Encode(IByteWriter stream, StellarMessage encodedStellarMessage)
        {
            XdrEncoding.EncodeInt32((int)encodedStellarMessage.Discriminant.InnerValue, stream);
            switch (encodedStellarMessage.Discriminant.InnerValue)
            {
            case MessageType.MessageTypeEnum.ERROR_MSG:
                Error.Encode(stream, encodedStellarMessage.Error);
                break;

            case MessageType.MessageTypeEnum.HELLO:
                Hello.Encode(stream, encodedStellarMessage.Hello);
                break;

            case MessageType.MessageTypeEnum.AUTH:
                Auth.Encode(stream, encodedStellarMessage.Auth);
                break;

            case MessageType.MessageTypeEnum.DONT_HAVE:
                DontHave.Encode(stream, encodedStellarMessage.DontHave);
                break;

            case MessageType.MessageTypeEnum.GET_PEERS:
                break;

            case MessageType.MessageTypeEnum.PEERS:
                int peerssize = encodedStellarMessage.Peers.Length;
                XdrEncoding.EncodeInt32(peerssize, stream);
                for (int i = 0; i < peerssize; i++)
                {
                    PeerAddress.Encode(stream, encodedStellarMessage.Peers[i]);
                }
                break;

            case MessageType.MessageTypeEnum.GET_TX_SET:
                Uint256.Encode(stream, encodedStellarMessage.TxSetHash);
                break;

            case MessageType.MessageTypeEnum.TX_SET:
                TransactionSet.Encode(stream, encodedStellarMessage.TxSet);
                break;

            case MessageType.MessageTypeEnum.TRANSACTION:
                TransactionEnvelope.Encode(stream, encodedStellarMessage.Transaction);
                break;

            case MessageType.MessageTypeEnum.GET_SCP_QUORUMSET:
                Uint256.Encode(stream, encodedStellarMessage.QSetHash);
                break;

            case MessageType.MessageTypeEnum.SCP_QUORUMSET:
                SCPQuorumSet.Encode(stream, encodedStellarMessage.QSet);
                break;

            case MessageType.MessageTypeEnum.SCP_MESSAGE:
                SCPEnvelope.Encode(stream, encodedStellarMessage.Envelope);
                break;

            case MessageType.MessageTypeEnum.GET_SCP_STATE:
                Uint32.Encode(stream, encodedStellarMessage.GetSCPLedgerSeq);
                break;
            }
        }