예제 #1
0
 // Copy constructor
 public AuthenticationToken(AuthenticationToken at)
 {
     this.m_Token = at.m_Token;
     this.m_Username = at.m_Username;
     this.m_StartTime = at.m_StartTime;
     this.m_ExpireTime = at.m_ExpireTime;
     this.m_ExpirationPeriod = at.m_ExpirationPeriod;
 }
예제 #2
0
        /// <summary>
        /// Fetch a session key for a user
        /// </summary>
        public void GetSession(Authentication authentication, AuthenticationToken token)
        {
            var parameters = new SortedDictionary<string, string>();
            parameters.Add("token", token.Value);

            ApiHelper.AddRequiredParams(parameters, GetSessionMethodName, authentication);

            XPathNavigator navigator = RestApi.SendGetRequest(ApiHelper.LastFmWebServiceRootUrl, parameters);
            ApiHelper.CheckLastFmStatus(navigator);

            authentication.Session = GetSessionFromNavigator(navigator);
        }
예제 #3
0
 private void Page_Load(object sender, System.EventArgs e)
 {
     myService = new Service1();
     AuthenticationToken header = new AuthenticationToken();
     if (ViewState["AuthenticationTokenHeader"] != null)
     {
         header.InnerToken = (Guid)ViewState["AuthenticationTokenHeader"];
     }
     else
     {
         header.InnerToken = Guid.Empty;
     }
     myService.AuthenticationTokenValue = header;
 }
예제 #4
0
        public void AuthenticationToken()
        {
            var AuthenticationToken = new AuthenticationToken()
            {
                AccessToken = "NgCXRK...MzYjw",
                ExpiresOn = DateTime.Now.AddSeconds(3600),
                RefreshToken = "dfagC...fd43x",
                TokenType = "Bearer"
            };

            // get the user you just logged in with
            var user = SpotifyWebAPI.User.GetCurrentUserProfile(AuthenticationToken);

            // get this persons playlists
        }
예제 #5
0
        public void AddTokenCookie(string nameIdentifier, string key, string value)
        {
            lock (locker)
            {
                AuthenticationToken token;

                if(tokens.ContainsKey(nameIdentifier))
                {
                    token = tokens[nameIdentifier];
                }
                else
                {
                    token = new AuthenticationToken();
                    tokens.Add(nameIdentifier, token);
                }

                token.Cookies.Add(key, value);
            }
        }
예제 #6
0
 public void AddToAuthenticationTokens(AuthenticationToken authenticationToken)
 {
     base.AddObject("AuthenticationTokens", authenticationToken);
 }
예제 #7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public org.apache.shiro.authc.AuthenticationInfo beforeAllAttempts(java.util.Collection<? extends org.apache.shiro.realm.Realm> realms, org.apache.shiro.authc.AuthenticationToken token) throws org.apache.shiro.authc.AuthenticationException
        public override AuthenticationInfo BeforeAllAttempts <T1>(ICollection <T1> realms, AuthenticationToken token) where T1 : org.apache.shiro.realm.Realm
        {
            return(new ShiroAuthenticationInfo());
        }
 /// <summary>
 /// Constructor
 /// </summary>
 public ClientCredentials(AuthenticationToken token)
 {
     InternalContract.RequireNotNull(token, nameof(token));
     InternalContract.Require(token.Type == "Bearer", $"Parameter {nameof(token)} must be of type Bearer.");
     _token = token;
 }
예제 #9
0
 public AuthenticationResult(AuthenticationToken token, string description, int code)
 {
     Token       = token;
     Description = description;
     Code        = code;
 }
예제 #10
0
 /// <summary>
 /// BaseClient constructor
 /// </summary>
 /// <param name="baseUri"></param>
 /// <param name="authenticationToken"></param>
 protected BaseClient(string baseUri, AuthenticationToken authenticationToken)
 {
     RestClient = new RestClient(GetUriStart(baseUri), authenticationToken);
 }
예제 #11
0
 public string EncodeToken(AuthenticationToken token)
 => string.Create(32 /* length of N-format GUID */ + 64 /* Length of HMAC-SHA256 output */, token, this.CreateString);
예제 #12
0
 public JNClient(AuthenticationToken auth)
 {
     Token = auth;
 }
예제 #13
0
 public AuthenticationHeader(AuthenticationToken token)
 {
     m_Token = token;
 }
예제 #14
0
 public GoodReadsApiClient(AuthenticationToken authToken)
 {
     _authToken          = authToken;
     _client.BaseAddress = new Uri("https://www.goodreads.com/");
 }
예제 #15
0
 public AuthenticationTokenPostLogicValidationStrategy(AuthenticationToken authenticationToken)
 {
     _authenticationToken          = authenticationToken;
     _authenticationTokenValidator = new AuthenticationTokenValidator();
 }
