private NtToken GetSessionToken(TokenAccessRights desired_access, int session_id)
        {
            if (!NtToken.EnableEffectivePrivilege(TokenPrivilegeValue.SeTcbPrivilege))
            {
                WriteWarning("Getting session token requires SeTcbPrivilege");
            }

            if (session_id < 0)
            {
                session_id = NtProcess.Current.SessionId;
            }
            using (var token = TokenUtils.GetSessionToken(session_id))
            {
                if (desired_access == TokenAccessRights.MaximumAllowed)
                {
                    return(token.Duplicate());
                }
                return(token.Duplicate(desired_access));
            }
        }
Example #2
0
        protected List <Token> TextUniteFilter(List <Token> lexes)
        {
            var twoTextsPattern = TokenSequencePatternBuilder
                                  .Reset()
                                  .Then(TokenType.TEXT)
                                  .Then(TokenType.TEXT)
                                  .Build();
            var textsPatternResult = twoTextsPattern.GetMatch(lexes);

            while (textsPatternResult.IsFullMatch)
            {
                var textLexes = lexes.GetRange(textsPatternResult.Start, textsPatternResult.Length);
                lexes.RemoveRange(textsPatternResult.Start, textsPatternResult.Length);
                var text       = TokenUtils.TokensToString(textLexes);
                var newTextLex = new Token(TokenType.TEXT, text);
                lexes.Insert(textsPatternResult.Start, newTextLex);
                textsPatternResult = twoTextsPattern.GetMatch(lexes, textsPatternResult.Start);
            }

            return(lexes);
        }
        public ActionResult Login([FromHeader] string username, [FromHeader] string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return(BadRequest("Unable to log in."));
            }

            var user = _context.Users.Where(u => u.Username == username).FirstOrDefault();

            if (user != null)
            {
                string hashedFromUserPass = Convert.ToBase64String(HashUtils.HashWithSuppliedSalt(password, user.Salt));
                if (hashedFromUserPass.Equals(Convert.ToBase64String(user.Password)))
                {
                    HttpContext.Response.Headers.Append("Authorization", TokenUtils.GenerateToken(user));
                    return(Ok("login successful"));
                }
            }

            return(BadRequest("Unable to authenticate the request"));
        }
        private NtToken CreateLowBoxToken(NtToken token)
        {
            Sid package_sid = TokenUtils.GetPackageSidFromName(textBoxPackageSid.Text);

            if (!NtSecurity.IsPackageSid(package_sid))
            {
                throw new ArgumentException(String.Format("Invalid Package Sid {0}", package_sid));
            }

            Sid[] capabilities = GetGroupFromList(listViewCapabilities.Items.OfType <ListViewItem>());
            foreach (Sid cap in capabilities)
            {
                if (!NtSecurity.IsCapabilitySid(cap))
                {
                    throw new ArgumentException(String.Format("Invalid Capability Sid {0}", cap));
                }
            }

            return(token.CreateLowBoxToken(package_sid, capabilities,
                                           new NtObject[0], TokenAccessRights.MaximumAllowed));
        }
        public async Task <IActionResult> AddChannel(
            Guid?id, string token, AddChannelModel model)
        {
            if (id == null)
            {
                return(BadRequest());
            }
            if (token == null)
            {
                return(BadRequest());
            }

            var list = await _listService.GetListAsync(id.Value);

            if (list == null)
            {
                return(BadRequest());
            }
            if (TokenUtils.NotEqual(token, list.TokenString))
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var channel = await _channelService.GetOrCreateChannelAsync(model.Url);

            if (channel == null)
            {
                ModelState.AddModelError("Url", "Cannot find channel on YouTube.");
                return(View(model));
            }

            await _listService.AddChannelAsync(list.Id, channel.Id);

            return(RedirectToAction("Index"));
        }
