You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.7 KiB
54 lines
1.7 KiB
import jwt from 'jsonwebtoken'; |
|
import ErrorType from '../error/types.error.js'; |
|
import serverConfig from '../configuration/server.config.js'; |
|
|
|
const signin = async (request, reply) => { |
|
const user = request.user; |
|
if (!user.message) { |
|
request.log.info(`User ${user.username} authenticated.`); |
|
try { |
|
const token = await generateToken(user); |
|
const body = { |
|
success: true, |
|
message: `User ${user.username} authenticated.`, |
|
token |
|
}; |
|
reply.code(200).send(body); |
|
} catch (e) { |
|
request.log.error(e); |
|
return reply.code(500).send({ message: ErrorType.TECHNICAL_UNKNOWN }); |
|
} |
|
} else { |
|
request.log.info(`User ${user.username} not authenticated.`); |
|
switch (user.message) { |
|
case ErrorType.FUNCTIONAL_NOT_FOUND: |
|
case ErrorType.FUNCTIONAL_FORBIDDEN: |
|
return reply.code(401).send({ message: 'Bad user or password' }); |
|
case ErrorType.FUNCTIONAL_EXPIRED_ACCESS: |
|
return reply.code(401).send({ message: ErrorType.FUNCTIONAL_EXPIRED_ACCESS }); |
|
case ErrorType.FUNCTIONAL_EXPIRED_PASSWORD: |
|
return reply.code(419).send({ message: ErrorType.FUNCTIONAL_EXPIRED_PASSWORD }); |
|
default: |
|
request.log.error(`User ${user.username} login internal error.`); |
|
return reply.code(500).send({ message: ErrorType.TECHNICAL_UNKNOWN }); |
|
} |
|
} |
|
}; |
|
|
|
async function generateToken(user) { |
|
const timestamp = new Date(); |
|
const iat = timestamp.getTime(); |
|
timestamp.setSeconds(timestamp.getSeconds() + (365 * 24 * 60 * 60)); |
|
const expiration = timestamp.getTime() |
|
const payload = { |
|
sub: user.username, |
|
iat, |
|
role: 'web_anon', |
|
exp: expiration |
|
}; |
|
return jwt.sign(payload, serverConfig.secret); |
|
} |
|
|
|
export default { |
|
signin |
|
};
|
|
|