예제 #16
0
 public static void MapAPIEndpoints(Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints)
 {
     endpoints.MapGet("/api/recipe/all/", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("page") ||
             !int.TryParse(context.Request.Query["page"].ToString(), out int page))
         {
             page = 0;
         }
         if (!context.Request.Query.ContainsKey("count") ||
             !int.TryParse(context.Request.Query["count"].ToString(), out int count))
         {
             count = 100;
         }
         RecipeAPI api = new RecipeAPI();
         await context.Response.WriteAsJsonAsync(api.GetAll(new AuthenticationToken(), page, count));
     });
     endpoints.MapGet("/api/recipe/", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("id") ||
             !long.TryParse(context.Request.Query["id"].ToString(), out long id))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not find a Recipe with that ID." });
         }
         else
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.GetOne(new AuthenticationToken(), id));
         }
     });
     endpoints.MapGet("/api/recipe/mine/", async(context) => {
         long id = 0;
         if ((!context.Request.Query.ContainsKey("name") && !context.Request.Query.ContainsKey("id")) ||
             (context.Request.Query.ContainsKey("name") && string.IsNullOrWhiteSpace(context.Request.Query["name"].ToString()) ||
              (context.Request.Query.ContainsKey("id") && !long.TryParse(context.Request.Query["id"].ToString(), out id))))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Either both no name and no id specified for that Cook, or one of the two wasn't readable." });
         }
         else
         {
             int page = 0, count = 100;
             if (context.Request.Query.ContainsKey("page") && !int.TryParse(context.Request.Query["page"].ToString(), out page) ||
                 (context.Request.Query.ContainsKey("count") && !int.TryParse(context.Request.Query["count"].ToString(), out count)) ||
                 (context.Request.Query.ContainsKey("page") && !context.Request.Query.ContainsKey("count")))
             {
                 await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Either couldn't read page or count requested, or page was requested and count (per page) wasn't." });
             }
             else
             {
                 AuthenticationToken tokenUser = new AuthenticationToken {
                     ApplicationWideId = id, ApplicationWideName = (context.Request.Query.ContainsKey("name")) ? context.Request.Query["name"].ToString() : ""
                 };
                 RecipeAPI api = new RecipeAPI();
                 await context.Response.WriteAsJsonAsync(api.GetMine(tokenUser, page, count));
             }
         }
     });
     endpoints.MapDelete("/api/recipe", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("id") ||
             !long.TryParse(context.Request.Query["id"].ToString(), out long id))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not find a Recipe with that ID." });
         }
         else
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.Delete(new AuthenticationToken(), id));
         }
     });
     endpoints.MapPost("/api/recipe", async(context) =>
     {
         Stream body   = context.Request.Body;
         Recipe recipe = null;
         if (body != null)
         {
             string bodyJsonString = await(new StreamReader(body)).ReadToEndAsync();
             recipe = JsonSerializer.Deserialize <Recipe>(bodyJsonString);
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Body of request must contain a Recipe in Json format." });
         }
         if (recipe != null)
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.Create(new AuthenticationToken(), recipe));
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Could not read a Recipe from the body of your request." });
         }
     });
     endpoints.MapPut("/api/recipe", async(context) => {
         Stream body   = context.Request.Body;
         Recipe recipe = null;
         if (body != null)
         {
             string bodyJsonString = await(new StreamReader(body)).ReadToEndAsync();
             recipe = JsonSerializer.Deserialize <Recipe>(bodyJsonString);
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Body of request must contain a Recipe in Json format." });
         }
         if (recipe != null)
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.Update(new AuthenticationToken(), recipe));
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Could not read a Recipe from the body of your request." });
         }
     });
 }
예제 #17
0
        public async Task <int> Create(AuthenticationToken user, Recipe newInfo)
        {
            using ApplicationDbContext context = new ApplicationDbContext();
            Recipe makeMe = newInfo;

            if (makeMe.RecipeIngredients != null && makeMe.RecipeIngredients.Count > 0)
            {
                List <RecipeIngredient> thisRecipesIngredients = makeMe.RecipeIngredients.ToList();
                for (int index = 0; index < thisRecipesIngredients.Count; index++)
                {
                    RecipeIngredient ri = thisRecipesIngredients[index];
                    Ingredient       maybeIExistInTheDatabase = await context.Ingredients.Where(i => ri.IngredientId == i.Id || (ri.Ingredient != null && ri.Ingredient.Name == i.Name)).FirstOrDefaultAsync <Ingredient>();

                    if (maybeIExistInTheDatabase != null)
                    {
                        ri.Ingredient   = null;
                        ri.IngredientId = maybeIExistInTheDatabase.Id;
                    }
                }
                makeMe.RecipeIngredients = RemoveDuplicateIngredients(thisRecipesIngredients);
            }

            if (makeMe.RecipeTags != null && makeMe.RecipeTags.Count > 0)
            {
                List <RecipeTag> thisRecipesTags = makeMe.RecipeTags.ToList();
                for (int index = 0; index < thisRecipesTags.Count; index++)
                {
                    RecipeTag rt = thisRecipesTags[index];
                    if (rt.Tag != null)
                    {
                        Tag maybeImATagInTheDatabase = await context.Tags.Where(t => rt.Tag.Text == t.Text || (rt.Tag.Id != null && t.Id == rt.Tag.Id)).FirstOrDefaultAsync <Tag>();

                        if (maybeImATagInTheDatabase != null)
                        {
                            rt.Tag   = null;
                            rt.TagId = maybeImATagInTheDatabase.Id;
                        }
                        else
                        {
                            context.Tags.Add(rt.Tag);
                            await context.SaveChangesAsync(); //Adding to the context and saving will give it an Id..

                            thisRecipesTags[index].TagId  = rt.Tag.Id;
                            thisRecipesTags[index].Tag.Id = rt.Tag.Id;
                            rt.Tag = null;
                        }
                    }
                    else if (rt.TagId != null)
                    {
                        Tag maybeImATagInTheDatabase = await context.Tags.SingleOrDefaultAsync <Tag>(t => rt.TagId == t.Id);

                        if (maybeImATagInTheDatabase == null)
                        {
                            throw new ApplicationException("Cannot find a Tag with that Id in the data.");
                        }
                    }
                    else
                    {
                        throw new ApplicationException("Tag specified, but neither Text nor Id were mentioned.");
                    }
                }
                makeMe.RecipeTags = RemoveDuplicateTags(thisRecipesTags);
            }
            context.Recipes.Add(makeMe);
            int numberCreated = await context.SaveChangesAsync();

            return(numberCreated);
        }
예제 #18
0
        public async Task <int> Update(AuthenticationToken user, Recipe updatedInfo)
        {
            using (ApplicationDbContext deletionContext = new ApplicationDbContext())
            {
                deletionContext.RemoveRange(deletionContext.RecipeIngredients.Where(ri => ri.RecipeId == updatedInfo.Id));
                deletionContext.RemoveRange(deletionContext.RecipeTags.Where(rt => rt.RecipeId == updatedInfo.Id));
                await deletionContext.SaveChangesAsync();
            }
            using ApplicationDbContext updateContext = new ApplicationDbContext();
            Recipe updateMe = await updateContext.Recipes.FirstOrDefaultAsync(a => a.Id == updatedInfo.Id);

            if (updateMe == null)
            {
                throw new ApplicationException("Could not find a Recipe with that Id.");
            }
            updateMe.CookId          = updatedInfo.CookId;
            updateMe.Name            = updatedInfo.Name ?? updateMe.Name ?? "";
            updateMe.Instructions    = updatedInfo.Instructions ?? updateMe.Instructions ?? "";
            updateMe.MainGraphicLink = updatedInfo.MainGraphicLink ?? updateMe.MainGraphicLink ?? "";
            if (updatedInfo.RecipeIngredients != null && updatedInfo.RecipeIngredients.Count > 0)
            {
                List <RecipeIngredient> thisRecipesIngredients = updatedInfo.RecipeIngredients.ToList();
                for (int index = 0; index < thisRecipesIngredients.Count; index++)
                {
                    RecipeIngredient ri = thisRecipesIngredients[index];
                    using (ApplicationDbContext ingredientTaggingContext = new ApplicationDbContext())
                    {
                        if (ri.Ingredient != null && ri.Ingredient.IngredientTags != null)
                        {
                            IEnumerator <IngredientTag> ite = ri.Ingredient.IngredientTags.GetEnumerator();
                            for (; ite.MoveNext();)
                            {
                                IngredientTag it = ite.Current;
                                if (ite.Current.CookId == null || ite.Current.CookId != updateMe.CookId)
                                {
                                    ite.Current.CookId = updateMe.CookId;
                                }
                                if (it.Tag != null)
                                {
                                    Tag maybeImATagInTheDatabase = await ingredientTaggingContext.Tags.Where(t => it.Tag.Text == t.Text || (it.Tag.Id != null && t.Id == it.Tag.Id)).FirstOrDefaultAsync <Tag>();

                                    if (maybeImATagInTheDatabase != null)
                                    {
                                        it.TagId = maybeImATagInTheDatabase.Id;
                                    }
                                    else
                                    {
                                        ingredientTaggingContext.Add(it.Tag);
                                        await ingredientTaggingContext.SaveChangesAsync();

                                        it.TagId          = it.Tag.Id;
                                        ite.Current.TagId = it.TagId;
                                    }
                                }
                            }
                        }
                    }
                    Ingredient maybeIExistInTheDatabase = await updateContext.Ingredients.Where(i => ri.IngredientId == i.Id || (ri.Ingredient != null && ri.Ingredient.Name == i.Name)).FirstOrDefaultAsync <Ingredient>();

                    if (maybeIExistInTheDatabase != null)
                    {
                        ri.Ingredient   = null;
                        ri.IngredientId = maybeIExistInTheDatabase.Id;
                    }
                }
                updateMe.RecipeIngredients = RemoveDuplicateIngredients(thisRecipesIngredients);
            }

            if (updatedInfo.RecipeTags != null && updatedInfo.RecipeTags.Count > 0)
            {
                List <RecipeTag> thisRecipesTags = updatedInfo.RecipeTags.ToList();
                for (int index = 0; index < thisRecipesTags.Count; index++)
                {
                    RecipeTag rt = thisRecipesTags[index];
                    if (rt.Tag != null)
                    {
                        Tag maybeImATagInTheDatabase = await updateContext.Tags.Where(t => rt.Tag.Text == t.Text || (rt.Tag.Id != null && t.Id == rt.Tag.Id)).FirstOrDefaultAsync <Tag>();

                        if (maybeImATagInTheDatabase != null)
                        {
                            rt.Tag   = null;
                            rt.TagId = maybeImATagInTheDatabase.Id;
                        }
                        else
                        {
                            updateContext.Tags.Add(rt.Tag);
                            await updateContext.SaveChangesAsync(); //Adding to the context and saving will give it an Id..

                            thisRecipesTags[index].TagId  = rt.Tag.Id;
                            thisRecipesTags[index].Tag.Id = rt.Tag.Id;
                            rt.Tag = null;
                        }
                    }
                    else if (rt.TagId != null)
                    {
                        Tag maybeImATagInTheDatabase = await updateContext.Tags.SingleOrDefaultAsync <Tag>(t => rt.TagId == t.Id);

                        if (maybeImATagInTheDatabase == null)
                        {
                            throw new ApplicationException("Cannot find a Tag with that Id in the data.");
                        }
                    }
                    else
                    {
                        throw new ApplicationException("Tag specified, but neither Text nor Id were mentioned.");
                    }
                }
                updateMe.RecipeTags = RemoveDuplicateTags(thisRecipesTags);
            }

            updateContext.Update(updateMe);
            return(await updateContext.SaveChangesAsync());
        }
 public ProjectRiskLevelHandler(AuthenticationToken authenticationToken, string accountID, EnvironmentType environmentType = EnvironmentType.Production, int itemsPerRequest = 100, int maximumRecursiveRequests = 50) :
     base($"{Common.GetBaseUrl(environmentType)}/v1/project_risk_levels", authenticationToken, accountID, itemsPerRequest, maximumRecursiveRequests)
 {
 }
