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.

54 lines
1.4 KiB

4 years ago
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. export async function forgotPassword(username: string): Promise<void> {
  19. const res = await Auth.forgotPassword(username);
  20. }
  21. export async function forgotPasswordSubmit(username: string, code: string, password: string): Promise<void> {
  22. await Auth.forgotPasswordSubmit(username, code, password);
  23. }
  24. async function getAccessToken(): Promise<CognitoAccessToken | null> {
  25. try {
  26. const u = await Auth.currentSession();
  27. if (!u || !u.isValid()) {
  28. return null;
  29. }
  30. return u.getIdToken();
  31. } catch (e) {
  32. return null;
  33. }
  34. }
  35. export async function getJwt(): Promise<string> {
  36. const token = await getAccessToken();
  37. if (!token) {
  38. throw new Error("unauthorized");
  39. }
  40. return token.getJwtToken();
  41. }
  42. export async function checkSession(): Promise<boolean> {
  43. return !!(await getAccessToken());
  44. }