Configuration¶
Properties¶
Properties are set when the service is instantiated, for example:
app.use(kryptonAuth({ mailFrom: '"Fred Foo 👻" <foo@example.com>' }));
-
class
Properties
()¶ interface, exported from
config
Properties for configuring Krypton Authentication.
-
Properties.
algorithm
¶ type: Algorithm
JSON Web Token signing algorithm. The default value is
RS256
.
-
Properties.
authTokenExpiryTime
¶ type: number
Time until the authentication token expires in milliseconds. The default value is
15 * 60 * 1000
(15 minutes). Call therefreshToken
mutation to renew it.
-
Properties.
dbAddress
¶ type: string
MongoDB server address. Example:
mongodb://user:password@host.com:27017/DBname
. The default value ismongodb://localhost:27017/users
.
-
Properties.
dbConfig
¶ type: <TODO>
MongoDB config, only if you need to set a special configuration for MongoDB. The default configuration used by Krypton aims to make the system resilient to database connection problems. Krypton will try to reconnect automatically to MongoDB. You can adapt this behavior by tweaking this property. Example:
{reconnectInterval: 500}
.
-
Properties.
eventEmitter
¶ type: EventEmitter
Event emitter transmitting krypton errors on “error” event and email errors on “email-error” event.
-
Properties.
extendedSchema
¶ type: object
Custom user model, see Extended Schema.
-
Properties.
graphiql
¶ type: boolean
Enable or disable GraphiQL IDE. The default value is true. In the page header, you will find an input field to include your auth token and be able to make authenticated requests.
Note: Include your auth token directly, no need to precede it with
Bearer
.
-
Properties.
host
¶ type: string
Public URL of the service.
Very important for use in production: when users receive emails to reset their password or to confirm their account, the links will be pointing to the
host
of the service. The default value isnull
. Whennull
, Krypton Authentication uses the address located inreq.headers.host
that can correspond to the machinelocalhost
.
-
Properties.
mailFrom
¶ type: string|Address
Sender address displayed in emails sent to users. The default value is
undefined
.app.use(kryptonAuth({ mailFrom: '"Fred Foo 👻" <foo@example.com>' })); // or app.use(kryptonAuth({ mailFrom: { name: "Fred Foo 👻"; address: "foo@example.com"; } }));
-
Properties.
nodemailerConfig
¶ type: any
A Nodemailer configuration used to send administration emails to users. The default value is
undefined
.const nodemailerConfig = { host: "smtp.example.email", port: 587, secure: false, // true for 465, false for other ports auth: { user: credentials.user, pass: credentials.pass } }; app.use('/auth', kryptonAuth({ nodemailerConfig }));
If left
undefined
a Nodemailer test account is set automatically. It will print URL links on the command line to let you preview the emails that would have normally been sent.Message sent: <365ea109-f645-e3a1-5e08-48e4c8a37bcb@JohannC> Preview URL: https://ethereal.email/message/Xklk07cTigz7mlaKXkllHsRk0gyz7kuxAAAAAWLgnFDcJwUFl8MZ-h1shKs
-
Properties.
notificationPageTemplate
¶ type: string
The filepath to the EJS template file of notification page. This library include a simple one located in ./nodes_module/krypton-auth/lib/templates/pages/Notification.ejs. You can create another, just gives the file path to the EJS file you wish to send. Here are the locals you can use inside the template:
notifications
:Array
ofObject
notification. Each notification object contains two properties:type
:String Enum
either equal tosuccess
-warning
-error
-info
message
:String
property containing the notificaiton message
-
Properties.
onReady
¶ type: <TODO>
The callback that will be executed when service is launched and ready. The default value is:
() => console.log("Krypton Authentication is ready.");
.
-
Properties.
privateKey
¶ type: string
The private key of the service. If both privateKey and privateKeyFilePath are undefined, it will create one under
your-app/private-key.txt
all along with the public key. You can retrieve the pair of keys created for re-use afterward.
-
Properties.
privateKeyFilePath
¶ type: string
The file path to the private key of the service. If both privateKey and privateKeyFilePath are undefined, it will create one under
your-app/private-key.txt
all along with the public key. You can retrieve the pair of keys created for re-use afterward.
-
Properties.
publicKey
¶ type: string
The public key of the service. If both publicKey and publicKeyFilePath are undefined, it will create one under
your-app/public-key.txt
all along with the private key. You can retrieve the pair of keys created for re-use afterward.
-
Properties.
publicKeyFilePath
¶ type: string
The file path to the public key of the service. If both publicKey and publicKeyFilePath are undefined, it will create one under
your-app/public-key.txt
all along with the private key. You can retrieve the pair of keys created for re-use afterward.
-
Properties.
refreshTokenExpiryTime
¶ type: number
The time until the refresh token expires in milliseconds. If a user is inactive during this period he will have to login in order to get a new refresh token. The default value is
7 * 24 * 60 * 60 * 1000
(7 days).Note: before the refresh token has expired, you can call the refreshToken mutation. Both the auth token and the refresh token will be renewed and your user won’t face any service interruption.
-
Properties.
resetPasswordEmailTemplate
¶ type: string
The file path to the EJS template file of the email to reset forgotten password. This library include a simple one located in ./nodes_module/krypton-auth/lib/templates/emails/ResetPassword.ejs. You can create another, just gives the file path to the EJS file you wish to send. Here are the locals you can use inside the template:
user
- The current user:<p>Hi <%= user.fistName %></p>
link
- The link to the reset form:Click here: <a href="<%= link %>"><%= link %>
-
Properties.
resetPasswordFormTemplate
¶ type: string
The file path to the EJS template file of the reset password form. This library include a simple one located in ./nodes_module/krypton-auth/lib/templates/forms/ResetPassword.ejs. You can create another, just gives the file path to the EJS file you wish to send. Here are the locals you can use inside the template:
link
: The link of the API:xhr.open("POST", '<%= link %>')
token
: The reset password token to include in the GraphQL resetMyPassword mutation (example below)
const xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("POST", '<%= link %>'); xhr.setRequestHeader("Content-Type", "application/json"); const mutation = { query: `mutation{resetMyPassword(password:"${formData.get("password")}" passwordRecoveryToken:<%= token %>){ notifications{ type message } }}` } xhr.send(JSON.stringify(mutation));
-
Properties.
verifyEmailTemplate
¶ type: string
The filepath to the EJS template file of the email to verify user account. This library include a simple one located in ./nodes_module/krypton-auth/lib/templates/emails/VerifyEmail.ejs. You can create another, just gives the file path to the EJS file you wish to send. Here are the locals you can use inside the template:
user
- The current user:<p>Hi <%= user.firstName %></p>
link
- The verification link:Click here: <a href="<%= link %>"><%= link %>
-
Error Handling¶
Krypton Authentication provides an eventBus
to notify eventual errors. The email-error
event is related to unsent emails. The error
event is related to any other kind of errors.
const kryptonAuth = require('@krypton-org/krypton-auth');
const express = require('express');
const EventEmitter = require('events');
const app = express();
const eventEmitter = new EventEmitter();
eventEmitter.on('email-error', (email) => {
console.log("Email not sent: "+email)
});
eventEmitter.on('error', (err) => {
console.log("An error occured: "+err)
});
app.use('/auth', kryptonAuth({ eventEmitter }));
Extended Schema¶
The true power of Krypton Authentication is the ability to customize the user model to your own needs.
To achieve that you simply need to pass the different Mongoose Schema fields you want to add. Under the hood, those extra fields will be converted into GraphQL types thanks to graphql-compose-mongoose and added to the different queries and mutations automatically.
Mongoose Schema is very powerful, you can define the field type, default value, custom validators & error messages to display, if it is required, if it should be unique. Please refer to its documentation.
Note
In each schema field, you can define the isPrivate
attribute. It is a Boolean
attribute telling whether or not this field can be accessible by public queries
like userById, userByOne, etc.
For example, you could pass the following extendedSchema
:
const extendedSchema = {
firstName: {
type: String,
required: false,
maxlength: 256,
validate: {
validator: v => v.length >= 2,
message: () => "A minimum of 2 letters are required for your first name!",
},
isPublic: false
},
lastName: {
type: String,
required: false,
maxlength: 256,
validate: {
validator: v => v.length >= 2,
message: () => "A minimum of 2 letters are required for your last name!",
},
isPublic: false
},
gender: {
type: String,
required: true,
enum: ["M", "Mrs", "Other"],
isPublic: true
},
age: {
type: Number,
required: true,
isPublic: true,
min: 0
},
receiveNewsletter: {
type: Boolean,
required: true,
default: false,
isPublic: false
}
};
app.use(kryptonAuth({ extendedSchema }));