Skip to content

Commit cf173c5

Browse files
committed
added sample auth controller for login
1 parent b7138e8 commit cf173c5

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

server/controllers/auth.controller.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import jwt from 'jsonwebtoken';
2+
import httpStatus from 'http-status';
3+
import APIError from '../helpers/APIError';
4+
import config from '../../config/config';
5+
6+
// sample user, used for authentication
7+
const user = {
8+
username: 'react',
9+
password: 'express',
10+
};
11+
12+
/**
13+
* Returns jwt token if valid username and password is provided
14+
* @param req
15+
* @param res
16+
* @param next
17+
* @returns {*}
18+
*/
19+
function login(req, res, next) {
20+
// Ideally you'll fetch this from the db
21+
// Idea here was to show how jwt works with simplicity
22+
if (req.body.username === user.username && req.body.password === user.password) {
23+
const token = jwt.sign({
24+
username: user.username,
25+
expiresIn: 3600,
26+
}, config.jwtSecret);
27+
return res.json({
28+
token,
29+
username: user.username,
30+
});
31+
}
32+
33+
const err = new APIError('Authentication error', httpStatus.UNAUTHORIZED, true);
34+
return next(err);
35+
}
36+
37+
/**
38+
* This is a protected route. Will return random number only if jwt token is provided in header.
39+
* @param req
40+
* @param res
41+
* @returns {*}
42+
*/
43+
function getRandomNumber(req, res) {
44+
// req.user is assigned by jwt middleware if valid token is provided
45+
return res.json({
46+
user: req.user,
47+
num: Math.random() * 100,
48+
});
49+
}
50+
51+
export default { login, getRandomNumber };

0 commit comments

Comments
 (0)