Last active
October 26, 2021 18:24
-
-
Save maoosi/04899cdcdebf097001f498820caeffd2 to your computer and use it in GitHub Desktop.
[WIP] Custom amplify auth scheme for nuxt/auth (auth.nuxtjs.org).
This file contains hidden or 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 { Amplify, Auth, withSSRContext } from 'aws-amplify' | |
import { Auth as NuxtAuth } from '@nuxtjs/auth-next' | |
export interface AmplifyAuthSchemeOptions { | |
name: string | |
} | |
export default class AmplifyAuthScheme { | |
public $auth: NuxtAuth | |
public options: AmplifyAuthSchemeOptions | |
constructor($auth: NuxtAuth, options: AmplifyAuthSchemeOptions) { | |
this.$auth = $auth | |
this.options = options | |
} | |
_Auth(): typeof Auth { | |
return process.server | |
? withSSRContext({ req: this.$auth.ctx.req }).Auth | |
: Auth | |
} | |
async mounted() { | |
// https://docs.amplify.aws/lib/auth/getting-started/q/platform/js#configure-your-application | |
Amplify.configure({ /* aws config here */ }) | |
return this.$auth.fetchUserOnce() | |
} | |
async login({ username, password }:{ username: string, password: string }) { | |
try { | |
await this.$auth.reset() | |
await this._Auth().signIn(username, password) | |
return this.$auth.fetchUser() | |
} catch (error) { | |
this.$auth.callOnError(error, { method: 'login' }) | |
} | |
} | |
async fetchUser() { | |
try { | |
const user = await this._Auth().currentAuthenticatedUser() | |
const { attributes } = process.server | |
? await this._Auth().currentUserInfo() | |
: user | |
this.$auth.setUser(attributes) | |
return user | |
} catch (error) { | |
this.$auth.callOnError(error, { method: 'fetchUser' }) | |
} | |
} | |
reset() { | |
this.$auth.setUser(false) | |
} | |
async logout() { | |
try { | |
await this._Auth().signOut() | |
return this.$auth.reset() | |
} catch (error) { | |
this.$auth.callOnError(error, { method: 'logout' }) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment