/// <summary>Downloads derserialzes and add/merges a table.</summary>
        /// <typeparam name="TPoco">The POCO type of the table.</typeparam>
        /// <param name="tableName">Name of the table to request.</param>
        /// <param name="dbTable">The actual POCO table.</param>
        /// <param name="cred">Credentials to be used to authenticate with the server. Only required for some
        /// types.</param>
        /// <returns>Null on success, otherwise an error message.</returns>
        private async Task <string> GetReqDeserMergeTable <TPoco>(string tableName, DbSet <TPoco> dbTable,
                                                                  Creds cred = null) where TPoco : class
        {
            // Any exeption raised in these methods result in abort exeption with an error message for debug.
            try
            {
                // Step 1: Request
                var response = await GetRequestTableThrowOnErrorAsync(tableName, cred);

                // Step 2: Deserialise
                var updatesFromServer = await DeserializeTableThrowOnErrrorAsync <TPoco>(tableName, response);

                Debug.WriteLineIf(updatesFromServer.Count > 0, $"Deserialised {updatesFromServer.Count} for {tableName}");

                // Step 3: Merge
                // Get the DbSet that this request should be inserted into.
                AddOrModify(updatesFromServer, dbTable);
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }

            return(null);
        }
Example #2
0
    public void Activate(Creds creds)
    {
        if (guarded)
        {
            return;
        }

        if (creds.Level < Level)
        {
            if (creds.Owner != null && creds.Owner.CompareTag("Guard"))
            {
                creds.Owner.SendMessage("Interrupt");
            }
            return;
        }
        guarded = creds.Owner != null && creds.Owner.CompareTag("Guard");

        Open = !Open || guarded;

        if (guarded)
        {
            StartCoroutine(Unguard());
        }
        else
        {
            GameObject.FindGameObjectWithTag("Player").GetComponent <AudioSource>().PlayOneShot(GetComponent <Networkable>().ActivateClip);
        }
    }
Example #3
0
 public LoginViewModel()
 {
     _credentials = new Creds();
     Password     = new SecureString();
     Mediator.Mediator.Subscribe("ClearLogin", this.ClearPage);
     Mediator.Mediator.Subscribe("SessionID", this.SetSessionID);
 }
Example #4
0
        public static Message Submit(string[] parameters, MessageEvent e)
        {
            if (System.DateTime.UtcNow.AddHours(8).DayOfWeek != System.DayOfWeek.Sunday)
            {
                return(new Message("only sunday"));
            }
            if (Creds.ensureLoggedIn(e.GetEndpoint().Item2).Result == false)
            {
                return(new Message("请重新进行/init"));
            }
            var d = new cqhttp.Cyan.Utils.Dialogue();

            d["BEGIN"] = async(c, m) => {
                await WRScraper.submitWR(
                    Creds.loggedIn[e.GetEndpoint().Item2],
                    m.GetRaw()
                    );

                await c.SendTextAsync(e.GetEndpoint(), "已提交");

                await WRScraper.updateIndex();

                return("DONE");
            };
            cqhttp.Cyan.Utils.DialoguePool.Join(e.GetEndpoint(), d);
            return(new Message("请发送周报的内容:"));
        }
Example #5
0
 public static Message GetWR(string[] parameters, MessageEvent e)
 {
     if (e.GetEndpoint().Item1 != MessageType.private_)
     {
         return(new Message("private chat only"));
     }
     Task.Run(async() => {
         if (await Creds.ensureLoggedIn(e.GetEndpoint().Item2))
         {
             string ret = "目前有: ";
             WRScraper.submittedUsers.ForEach((s) => ret += s + ',');
             ret += "已经提交了周报\n你要看谁的?";
             await Program.client.SendTextAsync(
                 e.GetEndpoint(), ret
                 );
         }
     }).ContinueWith((t) => {
         var d      = new cqhttp.Cyan.Utils.Dialogue();
         d["BEGIN"] = async(c, m) => {
             await c.SendTextAsync(
                 e.GetEndpoint(),
                 WRScraper.getWRFor(
                     Creds.loggedIn[e.GetEndpoint().Item2], m.GetRaw()).Result
                 );
             return("DONE");
         };
         cqhttp.Cyan.Utils.DialoguePool.Join(e.GetEndpoint(), d);
     });
     return(new Message());
 }
Example #6
0
 public static Message Init(string[] parameters, MessageEvent e)
 {
     if (e.GetEndpoint().Item1 != MessageType.private_)
     {
         return(new Message("private chat only"));
     }
     Program.client.SendTextAsync(
         e.GetEndpoint(),
         "请输入登陆所使用的昵称"
         ).ContinueWith((t) => {
         var d           = new cqhttp.Cyan.Utils.Dialogue();
         string username = "", password = "";
         d["BEGIN"]      = async(c, m) => {
             username = m.GetRaw();
             await c.SendTextAsync(e.GetEndpoint(), "请输入token");
             return("SET_TOKEN");
         };
         d["SET_TOKEN"] = async(c, m) => {
             password = m.GetRaw();
             Creds.PersistData(e.GetEndpoint().Item2, username, password);
             await c.SendTextAsync(e.GetEndpoint(), $"设置完成,用户名:{username},token:{password}");
             return("DONE");
         };
         cqhttp.Cyan.Utils.DialoguePool.Join(e.GetEndpoint(), d);
     });
     return(new Message());
 }
Example #7
0
        public async void Login()
        {
            LoginEnabled = false;
            const string entryUrl  = "https://greenhouseapi.azurewebsites.net/.auth/login/twitter";
            const string resultUrl = "https://greenhouseapi.azurewebsites.net/.auth/login/done";

            if (!Request.IsInternetAvailable())
            {
                LoginEnabled = true;
                FriendlyText = "Internet seems unavailable, please check your connection and try again.";
                return;
            }

            Creds creds;

            try
            {
                creds = await Creds.FromBroker(entryUrl, resultUrl);
            }
            catch (Exception ex)
            {
                Util.LoggingService.LogInfo($"Login failed or cancelled with error: {ex}", Windows.Foundation.Diagnostics.LoggingLevel.Warning);
                FriendlyText = "Login failed or cancelled.";
                LoginEnabled = true;
                return;
            }

            var settings = SettingsService.Instance;

            settings.SetNewCreds(creds.Token, creds.Userid, Guid.Parse(creds.StableSid.Remove(0, 4)));

            UpdateCredsAndTokens();

            ((Frame)Window.Current.Content).Navigate(typeof(SyncingView));
        }
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.

        var creds = new Creds()
        {
            username = Configuration["cloudantNoSQLDB:0:credentials:username"],
            password = Configuration["cloudantNoSQLDB:0:credentials:password"],
            host     = Configuration["cloudantNoSQLDB:0:credentials:host"]
        };

        if (creds.username != null && creds.password != null && creds.host != null)
        {
            services.AddAuthorization();
            services.AddSingleton(typeof(Creds), creds);
            services.AddTransient <ICloudantService, CloudantService>();
            services.AddTransient <LoggingHandler>();
            services.AddHttpClient("cloudant", client =>
            {
                var auth = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds.username + ":" + creds.password));

                client.BaseAddress = new Uri(Configuration["cloudantNoSQLDB:0:credentials:url"]);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
            })
            .AddHttpMessageHandler <LoggingHandler>();
        }

        services.AddMvc();
    }
Example #9
0
        public async Task <IActionResult> PostLogin(Creds creds)
        {
            //todo: Ensure that these input values are not logged.
            var user = await SignInUser(creds.UserName, creds.Password);

            if (user == null)
            {
                return(BadRequest("Invalid credentials"));
            }
            var identity = await _repository.GetClaimsIdentity(user.UserName);

            var jwtAccessToken = await GetAccessToken(identity, user);

            var jwtRefreshToken = await GetRefreshToken(identity, user);

            // Create the JWT security tokens and encode it.
            var encodedJwtAccess  = new JwtSecurityTokenHandler().WriteToken(jwtAccessToken);
            var encodedJwtRefresh = new JwtSecurityTokenHandler().WriteToken(jwtRefreshToken);

            // Serialize and return the response
            var response = new
            {
                access_token  = encodedJwtAccess,
                refresh_token = encodedJwtRefresh,
                expires_in    = (int)_jwtOptions.ValidFor.TotalSeconds
            };
            var json = JsonConvert.SerializeObject(response, _serializerSettings);

            _repository.AddRefreshToken(encodedJwtRefresh, user, jwtRefreshToken.ValidTo, this.HttpContext.Connection.RemoteIpAddress.ToString());
            return(new OkObjectResult(json));
        }
 public GenericCloudantService()
 {
     _cloudantCreds = new Creds()
     {
         host     = "******.cloudant.com",
         username = "******",
         password = "******"
     };
 }
Example #11
0
        public ActionResult CreateSecondaryAccountAccess(SecondaryAccountAccess secondaryAccountAccess)
        {
            string errorMessage = "";

            //Check to see if the account exists
            if (!DbHelper.DoesAccountExist(secondaryAccountAccess.SecondaryAccountEmail))
            {
                errorMessage = "Invalid Email";
            }
            // make sure the account isnt already a secondary account
            else if (DbHelper.IsAccountAlreadySecondary(secondaryAccountAccess.SecondaryAccountEmail))
            {
                errorMessage = "This Account is already a secondary account.";
            }
            else
            {
                secondaryAccountAccess.OwnerAccountID     = SessionHelper.GetAccountIdFromSession();
                secondaryAccountAccess.OwnerEmail         = DbHelper.GetEmailById(SessionHelper.GetAccountIdFromSession());
                secondaryAccountAccess.SecondaryAccountID = DbHelper.GetAccountIdByEmail(secondaryAccountAccess.SecondaryAccountEmail);
                secondaryAccountAccess.AccessToken        = DbHelper.RandomString();
                secondaryAccountAccess.OwnerEnabled       = true;
                secondaryAccountAccess.SecondaryEnabled   = false;
                secondaryAccountAccess.LastEdited         = DateTime.Now;

                using (var db = new AllStockedDBEntities())
                {
                    try
                    {
                        db.SecondaryAccountAccesses.Add(secondaryAccountAccess);
                        db.SaveChanges();

                        string senderName = DbHelper.GetAccountFullNameById(secondaryAccountAccess.OwnerAccountID);

                        // Sends email to requested account with the Access token to become secondary Account
                        // I am sending these emails to self for testing purposes.
                        //Debug
                        DbHelper.EmailSecondaryAccessRequest(senderName, Creds.EmailCreds(), secondaryAccountAccess.AccessToken);
                        //Production
                        //DbHelper.EmailSecondaryAccessRequest(senderName, secondaryAccountAccess.SecondaryAccountEmail,  secondaryAccountAccess.AccessToken);
                    }
                    catch
                    {
                        errorMessage = "Error processing your request";
                    }
                }
            }

            //Add Error Message
            if (!String.IsNullOrEmpty(errorMessage))
            {
                TempData["ErrorMessage"] = errorMessage;
            }

            return(RedirectToAction("Settings", "Settings"));
        }
        /// <summary>Only supports tables that derive from BaseEntity and Croptype.</summary>
        /// <param name="table">The DBSet object for the table.</param>
        /// <param name="tableName">The name of the table in the API .</param>
        /// <param name="lastPost">The last time the table was synced.</param>
        /// <param name="creds">Authentication credentials.</param>
        /// <returns>Null on success otherwise an error message.</returns>
        private static async Task<string> PostRequestTableWhereUpdatedAsync(IQueryable<BaseEntity> table,
            string tableName, DateTimeOffset lastPost, Creds creds)
        {
            var edited = table.AsNoTracking().Where(t => t.UpdatedAt > lastPost).ToList();

            if (!edited.Any()) return null;

            var data = JsonConvert.SerializeObject(edited, Formatting.None);
            var req = await Request.PostTable(ApiUrl, tableName, data, creds).ConfigureAwait(false);
            return req;
        }
Example #13
0
 public void Activate(Creds creds)
 {
     if (creds.Owner != null && creds.Owner.GetComponent<Player>())
     {
         var n = GetComponent<Networkable>();
         var player = creds.Owner.GetComponent<Player>();
         player.Hack = player.Hack != n ? n : null;
         n.Status = player.Hack == n ? "Active" : "Idle";
         GameObject.FindGameObjectWithTag("Player").GetComponent<AudioSource>().PlayOneShot(GetComponent<Networkable>().ActivateClip);
     }
 }
Example #14
0
 public void Activate(Creds creds)
 {
     if (creds.Owner != null && creds.Owner.GetComponent <Player>())
     {
         var n      = GetComponent <Networkable>();
         var player = creds.Owner.GetComponent <Player>();
         player.Hack = player.Hack != n ? n : null;
         n.Status    = player.Hack == n ? "Active" : "Idle";
         GameObject.FindGameObjectWithTag("Player").GetComponent <AudioSource>().PlayOneShot(GetComponent <Networkable>().ActivateClip);
     }
 }
Example #15
0
        /// <summary>Posts changes saved in the local DB (excluding histories) to the server. Only Items with
        /// UpdatedAt or CreatedAt changed since the last post are posted.</summary>
        private static async Task <List <string> > PostRequestUpdateAsync(MainDbContext db)
        {
            var creds = Creds.FromUserIdAndToken(Settings.Instance.CredUserId, Settings.Instance.CredToken);

            var lastDatabasePost = Settings.Instance.LastSuccessfulGeneralDbPost;
            var postTime         = DateTimeOffset.Now;

            var responses = new List <string>();

            // Simple tables that change:
            // CropCycle, Devices.

            responses.Add(
                await
                PostRequestTableWhereUpdatedAsync(db.Locations, nameof(db.Locations), lastDatabasePost, creds)
                .ConfigureAwait(false));

            // CropTypes is unique:
            var changedCropTypes = db.CropTypes.Where(c => c.CreatedAt > lastDatabasePost);

            if (changedCropTypes.Any())
            {
                var cropTypeData = JsonConvert.SerializeObject(changedCropTypes);
                responses.Add(
                    await Request.PostTable(ApiUrl, nameof(db.CropTypes), cropTypeData, creds).ConfigureAwait(false));
            }

            responses.Add(
                await
                PostRequestTableWhereUpdatedAsync(db.CropCycles, nameof(db.CropCycles), lastDatabasePost, creds)
                .ConfigureAwait(false));
            responses.Add(
                await
                PostRequestTableWhereUpdatedAsync(db.Devices, nameof(db.Devices), lastDatabasePost, creds)
                .ConfigureAwait(false));
            responses.Add(
                await
                PostRequestTableWhereUpdatedAsync(db.Sensors, nameof(db.Sensors), lastDatabasePost, creds)
                .ConfigureAwait(false));
            responses.Add(
                await
                PostRequestTableWhereUpdatedAsync(db.Relays, nameof(db.Relays), lastDatabasePost, creds)
                .ConfigureAwait(false));


            var errors = responses.Where(r => r != null).ToList();

            if (!errors.Any())
            {
                Settings.Instance.LastSuccessfulGeneralDbPost = postTime;
            }
            return(errors);
        }
Example #16
0
        public LoginViewModel()
        {
            _credentials = new Creds
            {
                Username = (string)Microsoft.Win32.Registry.GetValue(credentialsKey, "Username", ""),
                Password = Utilities.SecureStringUtility.StringToSecureString((string)Microsoft.Win32.Registry.GetValue(credentialsKey, "Password", ""))
            };

            _isSelected             = false;
            _incorrectLoginAttempts = 0;
            Mediator.Mediator.Subscribe("ClearLogin", this.ClearPage);
        }
Example #17
0
    public void Activate(Creds creds)
    {
        if (Opened || creds.Level < Level || !GetComponent<Networkable>().Hacked) return;

        net.Status = "Unlocked";
        Opened = true;
        var card = Instantiate(Card);
        card.transform.position = transform.position + Vector3.up;
        card.GetComponent<Rigidbody>().AddForce(Random.onUnitSphere*5);
        card.Level = net.Level + Random.Range(1, 3);
        card.Player = Guard._player;
        GetComponent<Light>().enabled = false; GameObject.FindGameObjectWithTag("Player").GetComponent<AudioSource>().PlayOneShot(GetComponent<Networkable>().ActivateClip);
    }
