Skip to content

Commit

Permalink
refresh tokens on first open
Browse files Browse the repository at this point in the history
  • Loading branch information
metkm committed Jul 9, 2022
1 parent e2e6bc2 commit 30ad984
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 28 deletions.
40 changes: 19 additions & 21 deletions server/src/routes/auth/refresh.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
use std::{collections::HashMap, sync::Arc};

use axum::Json;
use axum::{http::StatusCode, response::IntoResponse, Extension};
use axum_extra::extract::{cookie::Cookie, CookieJar};
use tokio_postgres::Client;

use crate::api::get_tokens;
use crate::database::insert_session;
use crate::models::server::ServerState;
use crate::models::session::Session;
use crate::utils::{gen_random_str, hashmap};
use crate::utils::{hashmap};

pub async fn refresh(
Extension(db): Extension<Arc<Client>>,
Extension(current_session): Extension<Session>,
Extension(server_state): Extension<Arc<ServerState>>,
jar: CookieJar,
) -> Result<impl IntoResponse, (StatusCode, &'static str)> {
let client = reqwest::Client::new();

Expand All @@ -23,24 +21,24 @@ pub async fn refresh(
"client_id" => &server_state.client_id,
"client_secret" => &server_state.client_secret,
"refresh_token" => &current_session.refresh_token,
"redirect_uri" => "http://127.0.0.1:3000/api/authorize"
"redirect_uri" => "http://localhost:3001/api/authorize"
};

let Ok(tokens) = get_tokens(&client, &params).await else {
return Err((StatusCode::INTERNAL_SERVER_ERROR, "Can't refresh tokens!"))
};

let session_str = gen_random_str();
insert_session(
&db,
&current_session.user_id,
&current_session.friend_ids,
&session_str,
&tokens.access_token,
&tokens.refresh_token,
)
.await?;
let tokens = get_tokens(&client, &params).await?;

let updated_jar = jar.add(Cookie::new("osu_session", session_str));
Ok((StatusCode::OK, updated_jar, "Ok!"))
if db
.execute(
"UPDATE sessions SET access_token=$1, refresh_token=$2 WHERE osu_session=$3",
&[&tokens.access_token, &tokens.refresh_token, &current_session.osu_session],
)
.await
.is_err()
{
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Can't update session tokens!",
));
}

Ok((StatusCode::OK, Json(tokens)))
}
15 changes: 13 additions & 2 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
import { notify, notifyRemove } from "./plugin/notification";
import TitleBar from "./components/AppTitleBar.vue";
import axios from "axios";
const router = useRouter();
const settingsStore = useSettingsStore();
const authStore = useAuthStore();
axios.defaults.baseURL = import.meta.env.DEV ? "http://localhost:3001" : "https://sibylku.xyz";
axios.defaults.withCredentials = true;
onMounted(() => {
let params = new URLSearchParams(window.location.search);
Expand Down Expand Up @@ -46,7 +49,15 @@ onMounted(async () => {
notify(updateText)
}
if (settingsStore.uploaded) return;
if (settingsStore.uploaded) {
// refresh token
axios.patch<{ access_token: string, refresh_token: string }>("/api/refresh").then(response => {
authStore.access_token = response.data.access_token;
authStore.refresh_token = response.data.refresh_token;
})
return;
}
notify("Would you like to upload your friend list to database?", {
acceptText: "Yes!",
Expand All @@ -65,7 +76,7 @@ event.listen("tauri://update-status", (res) => {
});
if (import.meta.env.DEV) {
router.push({ path: "/settings" });
router.push({ path: "/" });
} else {
router.push({ path: "/" });
}
Expand Down
10 changes: 5 additions & 5 deletions src/views/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ const userStore = useUserStore();
const mutuals = ref<UserObject[] | null>();
if (authStore.access_token) {
let url = import.meta.env.DEV ? "http://localhost:3001/api/mutuals" : "https://sibylku.xyz/api/mutuals";
axios.get<UserObject[]>(url, { withCredentials: true }).then(users => mutuals.value = users.data);
// fetch(url, { credentials: "include" }).then(response => response.json()).then(users => mutuals.value = users);
axios.get<UserObject[]>("/api/mutuals")
.then(users => {
mutuals.value = users.data;
});
}
const login = async () => {
Expand Down Expand Up @@ -87,7 +87,7 @@ const login = async () => {
<div class="flex flex-col gap-2">
<AppInput v-model="username" type="text" placeholder="Username" />
<AppInput v-model="password" type="text" placeholder="Password" />

<button class="form-button" :disabled="cooldown" @click="login">Login</button>
<p class="setting-description font-semibold">Version: {{ version }}</p>
</div>
Expand Down

0 comments on commit 30ad984

Please sign in to comment.