-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapikey-controller.ts
More file actions
49 lines (42 loc) · 1.26 KB
/
apikey-controller.ts
File metadata and controls
49 lines (42 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { Request, Response } from 'express';
import { successResponse, errorResponse } from '../utils/response';
import UserRepository from '../repositories/user-repository';
import { generateApiKey } from '../utils/auth';
import Users from '../models/user';
import { InferAttributes } from 'sequelize';
type UserType = InferAttributes<Users>;
interface AuthRequest extends Request {
user?: UserType;
}
export const getApiKey = async (req: AuthRequest, res: Response) => {
try {
if (!req.user) {
return errorResponse(res, 'Unauthorized', 401);
}
return successResponse(
res,
{ apikey: req.user.apikey },
'User details retrieved',
);
} catch (error) {
console.error(error);
return errorResponse(res, 'Unauthorized', 401);
}
};
export const regenerateApiKey = async (req: AuthRequest, res: Response) => {
try {
if (!req.user) {
return errorResponse(res, 'Unauthorized', 401);
}
const newApiKey = await generateApiKey();
await UserRepository.update({ id: req.user.id }, { apikey: newApiKey });
return successResponse(
res,
{ apikey: newApiKey },
'User details retrieved',
);
} catch (error) {
console.error(error);
return errorResponse(res, 'Unauthorized', 401);
}
};