예제 #20
0
 private bool TryAuthenticate(string username, string password, out AuthenticationToken token)
 {
     Log.Info("authenticating...");
     try
     {
         token = F1Timing.Live.Login(username, password);
         Log.InfoFormat("authenticated: {0}", username);
         return true;
     }
     catch(Exception exc)
     {
         Log.Error(exc);
         token = null;
         return false;
     }
 }
        /// <summary>
        /// Generates partner credentials using a user plus application Azure Active Directory token.
        /// </summary>
        /// <param name="clientId">The client id of the application in Azure Active Directory. This application should be an Azure native application.</param>
        /// <param name="authenticationToken">The Azure Active Directory token.</param>
        /// <param name="aadTokenRefresher">An optional delegate which will be called when the Azure Active Directory token
        /// expires and can no longer be used to generate the partner credentials. This delegate should return
        /// an up to date Azure Active Directory token.</param>
        /// <param name="requestContext">An optional request context.</param>
        /// <returns>The partner service credentials.</returns>
        public static async Task <IPartnerCredentials> GenerateByUserCredentialsAsync(string clientId, AuthenticationToken authenticationToken, TokenRefresher aadTokenRefresher = null, IRequestContext requestContext = null)
        {
            UserPartnerCredentials partnerCredentials = new UserPartnerCredentials(clientId, authenticationToken, aadTokenRefresher);

            await partnerCredentials.AuthenticateAsync(requestContext).ConfigureAwait(false);

            return(partnerCredentials);
        }
예제 #22
0
        /// <summary>
        /// Initialises a new instance of the <see cref="PlayLiveSessionResult"/> class.
        /// </summary>
        /// <param name="tmsPath">The user's <see cref="AuthenticationToken"/>.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="token"/> is <see langword="null"/>.
        /// </exception>
        public PlayLiveSessionResult(AuthenticationToken token)
        {
            Guard.NotNull(token, "token");

            Token = token;
        }
