Skip to main content

Base User Class

The base user class implements User Interface

Please note we're assuming that you followed up the Creating Defining current user instructions.

Login#

Log the user in and store its data inside storage driver.

login(userData: UserInfo);

The UserInfo interface is simply any object that has the user data with accessToken property that holds the current access token.

Example#

import user from 'user';
// login the useruser.login({    name: 'Hasan',    email: 'hassaonzohdy@gmail.com',    accessToken: 'ASDFHY5432QWSADFHY0', // please note this is very important to be added when calling the login method});

Usually the login method is called after the login form submission, or when creating a user.

The user data will be stored in the current cache driver;

LoginForm.tsx
import user from 'user';// some login serviceimport { login } from './../servies/auth';import { Form, PasswordInput, EmailInput, SubmitButton } from 'mongez/from';
export default function LoginPage() {    const submitLogin = e => {        login(e.target).then(response => {                    user.login(response.data.user); // now the user data is stored in the storage driver        });    };
    return (        <>            <Form onSubmit={submitLogin}>                <EmailInput name="email" placeholder="Email Address" label="Email Address" required />                <PasswordInput minLength={8} name="password" placeholder="Password" label="Password" required />                <SubmitButton>Login</SubmitButton>            </Form>        </>    )}

Check If user is already logged in#

Determine whether the user is currently logged in.

isLoggedIn(): boolean;

Example#

import user from 'user';
if (user.isLoggedIn()) {    // do something} else {    // do other things}

Check If user is not logged in#

Determine whether the user is currently not logged in.

isNotLoggedIn(): boolean;
import user from 'user';
if (user.isNotLoggedIn()) {    // do something} else {    // do other things}

Logout#

Clear user's data from the storage driver.

logout(): void;

Example#

Now let's remove the user's data from our current storage driver

Header.tsx
import user from 'user';// some logout serviceimport { logout } from './../servies/auth';
import { navigateTo } from 'mongez/router';
export default function header() {    const performLogout = e => {        // clear user's data        user.logout();
        // send API request to clear the user's data        logout();
        // navigate to home page or whatever page you want        navigateTo('/');    };
    return (        <>            <buton onClick={performLogout}>Logout</button>        </>    )}

The user.logout method will clear the user's data from the storage driver and clear the current user's data in the runtime.

Get current access token#

Get current user access token.

getAccessToken(): string;

Example#

import user from 'user';
// Get current access tokenconsole.log(user.getAccessToken()); // Will be something like SDFGHTR3E2WQSCDVBGHYT543E2WQSDCVG

Update current access token#

Update the current access token in the storage driver.

updateAccessToken(newAccessToken: string): void;

Example#

import user from 'user';
user.updateAccessToken('ADCFGHYT543EWQSCVBNHJY65T43EWSDCVBNJHYTRE');
console.log(user.getAccessToken()); // ADCFGHYT543EWQSCVBNHJY65T43EWSDCVBNJHYTRE

Get current cache key#

Return the cache key name that will be used to store user's data in the storage driver.

getCacheKey(): string;

Default is user, can be set in User Configurations.

Example#

import user from 'user';
console.log(user.getCacheKey()); // user

Update user data#

Update the entire user's data in the storage driver

update(newInfo: UserInfo): void;

Example#

import user from 'user';
// some dummy data for demo purposes.user.update({    name: {        first: 'Hasan',    },    address: {        street: {            number: 10,            name: 'My Street'        }    }});
tip

If the passed object to the update method does not have the accessToken key, then the current access token will remain the same, if passed then it will be overrriden.

Updating single value#

Update only single key in the user's data.

set(key: string, value: any): void;

Example#

import user from 'user';
user.set('name', 'Mohammad');

Dot notation can be used to update nested object data

import user from 'user';
user.set('address.city', 'Cairot');

Getting value from user data#

Get a value from stored data.

get(key: string, defaultValue: any): any;

Example#

import user from 'user';
// get some value based on the given key
user.get('name'); // for example: Hasan

If the given key does not exist, null will be returned.

import user from 'user';
user.get('role'); // null

If the given key does not exist, we can set a default value to be returned instead of null.

import user from 'user';
user.get('role', 'root'); // root

The get method works wih dot notation syntax to get a value from nested object.

import user from 'user';
user.update({    name: {        first: 'Hasan',    },    address: {        street: {            number: 10,            name: 'My Street'        }    }});
user.get('name.first'); // Hasanuser.get('name'); // returns the entire object: {first: Hasan}user.get('address.street.name'); // My Street

Listening For Update#

Track down any user data manipulation using event listeners.

When a key's value is changed, we can detect that change using by listening to theat key.

 onChange(key: string, callback: Function);

The callback function receives the new and old values as function arguments respectively.

Example#

import user from 'user';
user.onChange('name', (newValue, oldValue) => {    console.log(oldValue); // Hasan    console.log(newValue); // Mohammad});
// now let's update our data
user.set('name', 'Mohammad'); // once this method is called, the callback will be triggerd
tip

Be aware that the order matters, the onChange method must be defined earlier before updating any data or it won't work as expected.

Getting all user's data#

To retreive the entire object of the current user, all method can be used.

all(): UserInfo;

Example#

import user from 'user';
user.all(); // the entire object of current user's data

User Interface#

The Base User implements UserInterface.

interface UserInterface {    /**     * Get cache key     *      * @returns {string}     */    getCacheKey(): string;
    /**     * Check if user is logged in     *      * @returns {boolean}     */    isLoggedIn(): boolean;
    /**     * Check if user is not logged in     *      * @returns {boolean}     */    isNotLoggedIn(): boolean;
    /**     * Log the user in      * It will store the data in the storage engine i.e Local Storage     * But will not make the ajax request     *      * @param  {UserInfo} userData      * @returns {void}     */    login(userData: UserInfo);
    /**     * Log the user out     */    logout();
    /**     * Get user access token     *      * @returns {string}     */    getAccessToken(): string
    /**     * Update current access token     *      * @param {string} newAccessToken      */     updateAccessToken(newAccessToken: string): void;
    /**     * Set the given value     *      * @param   {string} key       * @param   {any} value     */    set(key: string, value: any);
    /**     * Reset user info excluding access token if not provided with the given data     *       * @param {object} newInfo      */    update(newInfo: UserInfo);
    /**     * Get value for the given key, otherwise return default value     *      * @param   {string} key       * @param   {any} defaultValue     * @returns {any}       */    get(key: string, defaultValue: any): any;
    /**     * Set user permissions list       */    setPermissions(permissions: object);
    /**     * Check if user has access to the given permission role      *      * @param {string} permission     * @returns {boolean}     */    can(permission: string): boolean;
    /**     * Detect when a value is changed     *      * @param {string} key      * @param {Function} callback     * @returns {void}     */    onChange(key: string, callback: Function);
    /**     * Check if the given key is being watched     *      * @param  {string} key     * @returns {boolean}     */    isBeingWatched(key: string): boolean;
    /**     * Get all user data     *      * @returns {UserInfo}     */    all(): UserInfo;}

User Info Interface#

The user interface is the shape of the data that must be passed to the user login or data update.

interface UserInfo {    /**     * Current access token     */    accessToken?: string;    /**     * Any other data     */    [key: string]: any;};