sweet-auth v1.0.3
sweet-auth
handles following backend tasks for you:
- Creating user accounts
- Logging into accounts
- Authorizing subsequent browser requests
- Updating user passwords
- Removing user accounts
- Logging out from accounts
✔ No database required. Fully file based.
✔ Works with Express.
✔ Lightweight. Zero configurations.
API
API (req.user.*) | Effect | Returns |
---|---|---|
create (email, password) | Creates a new user | A promise with success & failure handlers |
authenticate (email, password) | Validates user login. Upon success, the client is given a token valid for 3 days. | A promise with success & failure handlers |
isAuthorized | Becomes true if the user has logged in with a valid token. | N/A |
Holds the user's email if logged in | N/A | |
deauthenticate () | Logs out the current user. Clear the token. | A promise with success & failure handlers |
updatePassword (currentPassword, newPassword) | Updates the current password of the logged in user. | A promise with success & failure handlers |
remove (password) | Removes the account of the logged in user. | A promise with success & failure handlers |
QUICK START
Install sweet-auth
package:
npm i sweet-auth
Add sweet-auth
to your express app:
const express = require('express')
const app = express()
const sweetAuth = require('sweet-auth')
app.use(sweetAuth)
app.use(express.urlencoded()) // allows reading POST request data
Validate incoming requests for your protected pages with isAuthorized
flag:
app.get('/private-page', (req, res) => {
if (req.user.isAuthorized) {
// user is logged in! send the requested page
// you can access req.user.email
}
else {
// user not logged in. redirect to login page
}
})
In order to be authorized, a user must be registered and logged in first:
app.post('/signup', (req, res) => {
// extract sign up form data
let email = req.body.email
let password = req.body.password
req.user.create(email, password)
.then(
() => {
// tell user account is created
// probably redirect to the login page
},
(err) => {
// tell user something went wrong
}
)
})
Then handle the login:
app.post('/api/login', (req, res) => {
// extract html form data
let email = req.body.email
let password = req.body.password
req.user.authenticate(email, password)
.then(
() => {
// authentication success.
// redirect to home page.
},
(err) => {
// authentication failed.
// send error to client.
}
)
})
Upoun a successfull login, a token will be issued to the client which will be used to authenticate future requests. This token will be expired after 3 days.
Don't forget to checkout the demo
FAQ
Where does it store user data?
User data are stored under
sweet-auth
directory inside your project.How secure is this?
sweet-auth
doesn't store actual passwords, but their hashes. So it's pretty secure.How many users can it handle?
sweet-auth
can handle a good load of users for your web app. Unless you are planning to build the next big Facebook, you are good to go withsweet-auth
.