Example #18
0
        private Creds InputCredentials(string title = "", bool canCancel = true)
        {
            CredentialsForm loginForm = new CredentialsForm(title, canCancel);

            loginForm.ShowDialog();
            Creds credentials = null;

            if (loginForm.DialogResult == DialogResult.OK)
            {
                credentials = loginForm.LoginDetails;
            }
            loginForm.Dispose();
            return(credentials);
        }
Example #19
0
        private JwtSecurityToken GetJwtSecurityToken(Creds user)
        {
            var userClaims = GetTokenClaims(user);

            return(new JwtSecurityToken(
                       issuer: "test.com",
                       notBefore: DateTime.UtcNow,
                       audience: "test.com",
                       claims: userClaims,
                       expires: DateTime.UtcNow.AddMinutes(60),
                       signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ASSPJDFNNJF{IUSNF{UINSDF{SFNNF{")), SecurityAlgorithms.HmacSha256)

                       ));
        }
Example #20
0
        private async Task <List <string> > GetRequestUpdateAsync(MainDbContext db)
        {
            var settings = Settings.Instance;
            var creds    = Creds.FromUserIdAndToken(settings.CredUserId, settings.CredToken);
            var now      = DateTimeOffset.Now;

            var res = new List <string>();


            // Setting configure await to false allows all of this method to be run on the threadpool.
            // Without setting it false the continuation would be posted onto the SynchronisationContext, which is the UI.
            res.Add(await GetReqDeserMergeTable(nameof(db.Parameters), db.Parameters).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.Placements), db.Placements).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.Subsystems), db.Subsystems).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.RelayTypes), db.RelayTypes).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.SensorTypes), db.SensorTypes).ConfigureAwait(false));

            if (res.Any(r => r != null))
            {
                return(res.Where(r => r != null).ToList());
            }
            db.SaveChanges();

            // Editable types that must be merged:

            res.Add(await GetReqDeserMergeTable(nameof(db.People), db.People, creds).ConfigureAwait(false));
            // Crop type is the only mergable that is no-auth.
            res.Add(await GetReqDeserMergeTable(nameof(db.CropTypes), db.CropTypes).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.Locations), db.Locations, creds).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.CropCycles), db.CropCycles, creds).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.Devices), db.Devices, creds).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.Relays), db.Relays, creds).ConfigureAwait(false));
            res.Add(await GetReqDeserMergeTable(nameof(db.Sensors), db.Sensors, creds).ConfigureAwait(false));

            if (res.Any(r => r != null))
            {
                return(res.Where(r => r != null).ToList());
            }
            db.SaveChanges();


            res = res.Where(r => r != null).ToList();

            if (!res.Any())
            {
                settings.LastSuccessfulGeneralDbGet = now;
            }

            return(res);
        }
        public IActionResult Delete(int id)
        {
            Creds temp = _RESTContext.Creds.FirstOrDefault(x => x.Id == id);

            if (temp != null)
            {
                _RESTContext.Creds.Remove(temp);
                _RESTContext.SaveChanges();
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
Example #22
0
        public IHttpActionResult PostAuth([FromBody] Creds creds)
        {
            if (string.IsNullOrEmpty(creds.ToString()))
            {
                return(StatusCode(HttpStatusCode.BadRequest));
            }

            User user = GetUser(creds.username, creds.password);

            if (user is null)
            {
                return(NotFound());
            }

            return(Ok(user));
        }
Example #23
0
    public void Activate(Creds creds)
    {
        if (Opened || creds.Level < Level || !GetComponent <Networkable>().Hacked)
        {
            return;
        }

        net.Status = "Unlocked";
        Opened     = true;
        var card = Instantiate(Card);

        card.transform.position = transform.position + Vector3.up;
        card.GetComponent <Rigidbody>().AddForce(Random.onUnitSphere * 5);
        card.Level  = net.Level + Random.Range(1, 3);
        card.Player = Guard._player;
        GetComponent <Light>().enabled = false; GameObject.FindGameObjectWithTag("Player").GetComponent <AudioSource>().PlayOneShot(GetComponent <Networkable>().ActivateClip);
    }
Example #24
0
        public async Task CreateAsync(Creds creds, Role[] roles)
        {
            var user = new IdentityUser {
                UserName = creds.Login
            };

            using var scope = _scope.CreateScope();
            var userManager = scope.ServiceProvider.GetService <UserManager <IdentityUser> >();
            var roleManager = scope.ServiceProvider.GetService <RoleManager <IdentityRole> >();

            using var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            await ExecuteOrThrowAsync(userManager.CreateAsync(user, creds.Password)).ConfigureAwait(false);
            await ExecuteOrThrowAsync(CreateRolesIdempotentAsync(roleManager, roles.Select(Convert))).ConfigureAwait(false);
            await ExecuteOrThrowAsync(userManager.AddToRolesAsync(user, roles.Select(Convert))).ConfigureAwait(false);

            tran.Complete();
        }
Example #25
0
        public static void Main(string[] args)
        {
            // input credentials if used, different systems use different auth systems this however is the most common (passing 'auth' event with your credentials)
            var creds = new Creds
            {
                apiKey    = "your apikey if used",
                apiSecret = "your api secret if used"
            };

            // setup our options
            var opts = new PureSocketClusterOptions
            {
                Creds = creds,                                            // set our credentials
                MyReconnectStrategy = new ReconnectStrategy(4000, 60000), // how to handle reconnects
                //Serializer = new NewtonsoftSerializer(), // the default serializer is UTF8JSON, if you have issues or want to use your own you can do so
                DebugMode = true                                          // turn on debug mode to see detailed output
            };

            // initialize the client
            _scc = new PureSocketClusterSocket("wss://yoursocketclusterserver.com/socketcluster/", opts);

            // hook up to some events
            _scc.OnOpened       += Scc_OnOpened;
            _scc.OnMessage      += _scc_OnMessage;
            _scc.OnStateChanged += _scc_OnStateChanged;
            _scc.OnSendFailed   += _scc_OnSendFailed;
            _scc.OnError        += _scc_OnError;
            _scc.OnClosed       += _scc_OnClosed;
            _scc.OnData         += _scc_OnData;
            _scc.OnFatality     += _scc_OnFatality;
            _scc.Connect();

            // subscribe to some channels
            var cn = _scc.CreateChannel("TRADE-PLNX--BTC--ETC").Subscribe();

            cn.OnMessage(TradeData);
            var cn0 = _scc.CreateChannel("TRADE-PLNX--BTC--ETH").Subscribe();

            cn0.OnMessage(TradeData);
            var cn1 = _scc.CreateChannel("TRADE-GDAX--BTC--USD").Subscribe();

            cn1.OnMessage(TradeData);

            Console.ReadLine();
        }
Example #26
0
    public void Activate(Creds creds)
    {
        if(guarded) return;

        if (creds.Level < Level)
        {
            if (creds.Owner != null && creds.Owner.CompareTag("Guard")) creds.Owner.SendMessage("Interrupt");
            return;
        }
        guarded = creds.Owner != null && creds.Owner.CompareTag("Guard");

        Open = !Open || guarded;

        if (guarded)
            StartCoroutine(Unguard());
        else
            GameObject.FindGameObjectWithTag("Player").GetComponent<AudioSource>().PlayOneShot(GetComponent<Networkable>().ActivateClip);
    }
Example #27
0
        private static IEnumerable <Claim> GetTokenClaims(Creds user)
        {
            string privileges;

            if (user.Privilege == 1)
            {
                privileges = "ADMIN";
            }
            else
            {
                privileges = "USER";
            }

            return(new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, user.Client),
                new Claim("prv", privileges),
            });
        }
        public static RestRequest CreateNewRestletRequest(string jsonRequest, string restletUrl, string restletName)
        {
            string token;
            string tokenSecret;
            string consumerKey;
            string consumerSecret;

            if (restletName == "CreateCustomer")
            {
                token          = tokenIDCreateCustomer;
                tokenSecret    = tokenSecretCreateCustomer;
                consumerKey    = consumerKeyCreateCustomer;
                consumerSecret = consumerSecretCreateCustomer;
            }
            else
            {
                token          = tokenIDOrderImporter;
                tokenSecret    = tokenSecretOrderImporter;
                consumerKey    = consumerKeyOrderImporter;
                consumerSecret = consumerSecretOrderImporter;
            }

            Creds creds = new Creds(
                token,
                tokenSecret,
                consumerKey,
                consumerSecret,
                netsuiteAccount
                );

            var request = new RestRequest(Method.POST);

            string authHeader = OAuthBase.GenerateAuthorizationHeader(restletUrl, "POST", creds);

            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", authHeader);
            request.AddParameter("application/json; charset=utf-8", jsonRequest, ParameterType.RequestBody);

            return(request);
        }
Example #29
0
        private Creds SetCredentials(SavedCredentials toUpdate, bool canCancel = true)
        {
            Creds newCreds = InputCredentials(toUpdate.ToString(), canCancel);

            if (newCreds == null || newCreds.Username == null || newCreds.Password == null)
            {
                logger.Warn("Credentials contains a null value. Not set");
                return(null);
            }
            switch (toUpdate)
            {
            case SavedCredentials.BetFair:
                bfApi.LoginDetails = newCreds;
                break;

            case SavedCredentials.DynamicOdds:
                dynOdds.LoginDetails = newCreds;
                break;
            }
            SaveCredentials();
            return(newCreds);
        }
Example #30
0
        public async Task <LoginResult> SingInAsync(Creds creds)
        {
            using var scope = _scope.CreateScope();
            var signInManager = scope.ServiceProvider.GetService <SignInManager <IdentityUser> >();
            var userManager   = scope.ServiceProvider.GetService <UserManager <IdentityUser> >();
            var user          = await userManager.FindByNameAsync(creds.Login).ConfigureAwait(false);

            var result = await signInManager.PasswordSignInAsync(user, creds.Password, false, false).ConfigureAwait(false);

            if (!result.Succeeded)
            {
                return(new LoginResult {
                    Succeeded = false
                });
            }

            var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);

            return(new LoginResult {
                Succeeded = true, Roles = roles.Select(Convert).ToArray()
            });
        }
