Skip to content

Instantly share code, notes, and snippets.

@maoosi
Last active October 26, 2021 18:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maoosi/04899cdcdebf097001f498820caeffd2 to your computer and use it in GitHub Desktop.
Save maoosi/04899cdcdebf097001f498820caeffd2 to your computer and use it in GitHub Desktop.
[WIP] Custom amplify auth scheme for nuxt/auth (auth.nuxtjs.org).
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