Example #6
0
        public async Task <IActionResult> OpenAccount([FromHeader] string Authorization, [FromHeader] string accountNickname, [FromHeader] string type)
        {
            try {
                //TODO middleware/filter would be better
                if (TokenUtils.IsValidFormatTokenString(Authorization) && TokenUtils.ValidateToken(Authorization, out SecurityToken token) && !_tokenService.IsTokenBlackListed(token))
                {
                    int         id   = TokenUtils.GetUserIDFromToken(Authorization, token);
                    Models.User user = _userService.GetById(id);

                    if (user != null && ValidationUtils.IsMatch(Settings.AccountNameCriterion, accountNickname, Settings.AccountNameMinLength, Settings.AccountNameMaxLength))
                    {
                        AccountType   accountType          = (AccountType)Enum.Parse(typeof(AccountType), type, true);
                        AccountHolder primaryAccountHolder = new AccountHolder()
                        {
                            AccountHolderType = AccountHolderType.Primary,
                            Holder            = user
                        };
                        Account account = _accountService.OpenAccount(primaryAccountHolder, accountType, accountNickname);

                        // TODO move this to account service instead
                        _context.AccountHolders.Add(primaryAccountHolder);
                        _context.Accounts.Add(account);
                        _context.SaveChanges();

                        return(Ok(String.Format("New {0} account created with nickname {1}", accountType.ToString(), accountNickname)));
                    }
                    return(BadRequest("Cannot create account using account type and nickname supplied."));
                }
                else
                {
                    return(BadRequest("Unable to authorize account creation. Check credentials and try again."));
                }
            }

            catch (Exception ex) {
                // TODO put more informative exception message to log
                System.Console.WriteLine(ex.Message);
                return(BadRequest("A problem occurred. A new account was not created."));
            }
        }
