You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

4 years ago
4 years ago
4 years ago
  1. import Amplify from "@aws-amplify/core";
  2. import Auth from "@aws-amplify/auth";
  3. import type {CognitoAccessToken, CognitoUser} from "amazon-cognito-identity-js";
  4. Amplify.configure({
  5. Auth: {
  6. region: process.env.AWS_AMPLIFY_REGION,
  7. userPoolId: process.env.AWS_AMPLIFY_USER_POOL_ID,
  8. userPoolWebClientId: process.env.AWS_AMPLIFY_USER_POOL_WEB_CLIENT_ID,
  9. },
  10. });
  11. export async function signIn(username: string, password: string): Promise<CognitoUser | null> {
  12. const u = await Auth.signIn(username, password);
  13. return u || null;
  14. }
  15. export async function signOut(): Promise<void> {
  16. await Auth.signOut();
  17. }
  18. async function getAccessToken(): Promise<CognitoAccessToken | null> {
  19. try {
  20. const u = await Auth.currentSession();
  21. if (!u || !u.isValid()) {
  22. return null;
  23. }
  24. return u.getIdToken();
  25. } catch (e) {
  26. return null;
  27. }
  28. }
  29. export async function getJwt(): Promise<string> {
  30. const token = await getAccessToken();
  31. if (!token) {
  32. throw new Error("unauthorized");
  33. }
  34. return token.getJwtToken();
  35. }
  36. export async function checkSession(): Promise<boolean> {
  37. return !!(await getAccessToken());
  38. }