public Paging <SavedTrack> GetSavedTracks(CustomToken token, int limit = 10, int offset = 0, string market = "") { if (token.tokenCredentialType == CustomToken.TokenCredentialType.Client) { return(null); } SpotifyWebAPI api = new SpotifyWebAPI() { AccessToken = token.AccessToken, UseAuth = true, TokenType = token.TokenType }; try { Paging <SavedTrack> savedTracks = api.GetSavedTracks(limit, offset, market); return(savedTracks); } catch (System.Exception ex) { log.Error( string.Format("GetUsersRecentlyPlayedTracks()") , ex); } return(null); }
public Recommendations GetRecommendations(CustomToken token, string trackId, string artistId) { SpotifyWebAPI api = new SpotifyWebAPI() { AccessToken = token.AccessToken, UseAuth = true, TokenType = token.TokenType }; Recommendations recommendations = null; try { recommendations = api.GetRecommendations( artistId.Split(',').ToList(), null , trackId.Split(',').ToList() ); } catch (System.Exception ex) { log.Error( string.Format("GetRecommendations() => trackId {0}, artistId {1}", trackId, artistId) , ex); } return(recommendations); }
public CustomTokenForm(CustomToken ct) { InitializeComponent(); Application.Idle += new EventHandler(Application_Idle); Array sizes = Enum.GetValues(typeof(CreatureSize)); foreach (CreatureSize size in sizes) { SizeBox.Items.Add(size); } fToken = ct.Copy(); NameBox.Text = fToken.Name; SizeBox.SelectedItem = fToken.TokenSize; update_power(); DetailsBox.Text = fToken.Details; int n = Creature.GetSize((CreatureSize)SizeBox.SelectedItem); TilePanel.TileSize = new Size(n, n); TilePanel.Image = fToken.Image; TilePanel.Colour = fToken.Colour; }
public ActionResult Playlists() { CustomToken token = ViewBag.Token; if (token.IsTokenEmpty()) { return(PartialView("~/Views/Shared/_LoginMessage.cshtml")); } PrivateProfile profile = GetMe(token); if (profile == null || profile.Id == null) { return(null); } var playlists = base.GetPlaylists(token, profile.Id); if (playlists != null && playlists.Items != null && playlists.Items.Count > 0) { return(PartialView("~/Views/Shared/_PlaylistList.cshtml", playlists.Items)); } return(null); }
public CustomToken RefreshToken(string refreshToken, string clientSecret) { AutorizationCodeAuth auth = new AutorizationCodeAuth() { ClientId = Constants.ClientId, State = Constants.StateKey }; Token response; CustomToken result = null; try { response = auth.RefreshToken(refreshToken, clientSecret); result = response.ToCustomToken(); if (result != null) { result.RefreshToken = refreshToken; } } catch (Exception ex) { } return(result); }
public JsonResult Playlists(PlaylistModel model) { CustomToken token = ViewBag.Token; if (token.IsTokenEmpty()) { return(null); } SpotifyWebAPI api = new SpotifyWebAPI() { AccessToken = token.AccessToken, TokenType = token.TokenType }; var tracksIds = model.trackId.Split(','); List <ErrorResponse> errorResponses = new List <ErrorResponse>(); foreach (var tracksId in tracksIds) { errorResponses.Add(api.AddPlaylistTrack(model.playlistId, string.Format("spotify:track:{0}", tracksId))); } return(Json(errorResponses.FirstOrDefault(e => e.Error == null))); }
public CustomOverlayForm(CustomToken ct) { this.InitializeComponent(); Application.Idle += new EventHandler(this.Application_Idle); this.fToken = ct.Copy(); this.NameBox.Text = this.fToken.Name; this.WidthBox.Value = this.fToken.OverlaySize.Width; this.HeightBox.Value = this.fToken.OverlaySize.Height; this.update_power(); this.DetailsBox.Text = this.fToken.Details; this.TilePanel.TileSize = this.fToken.OverlaySize; this.TilePanel.Image = this.fToken.Image; this.TilePanel.Colour = this.fToken.Colour; this.StyleBox.Items.Add("Rounded (translucent)"); this.StyleBox.Items.Add("Block (opaque)"); switch (this.fToken.OverlayStyle) { case OverlayStyle.Rounded: { this.StyleBox.Text = "Rounded (translucent)"; break; } case OverlayStyle.Block: { this.StyleBox.Text = "Block (opaque)"; break; } } this.DifficultBox.Checked = this.fToken.DifficultTerrain; this.OpaqueBox.Checked = this.fToken.Opaque; this.TerrainLayerBox.Checked = this.fToken.IsTerrainLayer; this.IsUnSelectableBox.Checked = this.fToken.IsUnSelectable; }
public ActionResult Recommendations(string trackId, string artistId) { CustomToken token = ViewBag.Token; if (token.IsTokenEmpty()) { return(null); } var recommendations = _paradifyService.GetRecommendations(token, trackId, artistId); if (recommendations != null && recommendations.Tracks != null && recommendations.Tracks.Count > 0) { SeveralTracks tracks = _paradifyService.GetTracks(recommendations.Tracks.Select(t => t.Id).ToList(), token); if (tracks != null && tracks.Tracks != null && tracks.Tracks.Count > 0) { return(PartialView("~/Views/Shared/_RecommendedSongListShort.cshtml", tracks.Tracks)); } } return(PartialView("~/Views/Shared/_RecommendedSongListShort.cshtml", null)); }
public ActionResult GetPlayingTrack() { CustomToken token = ViewBag.Token; return(PartialView("~/Views/Shared/PlayingTrack/_PlayingTrack.cshtml" , token.IsTokenEmpty() ? null : _paradifyService.GetPlayingTrack(token))); }
public CustomToken RefreshToken(string refreshToken, string clientSecret) { AuthorizationCodeAuth auth = new AuthorizationCodeAuth( Settings.ClientId, Settings.ClientSecret, Settings.RedirectUri, Settings.RedirectUri, Scope.None, Settings.StateKey ); Token response; CustomToken result = null; try { response = auth.RefreshToken(refreshToken).Result; result = response.ToCustomToken(); if (result != null) { result.RefreshToken = refreshToken; } } catch (Exception) { } return(result); }
public ActionResult Me() { CustomToken token = ViewBag.Token; return(PartialView("~/Views/Shared/_Login.cshtml", token.IsTokenEmpty() ? null : _userService.GetMe(_tokenService))); }
private CustomToken GetClientToken() { SpotifyAPI.Web.Auth.CredentialsAuth clientCredentialsAuth = new SpotifyAPI.Web.Auth.CredentialsAuth(Settings.ClientId, Settings.ClientSecret); Token response = clientCredentialsAuth.GetToken().Result; CustomToken token = response.ToCustomToken(CustomToken.TokenCredentialType.Client); return(token); }
private CustomToken GetClientToken() { SpotifyAPI.Web.Auth.ClientCredentialsAuth clientCredentialsAuth = new SpotifyAPI.Web.Auth.ClientCredentialsAuth(); clientCredentialsAuth.ClientId = Constants.ClientId; clientCredentialsAuth.ClientSecret = Constants.ClientSecret; Token response = clientCredentialsAuth.DoAuth(); CustomToken token = response.ToCustomToken(CustomToken.TokenCredentialType.Client); return(token); }
public ActionResult GetNewReleasedTracks(string countryCode) { CustomToken token = ViewBag.Token; if (token.IsTokenEmpty()) { return(null); } var result = _paradifyService.GetNewReleasedTracks(token, countryCode); return(PartialView("~/Views/Shared/_NewReleasedTracks.cshtml", result)); }
public override void OnActionExecuting(ActionExecutingContext context) { CustomToken token = _sessionService.GetToken(); if (token == null) { token = _tokenCookieService.Get(); if (!string.IsNullOrEmpty(token.AccessToken) && token.tokenCredentialType == TokenCredentialType.Auth) { _sessionService.SetToken(token.ToCustomToken(token.tokenCredentialType)); } } if (token == null || (string.IsNullOrEmpty(token.AccessToken) && !string.IsNullOrEmpty(token.RefreshToken))) { token = RefreshToken(token.RefreshToken, Settings.ClientSecret); if (token == null || string.IsNullOrEmpty(token.AccessToken)) { //Just Die } else { _tokenCookieService.SetToken(token); _sessionService.SetToken(token); } } var controller = context.Controller as Controller; if (controller != null) { if (token.tokenCredentialType != TokenCredentialType.Auth) { controller.ViewBag.Token = null; } else { controller.ViewBag.Token = token; } } base.OnActionExecuting(context); }
private void EffectAddToken_Click(object sender, EventArgs e) { CustomToken token = new CustomToken(); token.Name = "New Token"; token.Type = CustomTokenType.Token; CustomTokenForm dlg = new CustomTokenForm(token); if (dlg.ShowDialog() == DialogResult.OK) { fHero.Tokens.Add(dlg.Token); update_effects(); } }
public TResponse BuildCustomUserResponse <TResponse>(Func <TIdentityUser, IEnumerable <UserClaim>, CustomToken, TResponse> outraFuncao) { var clams = _userClaims.Select(c => new UserClaim { Type = c.Type, Value = c.Value }); var token = new CustomToken { AccessToken = BuildToken(), ExpiresIn = TimeSpan.FromHours(_appJwtSettings.Expiration).TotalSeconds, tokenType = "bearer" }; return(outraFuncao(_user, clams, token)); }
private void EffectAddOverlay_Click(object sender, EventArgs e) { CustomToken overlay = new CustomToken(); overlay.Name = "New Overlay"; overlay.Type = CustomTokenType.Overlay; CustomOverlayForm dlg = new CustomOverlayForm(overlay); if (dlg.ShowDialog() == DialogResult.OK) { fHero.Tokens.Add(dlg.Token); update_effects(); } }
private static GitLabApi BuildGitLabApi(IConfiguration configuration) { var cfg = configuration.GetSection("GitLab"); var globalToken = cfg.GetValue <string>("globalToken"); var accessTokenSource = new CustomToken(globalToken); var memoryCache = new MemoryCache(new MemoryCacheOptions()); bool readOnly = false; if (!bool.TryParse(cfg["readOnly"] ?? "", out readOnly)) { readOnly = false; } return(GitLabApiFactory.CreateGitLabApi(cfg["url"], accessTokenSource, cfg["Proxy"], memoryCache, readOnly)); }
private CustomToken GetTokenFromCookie() { CustomToken token = new CustomToken { AccessToken = CookieManager.GetCookieValue("access_token"), RefreshToken = CookieManager.GetCookieValue("refresh_token"), TokenType = "Bearer" }; TokenCredentialType type = TokenCredentialType.Auth; Enum.TryParse(CookieManager.GetCookieValue("token_type"), out type); token.tokenCredentialType = type; return(token); }
void update_list() { EffectList.Items.Clear(); foreach (TokenLink link in fLinks) { string tokens = ""; foreach (IToken token in link.Tokens) { string name = ""; if (token is CreatureToken) { CreatureToken ct = token as CreatureToken; name = ct.Data.DisplayName; } if (token is Hero) { Hero hero = token as Hero; name = hero.Name; } if (token is CustomToken) { CustomToken ct = token as CustomToken; name = ct.Name; } if (name == "") { name = "(unknown map token)"; } if (tokens != "") { tokens += ", "; } tokens += name; } ListViewItem lvi = EffectList.Items.Add(tokens); lvi.SubItems.Add(link.Text); lvi.Tag = link; } }
public void JumpTo(string jumpString) { _jumpString = jumpString; string filterStr = String.Empty; CustomStringTokenizer tok = new CustomStringTokenizer(jumpString); IList <CustomToken> tokens = new List <CustomToken>(); string tmp = String.Empty; CustomToken token = null; do { token = tok.Next(); if (token.Kind == CustomTokenKind.EOL || token.Kind == CustomTokenKind.EOF || token.Kind == CustomTokenKind.Unknown || token.Kind == CustomTokenKind.WhiteSpace || (token.Kind == CustomTokenKind.Symbol && token.Value != ".") ) { continue; } tokens.Add(token); } while (token.Kind != CustomTokenKind.EOF); if (tokens.Count == 0 || tokens[tokens.Count - 1].Value == ".") { filterStr = String.Empty; } else { filterStr = "( DisplayName Like '" + tokens[tokens.Count - 1].Value + "%')"; } _bsListItems.Filter = filterStr; if (_bsListItems.Count > 0) { _bsListItems.Position = 0; _bsListItems.Sort = "DisplayName ASC"; } else { _bsListItems.Sort = String.Empty; } }
public ActionResult Index(string q) { _search = q; _trackId = ""; SearchResult searchResult = new SearchResult(); if (!_search.NullCheck()) { _search = _search.Decode(); ViewBag.Title = string.Format("{0} - {1}", _search, Constants.SingleTitle); CustomToken token = ViewBag.Token; SearchItem searchItem = null; if (!token.IsTokenEmpty()) { PrivateProfile profile = new PrivateProfile(); if (token.tokenCredentialType == CustomToken.TokenCredentialType.Auth) { profile = GetMe(token); } searchItem = Search(_search, token); if (searchItem != null && searchItem.Tracks != null && searchItem.Tracks.Items != null && searchItem.Tracks.Items.Count == 0) { var tempSearch = Regex.Replace(_search, "\\([^\\]]*\\)", ""); searchItem = Search(tempSearch, token); } } else { searchResult.IsTokenEmpty = true; } searchResult.SearchItem = searchItem; searchResult.query = _search; searchResult.track = _trackId; } return(View("Index", searchResult)); }
public PlaybackContext GetPlayingTrack(CustomToken token) { SpotifyWebAPI api = new SpotifyWebAPI() { AccessToken = token.AccessToken, UseAuth = true, TokenType = token.TokenType }; try { return(api.GetPlayingTrack()); } catch { return(null); } }
public ActionResult SavedTracks() { CustomToken token = ViewBag.Token; if (token.IsTokenEmpty()) { return(null); } var paginSavedTracks = _paradifyService.GetSavedTracks(token, 10); if (paginSavedTracks != null && paginSavedTracks.Items != null && paginSavedTracks.Items.Count > 0) { return(PartialView("~/Views/Shared/_SavedTracksShort.cshtml", paginSavedTracks)); } return(null); }
public ActionResult RecentlyPlayedTracks() { CustomToken token = ViewBag.Token; if (token.IsTokenEmpty()) { return(null); } var cursorPagingPlayHistory = _paradifyService.GetUsersRecentlyPlayedTracks(token, 10); if (cursorPagingPlayHistory != null && cursorPagingPlayHistory.Items != null && cursorPagingPlayHistory.Items.Count > 0) { return(PartialView("~/Views/Shared/_RecentlyPlayedTracks.cshtml", cursorPagingPlayHistory)); } return(null); }
public CustomTokenForm(CustomToken ct) { this.InitializeComponent(); Application.Idle += new EventHandler(this.Application_Idle); foreach (CreatureSize value in Enum.GetValues(typeof(CreatureSize))) { this.SizeBox.Items.Add(value); } this.fToken = ct.Copy(); this.NameBox.Text = this.fToken.Name; this.SizeBox.SelectedItem = this.fToken.TokenSize; this.update_power(); this.DetailsBox.Text = this.fToken.Details; int size = Creature.GetSize((CreatureSize)this.SizeBox.SelectedItem); this.TilePanel.TileSize = new System.Drawing.Size(size, size); this.TilePanel.Image = this.fToken.Image; this.TilePanel.Colour = this.fToken.Colour; }
public ActionResult GetGenres() { List <string> model = null; CustomToken token = ViewBag.Token; if (!token.IsTokenEmpty()) { RecommendationSeedGenres recommendationSeedGenres = _paradifyService.GetGenres(token); if (recommendationSeedGenres != null && recommendationSeedGenres.Genres != null && recommendationSeedGenres.Genres.Count > 0) { model = recommendationSeedGenres.Genres; } } return(PartialView("~/Views/Shared/Genres/_Genres.cshtml", model)); }
public CursorPaging <PlayHistory> GetUsersRecentlyPlayedTracks(CustomToken token, int limit = 20) { if (token.tokenCredentialType == CustomToken.TokenCredentialType.Client) { return(null); } SpotifyWebAPI api = new SpotifyWebAPI() { AccessToken = token.AccessToken, UseAuth = true, TokenType = token.TokenType }; try { return(api.GetUsersRecentlyPlayedTracks(limit)); } catch { } return(null); }
public ErrorResponse Post(PlaylistModel model) { Token token = GetToken(); if (token.RefreshToken != null) { string oldRefreshToken = token.RefreshToken; token = RefreshToken(token.RefreshToken); token.RefreshToken = oldRefreshToken; CustomToken customToken = new CustomToken(token); _tokenService.SetToken(customToken); } SpotifyWebAPI api = new SpotifyWebAPI() { AccessToken = token.AccessToken, TokenType = token.TokenType }; ErrorResponse errorResponse = api.AddPlaylistTrack(model.playlistId, model.trackId); return(errorResponse); }
/// <summary> /// Validates the signature on the incoming token. /// </summary> /// <param name="CustomToken">The incoming <see cref="CustomToken"/>.</param> protected virtual void ValidateSignature( CustomToken CustomToken ) { if ( CustomToken == null ) { throw new ArgumentNullException( "CustomToken" ); } if ( String.IsNullOrEmpty( CustomToken.SerializedToken ) || String.IsNullOrEmpty( CustomToken.Signature ) ) { throw new SecurityTokenValidationException( "The token does not have a signature to verify" ); } string serializedToken = CustomToken.SerializedToken; string unsignedToken = null; // Find the last parameter. The signature must be last per SWT specification. int lastSeparator = serializedToken.LastIndexOf( ParameterSeparator ); // Check whether the last parameter is an hmac. if ( lastSeparator > 0 ) { string lastParamStart = ParameterSeparator + CustomTokenConstants.Signature + "="; string lastParam = serializedToken.Substring( lastSeparator ); // Strip the trailing hmac to obtain the original unsigned string for later hmac verification. if ( lastParam.StartsWith( lastParamStart, StringComparison.Ordinal ) ) { unsignedToken = serializedToken.Substring( 0, lastSeparator ); } } CustomTokenKeyIdentifierClause clause = new CustomTokenKeyIdentifierClause(CustomToken.Audience); InMemorySymmetricSecurityKey securityKey = null; try { securityKey = (InMemorySymmetricSecurityKey)this.Configuration.IssuerTokenResolver.ResolveSecurityKey(clause); } catch (InvalidOperationException) { throw new SecurityTokenValidationException( "A Symmetric key was not found for the given key identifier clause."); } string generatedSignature = GenerateSignature( unsignedToken, securityKey.GetSymmetricKey() ); if ( string.CompareOrdinal( HttpUtility.UrlDecode( generatedSignature ), HttpUtility.UrlDecode( CustomToken.Signature ) ) != 0 ) { throw new SecurityTokenValidationException( "The signature on the incoming token is invalid.") ; } }
/// <summary> /// Parses the string token and generates a <see cref="SecurityToken"/>. /// </summary> /// <param name="serializedToken">The serialized form of the token received.</param> /// <returns>The parsed form of the token.</returns> protected SecurityToken ReadSecurityTokenFromString( string serializedToken ) { if (String.IsNullOrEmpty(serializedToken)) { throw new ArgumentException("The parameter 'serializedToken' cannot be null or empty string."); } // Create a collection of SWT name value pairs NameValueCollection properties = ParseToken( serializedToken ); CustomToken swt = new CustomToken( properties, serializedToken ); return swt; }
/// <summary>Creates <see cref="Claim"/>'s from the incoming token. /// </summary> /// <param name="CustomToken">The incoming <see cref="CustomToken"/>.</param> /// <returns>A <see cref="ClaimsIdentity"/> created from the token.</returns> protected virtual ClaimsIdentity CreateClaims( CustomToken CustomToken ) { if ( CustomToken == null ) { throw new ArgumentNullException( "CustomToken" ); } NameValueCollection tokenProperties = CustomToken.GetAllProperties(); if ( tokenProperties == null ) { throw new SecurityTokenValidationException( "No claims can be created from this Simple Web Token." ); } if ( Configuration.IssuerNameRegistry == null ) { throw new InvalidOperationException( "The Configuration.IssuerNameRegistry property of this SecurityTokenHandler is set to null. Tokens cannot be validated in this state." ); } string normalizedIssuer = Configuration.IssuerNameRegistry.GetIssuerName( CustomToken ); ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.Federation); foreach ( string key in tokenProperties.Keys ) { if ( ! IsReservedKeyName(key) && !string.IsNullOrEmpty( tokenProperties[key] ) ) { identity.AddClaim( new Claim( key, tokenProperties[key], ClaimValueTypes.String, normalizedIssuer ) ); if ( key == AcsNameClaimType ) { // add a default name claim from the Name identifier claim. identity.AddClaim( new Claim( DefaultNameClaimType, tokenProperties[key], ClaimValueTypes.String, normalizedIssuer ) ); } } } return identity; }
public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor) { if (tokenDescriptor == null) { throw new ArgumentNullException("tokenDescriptor"); } NameValueCollection properties = new NameValueCollection(); properties.Add(CustomTokenConstants.Id, Guid.NewGuid().ToString()); properties.Add(CustomTokenConstants.Issuer, tokenDescriptor.TokenIssuerName); properties.Add(CustomTokenConstants.Audience, tokenDescriptor.AppliesToAddress); properties.Add(CustomTokenConstants.ExpiresOn, SecondsFromSwtBaseTime(tokenDescriptor.Lifetime.Expires)); properties.Add(CustomTokenConstants.ValidFrom, SecondsFromSwtBaseTime(tokenDescriptor.Lifetime.Created)); foreach (Claim claim in tokenDescriptor.Subject.Claims) { properties.Add(claim.Type, claim.Value); } CustomToken token = new CustomToken(properties); return token; }