Example #7
0
        private async Task Init(string token, TokenType type)
        {
            await _clientLogger.InfoAsync("Discord Manager Initialize....").ConfigureAwait(false);

            await LogManager.PrintVersion().ConfigureAwait(false);

            await _clientLogger.DebugAsync("Check Internet is Available").ConfigureAwait(false);

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new ManagerException(
                          "UnAvailable Internet Check Your Pc/Server Internet State");
            }

            await _clientLogger.DebugAsync("Check Token is Validated").ConfigureAwait(false);

            try
            {
                TokenUtils.ValidateToken(type, token);
            }
            catch (Exception e)
            {
                throw new ManagerException(
                          "Token is Invalid. The token must be Validated", e);
            }

            await _clientLogger.DebugAsync("Successfully Check Token").ConfigureAwait(false);

            await _clientLogger.DebugAsync("Register Events...").ConfigureAwait(false);

            RegisterEvents();

            await _clientLogger.DebugAsync("Successfully Register Events").ConfigureAwait(false);

            await Client.LoginAsync(type, token).ConfigureAwait(false);

            await Client.StartAsync().ConfigureAwait(false);

            await Task.Delay(-1);
        }
        public async Task <ContentResult> Post(string jsonstring, string profileID)
        {
            if (profileID != "signin")
            {
                ContentResult badReq = new ContentResult();
                badReq.StatusCode = 400;
                return(badReq);
            }

            var          httprequest = Request.Body;
            StreamReader sr          = new StreamReader(httprequest);
            var          request     = JsonConvert.DeserializeObject <SigninRequest>(await sr.ReadToEndAsync());

            var playerid = request.sessionTicket.Split("-")[0];

            var response = new SigninResponse.ResponseTemplate()
            {
                result = new SigninResponse.Result()
                {
                    AuthenticationToken = playerid,
                    BasePath            = "/1",
                    Tokens           = TokenUtils.GetSigninTokens(playerid),
                    ClientProperties = new object(),
                    Updates          = new Updates()
                },
                updates = new Updates()
            };

            var resp = JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            Log.Information($"[{playerid}]: Logged in.");

            return(Content(resp, "application/json"));
            //return Content(
            //    "{\"result\":{\"authenticationToken\":\"" + playerid + "\",\"tokens\":{\"9b0acea5-8eaf-4ccc-8f8d-187784dc5544\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"605dc84c-f6d1-442b-8901-69b7b89a0cc8\"}},\"c025a117-de76-49c8-924a-9c56986d7a98\":{\"lifetime\":\"Persistent\",\"clientType\":\"ftue.context.pickup_mobs\",\"clientProperties\":{}},\"89e11f11-2582-47da-968d-764db91c7bd7\":{\"lifetime\":\"Persistent\",\"clientType\":\"ftue.context.build_with_friends.intro\",\"clientProperties\":{}},\"fc3028b9-36bf-473f-87ab-598ddc3d468f\":{\"lifetime\":\"Persistent\",\"clientType\":\"ftue.context.build_with_friends.menu\",\"clientProperties\":{}},\"80c106d4-3f80-4f42-8f1c-211278b1c2ef\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"9a2bd5aa-015d-419b-9c3a-d80dde87e312\"}},\"21dabe32-6d4e-4954-ab0d-8a21f5e51665\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.notification\",\"clientProperties\":{\"seasonId\":\"9a2bd5aa-015d-419b-9c3a-d80dde87e312\"}},\"7b6ecfe4-ad61-4353-af7b-cd005f0e3d1e\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"2ba1bbef-fc22-42e5-b1af-81f00c130a5b\"}},\"e74024fd-6c40-42b6-ba84-1a315e1f5982\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"cc456b52-1586-4e75-b7e9-aa811f609567\"}},\"a33fd95f-f567-4c53-ae6e-4fad94975e80\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"2bf15fa5-50ed-41ce-a2c4-b870028ed991\"}},\"b730a241-3966-4731-96c4-25387493f9d2\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"98749e7b-6a14-4fac-a851-3a68511c3f77\"}},\"e23a3f79-6362-4fff-8d10-636ab4052d10\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"07f1e716-b1d5-49df-ac81-fb8ce184746e\"}},\"4fbcb172-c215-482e-870b-6d3288a42cfb\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"ba777233-973b-4536-96e9-3e8abb3ae10a\"}},\"d702f10e-d616-444a-bf4b-3e2b9cbe3d07\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"5686ddbd-3da4-46da-a719-8e95e486cdb4\"}},\"9e9addd7-812e-4135-8edc-1155bf712240\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{}},\"39a32e0f-f19d-442a-9ae3-26785dd4b14a\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"3064a2c5-e5f6-44ed-9561-7e972e1c1410\"}},\"54b85e5d-1485-432f-929e-3845edb1e301\":{\"lifetime\":\"Persistent\",\"clientType\":\"empty.bucket.returned\",\"clientProperties\":{}},\"ab21c03d-18c0-441a-b78a-79fa429391d8\":{\"lifetime\":\"Persistent\",\"clientType\":\"ftue.context.adventures\",\"clientProperties\":{},\"rewards\":{\"inventory\":[],\"buildplates\":[],\"challenges\":[],\"personaItems\":[],\"utilityBlocks\":[]}},\"98c38d85-525e-4edf-849a-58ff68219c37\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"fe8a85b4-7b73-4182-8e46-adb894811f32\"}},\"3a99af70-bbf3-4041-8094-491bed0c3845\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.notification\",\"clientProperties\":{\"seasonId\":\"fe8a85b4-7b73-4182-8e46-adb894811f32\"}},\"af694f0c-b448-44a2-9d73-b2cc5e74b271\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"4c5bd76e-d57a-4ede-9193-eff0c12a6f8b\"}},\"878e2acc-238f-4bd3-870e-ebba2d374c68\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.welcome\",\"clientProperties\":{\"seasonId\":\"3604cd1b-dc4b-4e69-bf8f-8774c81caa74\"}},\"d5f19783-57ee-4bf9-883b-736680e9237f\":{\"lifetime\":\"Persistent\",\"clientType\":\"seasons.notification\",\"clientProperties\":{\"seasonId\":\"3604cd1b-dc4b-4e69-bf8f-8774c81caa74\"}}},\"updates\":{},\"basePath\":\"/1\",\"mrToken\":null,\"mixedReality\":null,\"streams\":null,\"clientProperties\":{}},\"expiration\":null,\"continuationToken\":null,\"updates\":{}}",
            //    "application/json");
        }
        private NtToken GetLowBoxToken(NtToken token)
        {
            Sid package_sid = TokenUtils.GetPackageSidFromName(PackageSid);

            if (!NtSecurity.IsPackageSid(package_sid))
            {
                throw new ArgumentException($"Invalid Package Sid {package_sid}");
            }

            if (!string.IsNullOrEmpty(RestrictedPackageName))
            {
                package_sid = TokenUtils.DeriveRestrictedPackageSidFromSid(package_sid, RestrictedPackageName);
            }

            if (AppContainer)
            {
                return(TokenUtils.CreateAppContainerToken(token, package_sid, GetCapabilitySids()));
            }

            return(token.CreateLowBoxToken(package_sid, GetCapabilitySids(),
                                           Handle ?? new NtObject[0], TokenAccessRights.MaximumAllowed));
        }
        public async Task <IActionResult> Delete(
            [FromQuery(Name = "id")] int id,
            [FromQuery(Name = "token")] string token)
        {
            ModelResult <Article> result = TokenUtils.CheckToken <Article>(token, _context);

            if (result != null)
            {
                return(BadRequest(result));
            }

            Article articleResult = await _context.Articles
                                    .FirstOrDefaultAsync(a => a.ArticleId == id);

            if (articleResult == null)
            {
                result = new ModelResult <Article>(405, null, "Article Not Exists");
                return(BadRequest(result));
            }

            User userResult = await _context.Users
                              .FirstOrDefaultAsync(u => u.UserId == articleResult.UserId);

            Session sessionResult = await _context.Sessions
                                    .FirstOrDefaultAsync(s => s.SessionToken == token);

            if (userResult == null ||
                userResult.UserId != sessionResult.SessionUserId)
            {
                result = new ModelResult <Article>(405, null, "User Not Exists or Token not suit");
                return(BadRequest(result));
            }

            _context.Articles.Remove(articleResult);
            await _context.SaveChangesAsync();

            result = new ModelResult <Article>(200, articleResult, "Article Deleted");
            return(Ok(result));
        }
Example #11
0
        static void Main(string[] args)
        {
            string[] testargs = new string[] {
                @"-m C:\AnswerFile\MACHINE_ANSWER_FILE_MI.xml",
                @"-t C:\Integration\Framework2.0\Framework\Trunk\Integration.MassImport\Integration.MassImport.exe.config.template",
                @"-o C:\Integration\Framework2.0\Framework\Trunk\Integration.MassImport\Integration.MassImport.exe.config"
            };

            //Uncomment for testing
            //args = testargs;

            if (args.Length < 3)
            {
                Console.WriteLine(usage);
                Environment.Exit(1);
            }
            Arguments arguments = new Arguments();
            Parser    p         = ParserFactory.BuildParser(arguments);

            p.OptStyle = OptStyle.Unix;
            // Parse the args
            p.Parse(args);
            try
            {
                List <string> tokensNotInAnswerFile = new List <string>();
                TokenUtils.ReplaceTokens(arguments.MachineAnswerFile, arguments.TemplateFile, arguments.OutputFile, out tokensNotInAnswerFile);
                Console.WriteLine("Token replacement completed successfully.\r\nAnswer file: {0}\r\nTemplate file: {1}\r\nOutput file: {2}",
                                  arguments.MachineAnswerFile, arguments.TemplateFile, arguments.OutputFile);
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                string message = string.Format("An error occurred while performing the token replacement.Please check the below information to fix the error.\r\n\r\n1) Answer file: {0}\r\n2)  Template file: {1}\r\n3)  Output file: {2}\r\n4)  Error message: {3}",
                                               arguments.MachineAnswerFile, arguments.TemplateFile, arguments.OutputFile, ex.Message);
                Console.WriteLine(message);
                Console.WriteLine(ex.StackTrace);
                Environment.Exit(1);
            }
        }
Example #12
0
        public async Task <string> CreateTokenAsync(Token token)
        {
            var newToken = TokenUtils.GenerateToken();

            var result = await _command.Execute(new InsertAuthRecordRequest
            {
                AuthRecord = new Domain.AuthRecord
                {
                    AccessToken  = newToken,
                    ClientId     = token.ClientId,
                    CreatedAt    = token.CreationTime,
                    ExpiresIn    = token.Lifetime,
                    GatewayId    = token.SubjectId,
                    IsPrivileged = false, //TODO: I don't know where this comes from
                    Scope        = token.Claims.First(c => c.Type == JwtClaimTypes.Scope).Value,
                    RefreshToken = TokenUtils.GenerateToken(),
                    //RefreshedAt = null
                }
            });

            return(newToken);
        }
        public async Task <AuthenticationResult> RegisterAsync(string email, string password)
        {
            var existingUser = await _userManager.FindByEmailAsync(email);

            if (existingUser != null)
            {
                return(new AuthenticationResult
                {
                    Errors = new[] { "User with this email already exists" }
                });
            }

            var newUserId = Guid.NewGuid();
            var newUser   = new IdentityUser
            {
                Id       = newUserId.ToString(),
                Email    = email,
                UserName = email
            };

            var createdUser = await _userManager.CreateAsync(newUser, password);

            if (!createdUser.Succeeded)
            {
                return(new AuthenticationResult
                {
                    Errors = createdUser.Errors.Select(x => x.Description)
                });
            }

            // Add autorização do usuário registrado acessar o endpoint de tags
            // await _userManager.AddClaimAsync(newUser, new Claim("tags.view", "true"));

            await _userManager.AddToRoleAsync(newUser, "Admin");

            return(await TokenUtils.GenerateAuthenticationResultForUserAsync(
                       newUser, _jwtSettings, _userManager, _context));
        }
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!await _userService.ValidateCredentials(model.Username, model.Password, out var user))
            {
                return(BadRequest());
            }

            var claims = new List <Claim>
            {
                new (ClaimTypes.NameIdentifier, model.Username),
                new ("name", model.Username),
                new (I18nClaimTypes.Admin, "")
            };

            var authUser = TokenUtils.BuildUserAuthObject(user, claims);

            return(Ok(authUser));
        }
