Created
September 30, 2024 04:54
-
-
Save SealtielFreak/69e05a660e6c2599ee3c7802b2cc5034 to your computer and use it in GitHub Desktop.
Dummy auth for Svelte in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { writable, type Writable } from "svelte/store"; | |
import axios from "axios"; | |
export type Token = "Authenticated" | "Unauthenticated"; | |
export class UserDataCredentials { | |
private readonly accessToken: string; | |
private readonly status: Token; | |
constructor(accessToken: string, status: Token = "Unauthenticated") { | |
this.accessToken = accessToken; | |
this.status = status; | |
} | |
get isAuthenticated() { | |
return this.status === "Authenticated"; | |
} | |
get token() { | |
return this.accessToken; | |
} | |
get authorizationHeader() { | |
return `Bearer ${this.token}`; | |
} | |
} | |
export type WritableToken = Writable<UserDataCredentials>; | |
export const userCredentials: WritableToken = writable<UserDataCredentials>( | |
new UserDataCredentials(""), | |
); | |
export async function loginAuthenticateToken( | |
username: string, | |
password: string, | |
): Promise<WritableToken> { | |
const response = await axios.post("https://dummyjson.com/auth/login", { | |
username: username, | |
password: password, | |
expiresInMins: 30, | |
}); | |
let accessToken: string = ""; | |
let status: Token = "Unauthenticated"; | |
if (response.status == 200) { | |
status = "Authenticated"; | |
accessToken = response?.data?.accessToken || ""; | |
} | |
userCredentials.set(new UserDataCredentials(accessToken, status)); | |
return userCredentials; | |
} | |
export async function refreshAuthenticateToken() {} | |
export async function logoutAuthenticateToken() { | |
userCredentials.set(new UserDataCredentials("")); | |
} | |
export function dischargeAuthenticateToken() { | |
return userCredentials.subscribe((count) => count); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment