Extending Meteor Accounts (login system)
Tags: javascript, meteor
Published: 2021-08-22 08:58:36

This is an update of an article that was originally posted to, now defunct, meteorhacks.com. [Here is the archived version.](https://web.archive.org/web/20160913210817/https://meteorhacks.com/extending-meteor-accounts/)
This code has been implemented on Meteor 2.3.5.

Meteor has a really good user authentication system called Accounts. It is so powerful and has built in support for login using password, facebook, twitter and other oauth providers (and you can find many more options on [Atmosphere](https://www.atmospherejs.com)). Another important fact is that Meteor Accounts is tightly coupled with core meteor services to provide great level of security.

But, what if you want to add a custom authentication method? Adding a custom authentication method is also pretty simple. Let’s find out how.

In this tutorial I’ll be creating a custom authentication system for administration purpose of our meteor app.

> This is not a properly implemented authentication system! It is only for demonstration purposes!

## Getting started

1. Create a meteor app with `meteor create admin --blaze`
2. Add `accounts-ui` package with `meteor add accounts-ui`
3. modify `index.html` with following code, we simple add `loginButtons` helper from the `account-ui` package and remove the `info` template:

```html
<head>
  <title>admin</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}
</body>

<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
  {{> loginButtons}}
  <input type="button" value="Click" />
</template>
```

Now, when you start you app you’ll see something like below (dont worry about the message in red):

![Initial look of the app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pd57fv1mzjahsob1upj6.png)

## Adding logging handler
Now we need to register a login handler for our admin authentication system. This is a server side functionality, so create following content in `server/main.js`. See comments for more information.

```javascript
import { Accounts } from 'meteor/accounts-base';

Accounts.registerLoginHandler(function(loginRequest) {
  // There are multiple login handlers in meteor.
  // A login request go through all these handlers to find it's login handler
  // so in our login handler, we only consider login requests which has admin field
  if(!loginRequest.admin) {
    return undefined;
  }

  // Our authentication logic 😉
  if(loginRequest.password !== 'admin-password') {
    return null;
  }

  // We create a admin user if none exists, and get the userId
  let userId = null;
  const user = Meteor.users.findOne({ username: 'admin' }, { fields: { _id: 1 } });
  if(!user) {
    userId = Meteor.users.insert({username: 'admin'});
  } else {
    userId = user._id;
  }

  // Send logged in user's user id 🎉
  return {
    userId
  }
});
```

Now we are done with our basic `loginHandler`.

## Client side login functionality
Add following content to the main client js file (`client/main.js`). See comments in the code:

```javascript
import { Meteor } from 'meteor/meteor';

Meteor.loginAsAdmin = function(password, callback) {
  // Create a login request with admin: true, so our loginHandler can handle this request
  const loginRequest = { admin: true, password: password };

  // Send the login request 📤
  Accounts.callLoginMethod({
    methodArguments: [loginRequest],
    userCallback: callback
  });
};
```

Now we’ve added our admin login system. Just call `loginAsAdmin` method in the browser console. You’ll see admin user has logged in.
```bash
Meteor.loginAsAdmin('admin-password');
```

![login via console result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmy313d215cohmh4736d.png)


As you can see we are now logged in as admin user.

That is it! To look back we did:
* We were trying to create a administration login system for our app
* Then, we added a new `loginHandler` for that
* We added a client side function to invoke the login request too

Profit!

You can find this [completed application on GitHub](https://github.com/StorytellerCZ/meteor-sample-admin-login-handler).

Isn’t it is easy to add a new authentication system/method in meteor? Let me know your thoughts!

--------
If you like my work, please support me on [GitHub Sponsors ❤️](https://github.com/sponsors/StorytellerCZ).