예제 #23
0
        public UserLoginResponse Login(UserLoginRequest userRequest)
        {
            UserLoginResponse userLoginResponse = new UserLoginResponse();

            userLoginResponse.IsSuccess = userLoginResponse.IsLoggedIn = false;
            userLoginResponse.Message   = "Login unsuccessful";
            try
            {
                if (userRequest != null)
                {
                    using (uow = new UnitOfWork())
                    {
                        if (!string.IsNullOrEmpty(userRequest.PasswordHash) && !string.IsNullOrEmpty(userRequest.UserNameOREmail))
                        {
                            //string PasswordHash = new Util().GetHashString(userRequest.PasswordHash);
                            string PasswordHash = userRequest.PasswordHash;
                            User   existUser    = existUser = uow.UserRepository.Get()
                                                              .Where(u => PasswordHash.Equals(u.Password) &&
                                                                     userRequest.UserNameOREmail.Equals(u.Username)
                                                                     ).FirstOrDefault();

                            if (existUser == null)
                            {
                                existUser = uow.UserRepository.Get()
                                            .Where(u => PasswordHash.Equals(u.Password) &&
                                                   userRequest.UserNameOREmail.Equals(u.Email, StringComparison.OrdinalIgnoreCase)
                                                   ).FirstOrDefault();
                            }

                            if (existUser != null)
                            {
                                #region Get Existing User

                                // If token exists then return existing token otherwise generate new one

                                AuthenticationToken existingToken = uow.AuthenticationTokenRepository.Get().
                                                                    Where(auth => auth.FkUserID.Equals(existUser.UserID))

                                                                    .FirstOrDefault();
                                string token;
                                if (existingToken != null)
                                {
                                    token = existingToken.Token;
                                }
                                else
                                {
                                    // Generate New Token and save
                                    AuthenticationToken authToken = new AuthenticationToken();
                                    authToken.FkUserID = existUser.UserID;
                                    token = authToken.Token = Guid.NewGuid().ToString().Replace("-", "");
                                    authToken.CreatedDate = System.DateTime.UtcNow;

                                    uow.AuthenticationTokenRepository.Insert(authToken);
                                    uow.Save();
                                }

                                #endregion

                                #region PrepareResponse

                                userLoginResponse.UserID     = existUser.UserID;
                                userLoginResponse.FullName   = existUser.Name;
                                userLoginResponse.PhoneNo    = existUser.PhoneNo;
                                userLoginResponse.Token      = token;
                                userLoginResponse.IsSuccess  = true;
                                userLoginResponse.IsLoggedIn = true;

                                userLoginResponse.Message = "Successfully Logged-in ";
                                UsersEL userEl = new UsersEL();
                                userEl.Active              = existUser.Active;
                                userEl.Address             = existUser.Address;
                                userEl.City                = existUser.City == null ? "" : existUser.City;
                                userEl.Country             = existUser.Country;
                                userEl.CreatedDate         = existUser.CreatedDate;
                                userEl.Email               = existUser.Email;
                                userEl.Name                = existUser.Name;
                                userEl.PhoneNo             = existUser.PhoneNo;
                                userEl.UserID              = existUser.UserID;
                                userEl.Username            = existUser.Username;
                                userEl.Zipcode             = existUser.Zipcode;
                                userEl.CreatedDate         = existUser.CreatedDate == null ? DateTime.Now : existUser.CreatedDate;
                                userEl.Password            = "";
                                userEl.ProfilePic          = "";
                                userEl.RoleID              = "2";
                                userEl.State               = "";
                                userEl.DeviceType          = existUser.DeviceType == null ? "" : existUser.DeviceType;
                                userEl.PushToken           = existUser.PushToken == null ? "" : existUser.PushToken;
                                userLoginResponse.userData = userEl;



                                #endregion
                            }
                            else
                            {
                                userLoginResponse.Message = "You are passing wrong credentials.";
                            }
                        }
                        else
                        {
                            userLoginResponse.Message = "Please pass value of all mandatory fields";
                        }
                    }
                }
            }
            catch
            {
                userLoginResponse.Message = "An error occurred while authentication";
            }

            return(userLoginResponse);
        }
