Skip to content

Commit e88ddb1

Browse files
docs(scheme): add custom scheme creation docs (#692)
1 parent d369e0b commit e88ddb1

File tree

1 file changed

+78
-1
lines changed

1 file changed

+78
-1
lines changed

docs/guide/scheme.md

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,84 @@ auth: {
2020
strategies: {
2121
local1: { _scheme: 'local', /* ... */ },
2222
local2: { _scheme: 'local', /* ... */ },
23-
custom: { _scheme: '~/app/customStrategy.js', /* ... */ },
23+
custom: { _scheme: '~/app/customScheme', /* ... */ },
2424
}
2525
}
2626
```
27+
28+
## Creating your own scheme
29+
Sometimes the included schemes doesn't match your requirements. Creating your own scheme will provide flexibility you need. You can create a new scheme from scratch or extend an existing scheme.
30+
31+
> **Note** A list of available scheme methods will be added in future releases.
32+
33+
Before creating custom schemes, you will need to add `@nuxtjs/auth` to `transpile`.
34+
35+
`nuxt.config.js`
36+
```js
37+
build: {
38+
transpile: ['@nuxtjs/auth']
39+
}
40+
```
41+
42+
With this set up, you can create your scheme file. We will be using the path below, but you can use a different path if you want.
43+
44+
> In this example we will be extending `local` scheme and overriding `fetchUser` method. We will transform the user object before setting it.
45+
46+
`~/schemes/customScheme.js`
47+
```js
48+
import LocalScheme from '@nuxtjs/auth/lib/schemes/local'
49+
50+
export default class CustomScheme extends LocalScheme {
51+
// Override `fetchUser` method of `local` scheme
52+
async fetchUser (endpoint) {
53+
// Token is required but not available
54+
if (this.options.tokenRequired && !this.$auth.getToken(this.name)) {
55+
return
56+
}
57+
58+
// User endpoint is disabled.
59+
if (!this.options.endpoints.user) {
60+
this.$auth.setUser({})
61+
return
62+
}
63+
64+
// Try to fetch user
65+
const user = await this.$auth.requestWith(
66+
this.name,
67+
endpoint,
68+
this.options.endpoints.user
69+
)
70+
71+
// Transform the user object
72+
const customUser = {
73+
...user,
74+
fullName: user.firstName + ' ' + user.lastName,
75+
roles: ['user']
76+
}
77+
78+
// Set the custom user
79+
// The `customUser` object will be accessible through `this.$auth.user`
80+
// Like `this.$auth.user.fullName` or `this.$auth.user.roles`
81+
this.$auth.setUser(customUser)
82+
}
83+
}
84+
```
85+
86+
Then set your new scheme in the auth config.
87+
88+
`nuxt.config.js`
89+
```js
90+
auth: {
91+
strategies: {
92+
customStrategy: {
93+
_scheme: '~/schemes/customScheme',
94+
/* ... */
95+
}
96+
}
97+
}
98+
```
99+
100+
That's it! Now you can log in using your new strategy.
101+
```js
102+
this.$auth.loginWith('customStrategy', { /* ... */ })
103+
```

0 commit comments

Comments
 (0)