2022-07-26 04:40:16 +02:00
|
|
|
import { Request, Response } from 'express';
|
2022-10-25 06:41:47 +02:00
|
|
|
import { ApiSuccess, getSuccessResponse } from '@/utils';
|
|
|
|
import { toApiModel } from '@helpers/api-model';
|
|
|
|
import { service } from '@services/index';
|
|
|
|
import { validation, TypedRequest } from '@validations/index';
|
2022-07-26 04:40:16 +02:00
|
|
|
import packageJson from '../package.json';
|
|
|
|
|
2022-10-25 06:41:47 +02:00
|
|
|
const login = async (
|
|
|
|
req: TypedRequest<typeof validation.auth.login>,
|
|
|
|
res: Response
|
|
|
|
) => {
|
2022-07-26 04:40:16 +02:00
|
|
|
const { username } = req.body;
|
2022-10-25 06:41:47 +02:00
|
|
|
const user = await service.auth.login({ username });
|
2022-07-26 04:40:16 +02:00
|
|
|
|
2022-10-25 06:41:47 +02:00
|
|
|
const success = ApiSuccess.ok({ data: toApiModel.users([user])[0] });
|
|
|
|
return res.status(success.statusCode).json(getSuccessResponse(success));
|
2022-07-26 04:40:16 +02:00
|
|
|
};
|
|
|
|
|
2022-10-25 06:41:47 +02:00
|
|
|
const register = async (
|
|
|
|
req: TypedRequest<typeof validation.auth.register>,
|
|
|
|
res: Response
|
|
|
|
) => {
|
2022-07-26 04:40:16 +02:00
|
|
|
const { username, password } = req.body;
|
2022-10-25 06:41:47 +02:00
|
|
|
const user = await service.auth.register({
|
2022-07-26 04:40:16 +02:00
|
|
|
password,
|
|
|
|
username,
|
|
|
|
});
|
|
|
|
|
2022-10-25 06:41:47 +02:00
|
|
|
const success = ApiSuccess.ok({ data: toApiModel.users([user])[0] });
|
|
|
|
return res.status(success.statusCode).json(getSuccessResponse(success));
|
2022-07-26 04:40:16 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const logout = async (req: Request, res: Response) => {
|
2022-10-25 06:41:47 +02:00
|
|
|
await service.auth.logout({
|
|
|
|
user: req.authUser,
|
|
|
|
});
|
|
|
|
|
|
|
|
const success = ApiSuccess.noContent({ data: {} });
|
|
|
|
return res.status(success.statusCode).json(getSuccessResponse(success));
|
2022-07-26 04:40:16 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const ping = async (_req: Request, res: Response) => {
|
|
|
|
return res.status(200).json(
|
|
|
|
getSuccessResponse({
|
|
|
|
data: {
|
|
|
|
description: packageJson.description,
|
|
|
|
name: packageJson.name,
|
|
|
|
version: packageJson.version,
|
|
|
|
},
|
|
|
|
statusCode: 200,
|
|
|
|
})
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2022-10-25 06:41:47 +02:00
|
|
|
const refresh = async (
|
|
|
|
req: TypedRequest<typeof validation.auth.refresh>,
|
|
|
|
res: Response
|
|
|
|
) => {
|
|
|
|
const refresh = await service.auth.refresh({
|
2022-07-26 04:40:16 +02:00
|
|
|
refreshToken: req.body.refreshToken,
|
|
|
|
});
|
|
|
|
|
2022-10-25 06:41:47 +02:00
|
|
|
const success = ApiSuccess.ok({ data: refresh });
|
|
|
|
return res.status(success.statusCode).json(getSuccessResponse(success));
|
2022-07-26 04:40:16 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export const authController = { login, logout, ping, refresh, register };
|