Example #31
0
        public IActionResult Auth([FromBody] Creds cred, [FromHeader] string options)
        {
            string value = Request.Headers["Authorization"];

            if (value != "{'firstName':'John', 'lastName':'Doe'}")
            {
                _logger.LogError("invalid auht token");
                return(BadRequest("Invali auth token"));
            }
            else
            {
                if (!cred.IsEmployee)
                {
                    if (_context.Authenticate(cred) != null)
                    {
                        _logger.LogInformation("Customer authenticated");
                        return(Ok(_context.Authenticate(cred)));
                    }
                    else
                    {
                        _logger.LogWarning("invalid logg inn attempt");
                        return(BadRequest("invalid credentials"));
                    }
                }
                else
                {
                    if (_context.AuthenticateEmployee(cred) != null)
                    {
                        _logger.LogInformation("Employee authenticated");
                        return(Ok(_context.AuthenticateEmployee(cred)));
                    }
                    else
                    {
                        _logger.LogWarning("invalid logg inn attempt");
                        return(BadRequest("invalid credentials"));
                    }
                }
            }
        }
Example #32
0
 public void Activate(Creds creds)
 {
     if (!Hacked)
     {
         if (_origin.Level <= creds.Level)
         {
             if (Alarm(_origin.transform))
             {
                 Hacked = true;
                 GameObject.FindGameObjectWithTag("Player").GetComponent <AudioSource>().PlayOneShot(_origin.HackClip, 0.2f);
             }
             else
             {
                 Alert();
             }
         }
     }
     else
     {
         _origin.SendMessage("Activate", creds);
     }
 }
Example #33
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                                  p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });
            services.AddMvc();

            // works with VCAP_SERVICES JSON value added to vcap-local.json when running locally,
            // and works with actual VCAP_SERVICES env var based on configuration set above when running in CF
            var creds = new Creds()
            {
                username = Configuration["cloudantNoSQLDB:0:credentials:username"],
                password = Configuration["cloudantNoSQLDB:0:credentials:password"],
                host     = Configuration["cloudantNoSQLDB:0:credentials:host"]
            };

            services.AddSingleton(typeof(Creds), creds);
            services.AddTransient <ICloudantService, CloudantService>();
            services.AddTransient <IServiceRepository, CloudantServiceRepository>();
            services.AddTransient <IServiceManager, ServiceManager>();
        }