예제 #24
0
        /// <summary>
        /// If this object has a Next page get it
        /// else
        /// throw new Exception("Next page does not exist.");
        /// </summary>
        /// <returns></returns>
        public async Task <Page <T> > GetNextPage <T>(Page <T> page, AuthenticationToken token)
        {
            _stopwatch.Reset();
            _stopwatch.Start();

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

            if (!page.HasNextPage)
            {
                throw new Exception("Next page does not exist.");
            }

            if (typeof(T) == typeof(Track))
            {
                var response = await _client.GetAsync(page.Next);

                _logger.LogInformation("Response for GetNextPage: " + response.StatusCode);

                var data = await response.Content.ReadAsStringAsync();

                var obj = JsonUtil.Deserialize <page <track> >(data);

                _stopwatch.Stop();
                _logger.LogInformation("GetNextPage: " + _stopwatch.Elapsed.Seconds + "(s)");

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(Playlist))
            {
                var response = await _client.GetAsync(page.Next);

                _logger.LogInformation("Response for GetNextPage: " + response.StatusCode);

                var obj = JsonUtil.Deserialize <page <playlist> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();
                _logger.LogInformation("GetNextPage: " + _stopwatch.Elapsed.Seconds + "(s)");

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(Artist))
            {
                var response = await _client.GetAsync(page.Next);

                _logger.LogInformation("Response for GetNextPage: " + response.StatusCode);

                var obj = JsonUtil.Deserialize <page <artist> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();
                _logger.LogInformation("GetNextPage: " + _stopwatch.Elapsed.Seconds + "(s)");

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(Album))
            {
                var response = await _client.GetAsync(page.Next);

                _logger.LogInformation("Response for GetNextPage: " + response.StatusCode);

                var obj = JsonUtil.Deserialize <page <album> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();
                _logger.LogInformation("GetNextPage: " + _stopwatch.Elapsed.Seconds + "(s)");

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(PlaylistTrack))
            {
                var response = await _client.GetAsync(page.Next);

                _logger.LogInformation("Response for GetNextPage: " + response.StatusCode);

                var data = await response.Content.ReadAsStringAsync();

                var obj = JsonUtil.Deserialize <page <playlisttrack> >(data);

                _stopwatch.Stop();
                _logger.LogInformation("GetNextPage: " + _stopwatch.Elapsed.Seconds + "(s)");

                return(obj.ToPOCO <T>());
            }

            return(null);
        }
