ramsayleung / rspotify

Spotify Web API SDK implemented on Rust
MIT License
639 stars 123 forks source link

Database storage for access token #370

Closed v3lmx closed 1 year ago

v3lmx commented 1 year ago

Hello!

Is your feature request related to a problem? Please describe. I want to store the access token obtained in the Authorization Code Flow with request_token() in a database, to handle multiple users.

Describe the solution you'd like Either :

Describe alternatives you've considered I tried implementing a new Trait for AuthCodeSpotify to rewrite the function request_token, but quickly encountered private enums and functions (such as params), so it felt like rewriting the whole crate for a single function.

Additional context The method currently used to get the token is request_token, and it "stores the token internally" in cache if it is configured, and nowhere if it is not as far as I can tell. I'm pretty new to rust so I may have missed something.

I would be willing to give a try to this issue if you think it is a desired feature, if you can give me some pointers to put me in the right direction :)

ramsayleung commented 1 year ago

have a method to directly get the token, such as https://github.com/ramsayleung/rspotify/issues/96 previously implemented (not is the codebase anymore as far as I can tell)

I think the get_token method in BaseClient could satisfy your need, you could disable the cache and get token from client:

https://github.com/ramsayleung/rspotify/blob/2fe50355312d90d9b93d3731ecdc1dda3c569a03/src/clients/base.rs#L36

fn get_token(&self) -> Arc<Mutex<Option<Token>>>;

Then You could get data from Token and save them into database as you want.

v3lmx commented 1 year ago

Got it ! It works :) This method doesn't fetch the token so I didn't think to use it in combination with request_token() that actually goes to spotify to get it.

In case anyone encounters this problem, solution snippet below :

// Callback function called by spotify
#[get("/callback?<code>")]
async fn callback(jar: &CookieJar<'_>, code: String) -> AppResponse<BasicResponse> {
    let mut spotify = init_spotify(jar);

    // Fetch the token
    let _res = spotify.request_token(&code).await;

    // Get it to store it in databse
    let token_mutex = spotify.get_token();
    let mut token = token_mutex.lock().await.unwrap();
    let mut token: &mut Token = token.as_mut().expect("Token can't be empty as this point");

    info!("Token: {}", token.access_token);
    // ...