npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bithero/simple-vue-auth

v0.1.0

Published

[![Npm package version](https://badgen.net/npm/v/@bithero/simple-vue-auth)](https://npmjs.com/package/@bithero/simple-vue-auth) [![Npm package license](https://badgen.net/npm/license/@bithero/simple-vue-auth)](https://codeark.it/Bithero-Agency-JS/simple-v

Downloads

5

Readme

simple-vue-auth

Npm package version Npm package license Npm package types

A set of vue components for authorization

License

This project is licensed under AGPL-3.0-or-later. See the LICENSE file for more informations.

Usage

For a detailed example, see the example folder.

Installation into an Vue App

First install the plugin and add it to your app:

import { AuthClient, createAuth } from '@bithero/simple-vue-auth';

let client: AuthClient = /* ... */;
app.use(createAuth(client, {
    loginRedirect: '/login'
}));

This does multiple things:

  1. It checks the current session via the provided client.
  2. Provides the auth object via globalProperties under the AUTH_TOKEN key.
  3. Enables injection via the AUTH_INJECTION_KEY.
  4. Sets a global value so non-vue code can access it as well via getGlobalClient.

Due to the global, multiple instantiations will overwrite the value. The global is needed for authGuard to work correctly; so it is advised to only ever install the plugin once.

Auth Clients

An auth client is an class (or object) that implements the interface AuthClient. The plugin (or AuthVueClient), to do the actual authentication.

import { AuthClient } from '@bithero/simple-vue-auth';
type MockUser = { name: string };
class MockClient implements AuthClient<MockUser> {
    private user: MockUser | null = null;
    async login(params: any): Promise<void> {
        // Handles the login.
        // The parameters are the one provided by your application.
        // This method should fill in neccessary caches like the
        // user field above, and throw if any issue arieses.
    }
    async logout(): Promise<void> {
        // Handles the logout.
        // You should cleanup all cached data from a login here.
    }
    async checkSession(): Promise<void> {
        // Called on app startup to determine if already logged in.
        // In other words: it checks a users "session". Effectivly
        // the client should after this be the same state as after
        // a call to '.login()'.
    }
    async getUser(): Promise<MockUser | null> {
        // Accessor to the user object.
        // Can be as complex or simple as you need it; since we
        // cache the user inside the client, this is as simple
        // as a return. Other clients might do an api request here.
        return this.user;
    }
}

Using the AuthVueClient

Once installed, vue components can access all functionality via the useAuth() composite.

The useAuth function returns an object from type AuthVueClient<TUser> where TUser is the same as the generic argument given to useAuth, and defaults to any.

import { AuthClient, AuthVueClient, useAuth } from '@bithero/simple-vue-auth';

// `auth` gives access to all functions of the library
const auth: AuthVueClient = useAuth<MockUser>();

// Starts a login; you can provide any value's you want as parameters,
// they'll simply be given to your `AuthClient`'s login method.
await auth.login(/*login-params*/);

// Like `login` (the first parameter is given to it), but if successfull,
// it redirects to either a stored route, or the route given in the call.
//
// Uses vue-router if available, else uses `window.location`.
await auth.loginAndRedirect(/*login-params*/, /*default route*/);

// Simple way of refreshing the cached user object in `AuthVueClient`
// by calling `AuchClient.getUser`.
await auth.refreshUser();

// Manually check the session. Will not redirect on failure, only update's
// internal state, like if we have an valid authentication & user.
await auth.checkSession();

// Redirects to the login route specified in the call to `createAuth`,
// and stores the provided route as route to return to
// when using `loginAndRedirect`.
//
// Uses vue-router if available, else uses `window.location`.
//
// Stores the "returnTo" route inmemory if vue-router is available,
// else uses `sessionStorage`.
auth.redirect(/*route*/);

// With this you'll get a simple promise that resolves only
// once the authflow is finished; or in other words: the loading has finished.
await auth.waitUntilLoaded();

// Returns the underlaying client as provided in the call to `createAuth`.
const client: AuthClient = auth.getClient();

// -----
// Now some properties one can access; all of them are reactive `Ref`'s.

// Flag that, when true, expresses that the authentication flow is fully loaded
// and all other properties are stable.
auth.isLoading;

// Flag to express if an authenticated user is present; false otherwise.
auth.isAuthenticated;

// Contains the currently cached user object, and is of the type `TUser`, or
// in other words, the type provided by you to the call to `useAuth`.
// Can be refreshed by a call to `refreshUser`, as mentioned above.
auth.user;

// Contains the last error
auth.error;

Since vue-router is optional, the plugin uses browser-equivalents to provide some of the libraries functionalities; like storing the "returnTo" route in sessionStorage or, more important, uses window.location to redirect to certain routes. This feature is only useable with raw string routes or path locations and will not work with named routes!

Guards

To guard vue-router routes from being accessed when not authenticated, one can use authGuard for the beforeEnter property of an route:

import { authGuard } from '@bithero/simple-vue-auth';

createRouter({
    routes: {
        { /* ... */, beforeEnter: authGuard, },
    }
});

This uses the globally stored AuthVueClient, waits until all is loaded via waitUntilLoaded, and checks if a user is authenticated. If not, it calls redirect() with the route the router was about to enter as argument, so a call to loginAndRedirect() can put the user back where they wanted to go.