Example #15
0
 //刷新令牌信息
 private void RefreshToken(string token)
 {
     try
     {
         //加载用户头像
         var cancellationTokenSource = new CancellationTokenSource();
         cancellationTokenSource.CancelAfter(5 * 1000);
         HttpMultipartFormDataContent form = new HttpMultipartFormDataContent
         {
             { new HttpStringContent(token), "token" }
         };
         HttpClient httpClient = new HttpClient();
         var        response   = httpClient.PostAsync(new Uri("https://www.gdeiassistant.cn/rest/token/refresh"), form)
                                 .AsTask(cancellationTokenSource.Token).Result;
         if (response.IsSuccessStatusCode)
         {
             //反序列化并解析JSON结果信息
             var data   = response.Content.ReadAsStringAsync().GetResults();
             var result = new DataContractJsonSerializer(typeof(DataJsonResult <RefreshTokenResult>))
                          .ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(data))) as DataJsonResult <RefreshTokenResult>;
             if (result.success)
             {
                 var username = TokenUtils.ParseTokenUsername(accessToken);
                 //保存新的令牌信息到凭据保险箱中
                 TokenUtils.SaveAccessTokenCredential(username, result.data.accessToken);
                 TokenUtils.SaveRefreshTokenCredential(username, result.data.refreshToken);
                 //缓存令牌和用户信息到应用中
                 this.accessToken  = result.data.accessToken.signature;
                 this.refreshToken = result.data.refreshToken.signature;
                 this.username     = username;
             }
         }
     }
     catch (Exception)
     {
     }
 }
        public async Task <AuthenticationResult> RegisterAsync(Author author)
        {
            var existingAuthor = await _unitOfWork.Authors
                                 .FindByConditionAsync(a => a.Email == author.Email)
                                 .Result.SingleOrDefaultAsync();

            if (existingAuthor != null)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "Author with this email already exists" }
                });
            }

            string salt           = SecurePasswordHasher.CreateSalt(8);
            string hashedPassword = SecurePasswordHasher.GenerateHash(author.Password, salt);

            author.Id       = Guid.NewGuid();
            author.Password = hashedPassword;
            author.Salt     = salt;

            await _unitOfWork.Authors.CreateAuthorAsync(author);

            var createdAuthor = await _unitOfWork.Commit();

            if (createdAuthor <= 0)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "An error occurred when try inserted new author" }
                });
            }

            return(await TokenUtils.GenerateAuthenticationResultForUserAsync(author, _jwtOptions));
        }
        public async Task <IActionResult> SignUp([FromBody] User user)
        {
            if (user == null || !ModelState.IsValid)
            {
                return(BadRequest(new ErrorModel <Object>(ProjectCodes.Form_Generic_Error)));
            }

            var userData = await _userRepository.GetUser(user.Email);

            if (userData != null)
            {
                return(BadRequest(new ErrorModel <User>(ProjectCodes.User_Already_Present, userData)));
            }

            try {
                userData = await _userRepository.CreateUser(user);

                return(Ok(new { User = userData, Token = TokenUtils.GetNewUserToken(userData.Email, userData.Password) }));
            }
            catch (Exception exception) {
                Console.WriteLine(exception.ToString());
                return(BadRequest());
            }
        }
Example #18
0
        public async Task <IActionResult> Get(int id, [FromQuery(Name = "token")] string token)
        {
            ModelResult <UserFollowInfo> result = TokenUtils.CheckToken <UserFollowInfo>(token, _context);

            if (result != null)
            {
                return(BadRequest(result));
            }

            Session sessionResult = await _context.Sessions
                                    .FirstOrDefaultAsync(s => s.SessionToken == token);

            UserFollow userFollowResult = await _context.UserFollows
                                          .FirstOrDefaultAsync(uf => uf.FollowingId == id &&
                                                               uf.FollowerId == sessionResult.SessionUserId);

            return(Ok(
                       new
            {
                status = 200,
                isFollowing = (userFollowResult != null)
            }
                       ));
        }
Example #19
0
        public void Update(Cluster cluster)
        {
            int     markerId;
            Vector2 newPostion;

            foreach (KeyValuePair <int, TouchInput> entry in cluster.Points)
            {
                markerId   = entry.Key;
                newPostion = entry.Value.Position;

                this.markers[markerId].UpdatePosition(newPostion);
            }

            UpdateMarkersTypeList();
            UpdateTokenAxis();
            UpdateAngle();
            UpdatePosition();

            TokenMarker[] meanSquaredTokenReferenceSystemOptimized = TokenUtils.MeanSquareOrthogonalReferenceSystemOptimized(typeMarkers[MarkerType.Origin],
                                                                                                                             typeMarkers[MarkerType.XAxis],
                                                                                                                             typeMarkers[MarkerType.YAxis],
                                                                                                                             TokenManager.CurrentTokenType.DistanceOriginAxisMarkersPX);
            SetMeanSquareReferenceSystem(meanSquaredTokenReferenceSystemOptimized);
        }
        protected ParseRule.ParseRuleDelegate GetElseParseFunc(TokenPattern pattern)
        {
            return((tokens, matchResult) =>
            {
                if (matchResult.MatchesCount == 2)
                {
                    var blockMatch = matchResult.GetMatch(1);
                    if (matchResult.IsFullMatch)
                    {
                        var blockTokens = TokenUtils.GetMatchResultBlockTokens(tokens, blockMatch);
                        var childNodes = ParseBlock(blockTokens);

                        var newNode = new Node(NodeType.ELSE);
                        newNode.PrimaryChildNodes = childNodes;
                        return newNode;
                    }
                    else if (!blockMatch.IsFullMatch)
                    {
                        throw new ParseRuleException(pattern, tokens, matchResult.Start, NodeType.ELSE);
                    }
                }
                throw new ParseException(tokens, matchResult.Start, NodeType.ELSE);
            });
        }
Example #21
0
        public async Task <IActionResult> AddChannel(Guid?id, string token)
        {
            if (id == null)
            {
                return(NotFound());
            }
            if (token == null)
            {
                return(BadRequest());
            }

            var list = await _listService.GetListAsync(id.Value);

            if (list == null)
            {
                return(NotFound());
            }
            if (TokenUtils.NotEqual(token, list.TokenString))
            {
                return(NotFound());
            }

            return(View(new AddChannelModel()));
        }
Example #22
0
        public async Task <IActionResult> Index(Guid?id, string token)
        {
            if (id == null)
            {
                return(BadRequest());
            }
            if (token == null)
            {
                return(BadRequest());
            }

            var listView = await _listService.GetListViewAsync(id.Value);

            if (listView == null)
            {
                return(NotFound());
            }
            if (TokenUtils.NotEqual(token, listView.Token))
            {
                return(NotFound());
            }

            return(View(listView));
        }
Example #23
0
        public async Task <IActionResult> SignIn(SignInModel model)
        {
            if (ModelState.IsValid)
            {
                User user;

                if (await _userService.ValidateCredentials(model.UserName, model.Password, out user))
                {
                    //Build Claims, get from database
                    var claims = new List <Claim>
                    {
                        //unique identifier for user
                        new Claim(ClaimTypes.NameIdentifier, model.UserName),
                        new Claim("name", model.UserName)
                    };

                    //build auth object
                    var authUser = TokenUtils.BuildUserAuthObject(user, claims);

                    return(Ok(authUser));
                }
            }
            return(BadRequest());
        }
Example #24
0
        protected List <Token> StringUniteFilter(List <Token> lexes)
        {
            var strStartPattern = AnyOfTokensPatternBuilder
                                  .Reset()
                                  .Or(TokenType.DOUBLE_QUOTE)
                                  .Or(TokenType.SINGLE_QUOTE)
                                  .Build();
            var strStartPatternResult = strStartPattern.GetMatch(lexes);

            while (strStartPatternResult.IsFullMatch)
            {
                var quoteType       = lexes[strStartPatternResult.Start].TokenType;
                var quotePattern    = new StartEndTokensPattern(quoteType, quoteType);
                var quotePatternRes = quotePattern.GetMatch(lexes, strStartPatternResult.Start);
                var textLexes       = lexes.GetRange(strStartPatternResult.Start + 1, quotePatternRes.Length - 2);
                lexes.RemoveRange(strStartPatternResult.Start, quotePatternRes.Length);
                var text       = TokenUtils.TokensToString(textLexes);
                var newTextLex = new Token(TokenType.TEXT, text);
                lexes.Insert(strStartPatternResult.Start, newTextLex);
                strStartPatternResult = strStartPattern.GetMatch(lexes, strStartPatternResult.Start);
            }

            return(lexes);
        }
        protected List <Token> ClassFilter(TokenPattern classDefPattern, List <Token> tokens)
        {
            var classDef = classDefPattern.GetMatch(tokens);

            while (classDef.IsPartMatch)
            {
                var classOperatorMatch = classDef.GetMatch(0);
                var classArgsMatch     = classDef.GetMatch(1);
                var codeBlockMatch     = classDef.GetMatch(2);
                if (codeBlockMatch.IsFullMatch)
                {
                    var classBlockLex = TokenUtils.GetMatchResultBlockTokens(tokens, codeBlockMatch);
                    tokens.RemoveRange(classDef.Start, classDef.Length);
                    tokens.InsertRange(classDef.Start, classBlockLex);
                    classDef = classDefPattern.GetMatch(tokens, classDef.End - 4);
                }
                else if (classOperatorMatch.IsFullMatch && (!classArgsMatch.IsFullMatch | classArgsMatch.IsFullMatch))
                {
                    throw new ParseRuleException(classDefPattern, tokens, classDef.Start);
                }
            }

            return(tokens);
        }
 private NtToken GetAnonymousToken(TokenAccessRights desired_access)
 {
     return(TokenUtils.GetAnonymousToken(desired_access));
 }
 private NtToken GetClipboardToken(TokenAccessRights desired_access)
 {
     return(TokenUtils.GetTokenFromClipboard(desired_access));
 }
        /// <summary>
        /// Process record.
        /// </summary>
        protected override void ProcessRecord()
        {
            Sid sid;

            switch (ParameterSetName)
            {
            case "sddl":
                sid = new Sid(Sddl);
                break;

            case "name":
                sid = NtSecurity.LookupAccountName(Name);
                break;

            case "service":
                sid = NtSecurity.GetServiceSid(ServiceName);
                break;

            case "il":
                sid = NtSecurity.GetIntegritySid(IntegrityLevel);
                break;

            case "il_raw":
                sid = NtSecurity.GetIntegritySidRaw(IntegrityLevelRaw);
                break;

            case "package":
                sid = TokenUtils.DerivePackageSidFromName(PackageName);
                if (RestrictedPackageName != null)
                {
                    sid = TokenUtils.DeriveRestrictedPackageSidFromSid(sid, RestrictedPackageName);
                }
                break;

            case "known":
                sid = KnownSids.GetKnownSid(KnownSid);
                break;

            case "token":
                using (NtToken token = NtToken.OpenProcessToken())
                {
                    if (PrimaryGroup)
                    {
                        sid = token.PrimaryGroup;
                    }
                    else if (Owner)
                    {
                        sid = token.Owner;
                    }
                    else if (LogonGroup)
                    {
                        sid = token.LogonSid.Sid;
                    }
                    else if (AppContainer)
                    {
                        sid = token.AppContainerSid;
                    }
                    else if (Label)
                    {
                        sid = token.IntegrityLevelSid.Sid;
                    }
                    else
                    {
                        sid = token.User.Sid;
                    }
                }
                break;

            case "cap":
                sid = CapabilityGroup ? NtSecurity.GetCapabilityGroupSid(CapabilityName)
                                    : NtSecurity.GetCapabilitySid(CapabilityName);
                break;

            case "sid":
                sid = new Sid(SecurityAuthority, RelativeIdentifiers);
                break;

            case "logon":
                sid = NtSecurity.GetLogonSessionSid();
                break;

            default:
                throw new ArgumentException("No SID type specified");
            }

            if (ToSddl)
            {
                WriteObject(sid.ToString());
            }
            else if (ToName)
            {
                WriteObject(sid.Name);
            }
            else
            {
                WriteObject(sid);
            }
        }
Example #29
0
 private void RecreateToken()
 {
     AppSettingsSerializer.Instance.AppSettings.DiscordBotToken = TokenUtils.GenerateDiscordToken();
     AppSettingsSerializer.Instance.SaveSettings();
     DiscordBotLogin();
 }
Example #30
0
 public DiscordHostConfigurationBuilder SetToken(string token)
 {
     TokenUtils.ValidateToken(TokenType.Bot, token);
     _token = token;
     return(this);
 }