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.
65 lines
1.7 KiB
65 lines
1.7 KiB
import DOMPurify from 'isomorphic-dompurify'
|
|
import bcrypt from 'bcrypt'
|
|
|
|
import UserRepository from './../../repositories/userRepository.js'
|
|
import loginSchema from './../../schemas/auth/login.js'
|
|
|
|
/**
|
|
* handle auth
|
|
*
|
|
* @author Björn Hase, Tentakelfabrik
|
|
* @license http://opensource.org/licenses/MIT The MIT License
|
|
* @link https://github.com/tentakelfabrik/fastify-lowdb-riotjs-lessons-learned
|
|
*
|
|
*/
|
|
|
|
export default async function(fastify, opts)
|
|
{
|
|
/**
|
|
* auth
|
|
*
|
|
* @param {object} request
|
|
* @param {object} response
|
|
*
|
|
*/
|
|
fastify.post('/auth', loginSchema, async function (request, reply)
|
|
{
|
|
let { username, password } = request.body
|
|
|
|
// strip crap from strings
|
|
username = DOMPurify.sanitize(username)
|
|
password = DOMPurify.sanitize(password)
|
|
|
|
const userRepository = new UserRepository()
|
|
const user = await userRepository.findOneByUsername(username)
|
|
|
|
// add header for json
|
|
reply.header('Content-Type', 'application/json; charset=utf-8')
|
|
|
|
// user not found
|
|
if (!user) {
|
|
return reply
|
|
.code(404)
|
|
.send()
|
|
}
|
|
|
|
// password wrong
|
|
if (!bcrypt.compareSync(password, user.password)) {
|
|
return reply
|
|
.code(401)
|
|
.send()
|
|
}
|
|
|
|
// setting session to store and set cookie
|
|
request.sessionStore.set(request.session.sessionId, request.session, async function() {
|
|
user.sessionId = request.session.sessionId
|
|
|
|
await userRepository.update(user)
|
|
|
|
// send 200 and send set-token
|
|
reply
|
|
.code(200)
|
|
.send()
|
|
})
|
|
})
|
|
} |