예제 #25
0
        public bool ValidateToken(string tokenString, string userId, DateTimeOffset issuedAt, Guid guid, out AuthenticationToken token)
        {
            var issued = issuedAt.ToUnixTimeMilliseconds();

            token = default;
            if (tokenString.Length != 96)
            {
                return(false);
            }

            if (!tokenString.All(xc => (xc <= '9' && xc >= '0') || (xc >= 'a' && xc <= 'f')))
            {
                return(false);
            }

            var         stampString = tokenString.AsSpan(32, 64);
            var         stampDst    = this.ComputeHmac(guid, issued, userId);
            Span <byte> stampSrc    = stackalloc byte[stampDst.Length];

            for (var i = 0; i < stampString.Length; i += 2)
            {
                if (!byte.TryParse(stampString.Slice(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out stampSrc[i / 2]))
                {
                    return(false);
                }
            }

            if (stampSrc.SequenceEqual(stampDst))
            {
                token = new AuthenticationToken(userId, issuedAt, guid);
                return(true);
            }

            return(false);
        }
예제 #26
0
 private void OnGetWatsonToken(AuthenticationToken authenticationToken, string customData)
 {
     _authenticationToken = authenticationToken;
     Log.Debug("ExampleGetToken.OnGetToken()", "created: {0} | time to expiration: {1} minutes | token: {2}", _authenticationToken.Created, _authenticationToken.TimeUntilExpiration, _authenticationToken.Token);
     _receivedAuthToken = true;
 }
예제 #27
0
 //NLU AuthenticationToken
 private void OnGetToken(AuthenticationToken authenticationToken, string customData)
 {
     _nluAuthenticationToken = authenticationToken.ToString();
     //Log.Debug("ExampleGetToken.OnGetToken()", "created: {0} | time to expiration: {1} minutes | token: {2}", _authenticationToken.Created, _authenticationToken.TimeUntilExpiration, _authenticationToken.Token);
 }
예제 #28
0
 public PivotalTrackerClient(AuthenticationToken token) : this((string)token)
 {
 }
예제 #29
0
 private protected NegotiateAuthenticationToken(byte[] data, AuthenticationToken token, byte[] mic)
     : base(data)
 {
     Token = token;
     MessageIntegrityCode = mic;
 }
예제 #30
0
        public LoginModule(IDbFactory dbFactory) : base("Users")
        {
            Get["/login"] = parameters =>
            {
                var viewModel = GetViewModel <LoginViewModel>();
                // Called when the user visits the login page or is redirected here because
                // an attempt was made to access a restricted resource. It should return
                // the view that contains the login form

                return(View["Login.cshtml", viewModel]);
            };

            Get["/logout"] = parameters =>
            {
                //var viewModel = GetViewModel<LoginViewModel>();
                // Called when the user clicks the sign out button in the application. Should
                // perform one of the Logout actions (see below)
                return(this.LogoutAndRedirect("/"));
            };

            Post["/login"] = parameters =>
            {
                var viewModel = this.Bind <LoginViewModel>();
                // Called when the user submits the contents of the login form. Should
                // validate the user based on the posted form data, and perform one of the
                // Login actions (see below)

                var passwordHash = SHA256(viewModel.Password);
                viewModel.Password = string.Empty;

                try
                {
                    using (var db = dbFactory.Create())
                    {
                        var user = db.SingleOrDefault <User>("SELECT * FROM Users WHERE Username=@0", viewModel.Username);
                        if (user == null ||
                            user.PasswordHash != passwordHash)
                        {
                            ViewBag.ValidationError = "Username or password does not match.";
                            return(View["Login.cshtml", viewModel]);
                        }

                        var token = db.SingleOrDefault <AuthenticationToken>("SELECT * FROM AuthenticationTokens WHERE UserId=@0",
                                                                             user.Id);

                        if (token == null)
                        {
                            token = new AuthenticationToken
                            {
                                CreatedOn = DateTime.UtcNow,
                                UserId    = user.Id,
                                Id        = Guid.NewGuid().ToByteArray()
                            };
                            db.Insert(token);
                        }

                        return(this.LoginAndRedirect(new Guid(token.Id)));
                    }
                }
                catch (Exception e)
                {
                    ViewBag.ValidationError = e.Message;
                    return(View["Login.cshtml", viewModel]);
                }
            };
        }
예제 #31
0
        /// <summary>
        /// If this object has a Previous page get it
        /// else
        /// throw new Exception("Previous page does not exist.");
        /// </summary>
        /// <returns></returns>
        public async Task <Page <T> > GetPreviousPage <T>(Page <T> page, AuthenticationToken token)
        {
            _stopwatch.Reset();
            _stopwatch.Start();

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

            if (!page.HasPreviousPage)
            {
                throw new Exception("Previous page does not exist.");
            }

            if (typeof(T) == typeof(Track))
            {
                var response = await _client.GetAsync(page.Next);

                var obj = System.Text.Json.JsonSerializer.Deserialize <page <track> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(Playlist))
            {
                var response = await _client.GetAsync(page.Next);

                var obj = System.Text.Json.JsonSerializer.Deserialize <page <playlist> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(Artist))
            {
                var response = await _client.GetAsync(page.Next);

                var obj = System.Text.Json.JsonSerializer.Deserialize <page <artist> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(Album))
            {
                var response = await _client.GetAsync(page.Next);

                var obj = System.Text.Json.JsonSerializer.Deserialize <page <album> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();

                return(obj.ToPOCO <T>());
            }
            else if (typeof(T) == typeof(PlaylistTrack))
            {
                var response = await _client.GetAsync(page.Next);

                var obj = System.Text.Json.JsonSerializer.Deserialize <page <playlisttrack> >(await response.Content.ReadAsStringAsync());

                _stopwatch.Stop();

                return(obj.ToPOCO <T>());
            }

            return(null);
        }
예제 #32
0
 public static string Serialize(AuthenticationToken token)
 {
     if (token.Data is string strToken)
     {
         return new { r = token.Realm, d = strToken }
     }
        public void can_create()
        {
            var token = new AuthenticationToken("token");

            Assert.Equal("token", token.Token);
        }
예제 #34
0
 /// <summary>
 /// Creates a live message reader using the specified authentication
 /// <paramref name="token"/> and records the messages to the specified
 /// <paramref name="path"/>.
 /// </summary>
 /// <param name="token">The authentication token.</param>        
 /// <param name="path">The path to save the messages to.</param>
 /// <returns>A message reader which reads and records live messages.</returns>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown when <paramref name="token"/> or <paramref name="path"/> is
 /// <see langword="null"/>.
 /// </exception>
 /// <exception cref="System.ArgumentException">
 /// Thrown when <paramref name="path"/> is of zero length.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// Thrown when an IO error occurs whilst creating the output file or connecting to the
 /// live-timing message stream.
 /// </exception>
 public static IMessageReader ReadAndRecord(AuthenticationToken token, string path)
 {
     return new RecordingMessageReader(Read(token), path);
 }
예제 #35
0
 public static AuthenticationToken CreateAuthenticationToken(string claimedIdentifier, global::System.DateTime createdOnUtc, global::System.DateTime lastUsedUtc, int usageCount, int authenticationTokenId)
 {
     AuthenticationToken authenticationToken = new AuthenticationToken();
     authenticationToken.ClaimedIdentifier = claimedIdentifier;
     authenticationToken.CreatedOnUtc = createdOnUtc;
     authenticationToken.LastUsedUtc = lastUsedUtc;
     authenticationToken.UsageCount = usageCount;
     authenticationToken.AuthenticationTokenId = authenticationTokenId;
     return authenticationToken;
 }
예제 #36
0
        // Add a token for a login user
        public void AddToken(string token, string username)
        {
            lock (m_TokenDatabase)
            {
                AuthenticationToken newToken = new AuthenticationToken(token, username, DateTime.Now);
                m_TokenDatabase.Add(newToken);
#if DEBUG
              //  Console.WriteLine("Generate token: " + token + ", for user: "******" at time: " + DateTime.Now);
#endif
            }
        }
 private void OnGetToken(AuthenticationToken authenticationToken, string customData)
 {
     _authenticationToken = authenticationToken;
     Log.Debug("SpeechSynthesizer.OnGetToken()", "created: {0} | time to expiration: {1} minutes | token: {2}", _authenticationToken.Created, _authenticationToken.TimeUntilExpiration, _authenticationToken.Token);
 }
예제 #38
0
        public IActionResult GetToken(string username, string password)
        {
            ClaimsIdentity claimsIdentity = GetPerson(username, password);

            if (claimsIdentity != null)
            {
                DateTime         currentTime      = DateTime.Now;
                JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: AuthenticationToken.Issuer,
                                                                         AuthenticationToken.Audience,
                                                                         claimsIdentity.Claims,
                                                                         currentTime,
                                                                         currentTime.Add(TimeSpan.FromMinutes(AuthenticationToken.TTL)),
                                                                         new SigningCredentials(AuthenticationToken.GetSymmetricSecurityKey(),
                                                                                                SecurityAlgorithms.HmacSha256));
                string token =
                    new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                var response = new
                {
                    access_token = token,
                    username     = claimsIdentity.Name
                };
                return(Json(response));
            }
            else
            {
                return(BadRequest(400));
            }
        }
예제 #39
0
        /// <summary>
        /// Initialises a new instance of the <see cref="LiveDecrypterFactory"/> class and specifies
        /// the user's <see cref="AuthenticationToken"/>
        /// </summary>
        /// <param name="token">The user's <see cref="AuthenticationToken"/>.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="token"/> is <see langword="null"/>.
        /// </exception>
        public LiveDecrypterFactory(AuthenticationToken token)
        {
            Guard.NotNull(token, "token");

            AuthToken = token.Token;
        }
예제 #40
0
 public GoodReadsClientTests()
 {
     // read authentication information from configuration file.
     _token = JsonConvert.DeserializeObject <AuthenticationToken>(File.ReadAllText(configDataLocation));
 }
예제 #41
0
 /// <summary>
 /// Creates a live-timing message reader using the specified authentication
 /// <paramref name="token"/>.
 /// </summary>
 /// <param name="token">The authentication token.</param>
 /// <returns>A message reader which reads live messages.</returns>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown when <paramref name="token"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// Thrown when an IO error whilst connecting to the live-timing message stream.
 /// </exception>
 public static IMessageReader Read(AuthenticationToken token)
 {
     return new LiveMessageReader(new LiveMessageStreamEndpoint(), new LiveDecrypterFactory(token));
 }
예제 #42
0
 public void ReadFrom(ref SpanBufferReader bufferReader)
 {
     AuthenticationToken = new AuthenticationToken();
     AuthenticationToken.ReadFrom(ref bufferReader);
 }
예제 #43
0
        // This is a token generated by other authserver, we need to add it to synchronize the data
        // among all authservers
        public void AddSynchronizedToken(string token, string username, DateTime expTime)
        {
            AuthenticationToken authtoken = null;
            lock (m_TokenDatabase) {
                authtoken = m_TokenDatabase.Find(
                    delegate(AuthenticationToken tmptoken)
                    {
                        return tmptoken.m_Token == token;
                    }
                );
                if (authtoken != null)
                {
                    authtoken.m_ExpireTime = expTime;
                }
                else
                {
                    AuthenticationToken newtoken = new AuthenticationToken(token, username, expTime);
                    newtoken.m_ExpireTime = expTime;
                    m_TokenDatabase.Add(newtoken);
                }
#if DEBUG
                Console.WriteLine("Copy token: " + token + ", for user: "******" at time: " + DateTime.Now);
#endif
            }
        }
예제 #44
0
 public Task CreateAsync(AuthenticationToken authenticationToken)
 {
     return(Task.Run(() => AuthenticationTokens.Add(authenticationToken)));
 }
        public void Given_token_doesnt_exist_when_DisableAuthenticationToken_then_token_disabled()
        {
            //given
            var savedToken = new AuthenticationToken(){IsEnabled =  true};
            _authTokenRepository.Setup(x => x.GetById(It.IsAny<Guid>()))
                .Returns(() => savedToken);

            var target = GetTarget();

            //then
            target.DisableAuthenticationToken(Guid.NewGuid());

            //when
            Assert.False(savedToken.IsEnabled = false);


        }
예제 #46
0
 public Task UpdateAsync(AuthenticationToken authenticationToken)
 {
     NumberOfTimesUpdateWasInvoked++;
     return(Task.FromResult <object>(null));
 }