File size: 8,136 Bytes
aa8f65d
 
 
 
 
 
 
 
 
 
bb95664
 
aa8f65d
bb95664
 
 
 
 
aa8f65d
bb95664
 
 
 
aa8f65d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abdeed6
 
 
 
aa8f65d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abdeed6
 
 
 
aa8f65d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
'use strict';

/**
 * Admin Auth Controller Unit Tests
 * Tests for admin authentication endpoints
 */

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

process.env.ADMIN_JWT_SECRET = 'test-secret-for-unit-tests';

// Mock dependencies before requiring the controller
const mockPool = {
  query: jest.fn(),
  connect: jest.fn(() => ({
    query: jest.fn(),
    release: jest.fn()
  }))
};

jest.mock('../db', () => ({
  getPool: jest.fn(() => mockPool)
}));

const authController = require('../controllers/auth.controller');
const { getPool } = require('../db');

describe('Admin Auth Controller', () => {
  let mockReq;
  let mockRes;
  let mockPool;

  beforeEach(() => {
    mockReq = {
      body: {},
      user: {}
    };
    mockRes = {
      status: jest.fn().mockReturnThis(),
      json: jest.fn().mockReturnThis()
    };
    mockPool = getPool();
    jest.clearAllMocks();
  });

  describe('register', () => {
    it('should register a new admin successfully', async () => {
      mockReq.body = {
        username: 'admin1',
        email: 'admin@example.com',
        password: 'SecurePass123!',
        name: 'Admin User'
      };

      // No existing admin
      mockPool.query.mockResolvedValueOnce({ rows: [] });
      
      // Insert returns new admin
      const newAdmin = {
        id: 'admin-id-1',
        username: 'admin1',
        email: 'admin@example.com',
        name: 'Admin User',
        permissions: ['all']
      };
      mockPool.query.mockResolvedValueOnce({ rows: [newAdmin] });

      await authController.register(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(201);
      expect(mockRes.json).toHaveBeenCalledWith(
        expect.objectContaining({
          admin: expect.objectContaining({
            email: 'admin@example.com',
            username: 'admin1'
          }),
          tokens: expect.objectContaining({
            accessToken: expect.any(String),
            refreshToken: expect.any(String)
          })
        })
      );
    });

    it('should return 400 if admin already exists by email', async () => {
      mockReq.body = {
        username: 'newadmin',
        email: 'existing@example.com',
        password: 'pass123',
        name: 'New Admin'
      };

      mockPool.query.mockResolvedValueOnce({ rows: [{ id: 'existing-id' }] });

      await authController.register(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(400);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Admin already exists' });
    });

    it('should return 400 if admin already exists by username', async () => {
      mockReq.body = {
        username: 'existingadmin',
        email: 'new@example.com',
        password: 'pass123',
        name: 'New Admin'
      };

      mockPool.query.mockResolvedValueOnce({ rows: [{ id: 'existing-id' }] });

      await authController.register(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(400);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Admin already exists' });
    });

    it('should return 500 if database is not connected', async () => {
      mockReq.body = { username: 'admin', email: 'a@b.com', password: 'pass', name: 'Admin' };
      require('../db').getPool.mockReturnValueOnce(null);

      await authController.register(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Database not connected' });
    });

    it('should return 500 on database error', async () => {
      mockReq.body = { username: 'admin', email: 'a@b.com', password: 'pass', name: 'Admin' };
      mockPool.query.mockRejectedValueOnce(new Error('DB error'));

      await authController.register(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Failed to register admin' });
    });
  });

  describe('login', () => {
    it('should login admin with valid credentials', async () => {
      const password = 'SecurePass123!';
      const hashedPassword = await bcrypt.hash(password, 12);

      mockReq.body = {
        email: 'admin@example.com',
        password: password
      };

      const admin = {
        id: 'admin-id-1',
        username: 'admin1',
        email: 'admin@example.com',
        password_hash: hashedPassword,
        name: 'Admin User',
        permissions: ['all']
      };
      mockPool.query.mockResolvedValueOnce({ rows: [admin] });

      await authController.login(mockReq, mockRes);

      expect(mockRes.json).toHaveBeenCalledWith(
        expect.objectContaining({
          admin: expect.objectContaining({
            email: 'admin@example.com'
          }),
          tokens: expect.objectContaining({
            accessToken: expect.any(String),
            refreshToken: expect.any(String)
          })
        })
      );
      // Password hash should be removed from response
      expect(mockRes.json.mock.calls[0][0].admin.password_hash).toBeUndefined();
    });

    it('should return 401 if admin not found', async () => {
      mockReq.body = {
        email: 'nonexistent@example.com',
        password: 'password123'
      };

      mockPool.query.mockResolvedValueOnce({ rows: [] });

      await authController.login(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(401);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Invalid credentials' });
    });

    it('should return 401 for invalid password', async () => {
      mockReq.body = {
        email: 'admin@example.com',
        password: 'wrongpassword'
      };

      const admin = {
        id: 'admin-id-1',
        email: 'admin@example.com',
        password_hash: await bcrypt.hash('correctpassword', 12)
      };
      mockPool.query.mockResolvedValueOnce({ rows: [admin] });

      await authController.login(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(401);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Invalid credentials' });
    });

    it('should return 500 if database is not connected', async () => {
      mockReq.body = { email: 'admin@example.com', password: 'pass' };
      require('../db').getPool.mockReturnValueOnce(null);

      await authController.login(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Database not connected' });
    });

    it('should return 500 on database error', async () => {
      mockReq.body = { email: 'admin@example.com', password: 'pass' };
      mockPool.query.mockRejectedValueOnce(new Error('DB error'));

      await authController.login(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Login failed' });
    });
  });

  describe('getMe', () => {
    it('should return current admin profile', async () => {
      mockReq.user = { id: 'admin-id-1' };

      const admin = {
        id: 'admin-id-1',
        username: 'admin1',
        email: 'admin@example.com',
        name: 'Admin User',
        permissions: ['all']
      };
      mockPool.query.mockResolvedValueOnce({ rows: [admin] });

      await authController.getMe(mockReq, mockRes);

      expect(mockRes.json).toHaveBeenCalledWith({ admin });
    });

    it('should return 404 if admin not found', async () => {
      mockReq.user = { id: 'nonexistent-id' };
      mockPool.query.mockResolvedValueOnce({ rows: [] });

      await authController.getMe(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(404);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Admin not found' });
    });

    it('should return 500 on database error', async () => {
      mockReq.user = { id: 'admin-id-1' };
      mockPool.query.mockRejectedValueOnce(new Error('DB error'));

      await authController.getMe(mockReq, mockRes);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({ error: 'Failed to fetch profile' });
    });
  });
});