Authentication
Pruvious provides a built-in user authentication system that uses JSON web tokens (JWTs) and utility functions to manage user logins, logouts, and tokens.
API
Here is a list of the default API endpoints for authentication:
Route | Description |
---|---|
POST: | Logs in the user using their |
POST: | Logs out the user and returns |
POST: | Removes all active tokens of the user, except the one currently used in the request, and returns the number of deleted tokens. Check out on GitHub. |
POST: | Logs the user out from all active sessions and returns the number of removed tokens. Check out on GitHub. |
POST: | Replaces the current token used in the request with a new one and returns it. Check out on GitHub. |
GET: | Retrieves the profile of the currently authenticated user. Check out on GitHub. |
PATCH: | Updates the profile of the currently authenticated user. Check out on GitHub. |
When accessing API routes that require authentication, you need to send the token in the Authorization
header as a Bearer
token (i.e., Authorization: Bearer {token}
). However, when using Pruvious' utility functions, this step is automated and you don't need to do it manually.
Event context
When you create custom API routes and server handlers in Nuxt, authentication is automatically handled by a Pruvious middleware. The result is stored in the auth
parameter of the H3 event.context
. If you're not familiar with Nuxt APIs, we recommend learning more about it on the official Nuxt documentation page.
Here's an example of a custom API route that verifies if the user is logged in:
# server/api/whoami.get.ts
export default defineEventHandler((event) => {
if (!event.context.auth.isLoggedIn) {
setResponseStatus(event, 401)
return 'You are not logged in'
}
return `Hello, ${event.context.auth.user.firstName}`
})
The auth
parameter includes the following properties:
isLoggedIn
- A boolean indicating whether a valid token is provided with the request.user
- The populated user record (excluding thepassword
field) ornull
if no user is logged in.
Server Utilities
If you prefer to manually manage tokens in the backend, you can import the following utility functions from the #pruvious/server
alias:
Function | Description |
---|---|
| Deletes expired tokens from the internal database table |
| Checks whether a token exists in the cache or the internal |
| Retrieves the |
| Generates a new JSON web token (JWT) for a user ID. |
| Deletes a specific token from the database and cache. |
| Deletes all stored tokens associated with a user ID. |
| Stores a token in the internal database table |
| Verifies a JSON web token (JWT) and returns an object with the verification results. |
For more information, refer to the function implementations on GitHub.
Vue utilities
Pruvious also provides authentication utilities for Vue components.
# components/AuthExamples.vue
<template>
<div>...</div>
</template>
<script lang="ts" setup>
import {
getUserProfile,
login,
logout,
logoutAll,
logoutOtherSessions,
renewToken,
updateUserProfile,
useAuth,
} from '#pruvious/client'
const auth = useAuth()
// Login with email and password (third argument is `remember`)
const loginRes = await login('user@pruvious.com', 'password', true)
if (loginRes.success) {
console.log('User ID:', auth.value.userId)
} else {
console.error(loginRes.error, loginRes.code)
}
// Logout
await logout()
console.log(auth.value) // { isLoggedIn: false, userId: null }
// Logout other sessions except the current one
const otherTokensRemoved = await logoutOtherSessions()
console.log(otherTokensRemoved) // 0
// Logout all sessions
const tokensRemoved = await logoutAll()
console.log(tokensRemoved) // 0
// Renew token
const renewRes = await renewToken()
if (renewRes.success) {
console.log('User ID:', auth.value.userId)
} else {
console.error(renewRes.error, renewRes.code)
}
// Get user profile
const user = await getUserProfile()
console.log(user) // null
// Update user profile
const profileRes = await updateUserProfile({ password: 'new-password' })
if (profileRes.success) {
console.log('User:', profileRes.data)
} else {
console.error(profileRes.error, profileRes.code)
}
</script>
All functions can be imported from the #pruvious/client
alias.
Module options
You can configure authentication-related settings directly in the module options of your nuxt.config.ts
file. The most important options are found in the jwt
property.
# nuxt.config.ts
export default defineNuxtConfig({
modules: ['pruvious'],
pruvious: {
jwt: {
// Key used for signing JWTs
secretKey: 'random-secret-key',
// Tip: Use `NUXT_PRUVIOUS_JWT_SECRET_KEY` env var in production
// Token expiration time in seconds or a time span string
expiration: '4 hours',
// Token expiration time when `remember` is set to `true`
expirationLong: '7 days',
// Local storage key for storing the JWT
localStorageKey: 'token',
// Dashboard token renewal interval in minutes
renewInterval: 30,
},
},
})
When you install Pruvious using the CLI (i.e., pruvious init
) or run the pruvious setup
command in an existing Nuxt project, a random secretKey
will be generated automatically. Alternatively, you can manually generate a key using the https://pruvious.com/generate-key tool.
In addition, you have the option to customize or disable the default API routes for authentication. Here is an example configuration in the nuxt.config.ts
file:
# nuxt.config.ts
export default defineNuxtConfig({
modules: ['pruvious'],
pruvious: {
api: {
routes: {
// POST: /api/login
'login.post': 'login',
// POST: /api/logout
'logout.post': 'logout',
// POST: /api/logout-others
'logout-others.post': 'logout-others',
// POST: /api/logout-all
'logout-all.post': 'logout-all',
// POST: /api/renew-token
'renew-token.post': 'renew-token',
// GET: /api/profile
'profile.get': 'profile',
// PATCH: /api/profile
'profile.patch': 'profile',
},
},
},
})
You can change route names or disable them entirely by setting their value to false
. Keep in mind that this may significantly affect certain functionalities in the dashboard. It is recommended to do so only if you intend to use a custom dashboard interface or solely rely on the Pruvious API.
Last updated on December 31, 2023 at 21:55