All files / src/presentation api.protected.ts

0% Statements 0/14
0% Branches 0/2
0% Functions 0/2
0% Lines 0/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                     
// hono
import { HTTPException } from 'hono/http-exception';
// hono object factory
import honoFactory from './factory/hono';
// better-auth object factory
import { AuthFactoryType } from './factory/auth';
// routes
import sessionRoute from './routes/session';
import group from './routes/group';
import info from './routes/info';
import userProfile from './routes/userProfile';
 
// protected router with authentication
const apiProtected = (auth: AuthFactoryType) => {
  const app = honoFactory();
 
  // authentication middleware
  app.use('/api/*', async (c, next) => {
    const session = await auth(c.env).api.getSession({ headers: c.req.raw.headers });
 
    // if no session, throw unauthorized error
    if (!session) {
      throw new HTTPException(401, { message: 'Unauthorized' });
    }
 
    // set user and session in context for downstream handlers
    c.set('user', session.user);
    c.set('session', session.session);
 
    await next();
  });
 
  //* endpoint registration *//
  app.route('/', sessionRoute);
  app.route('/', group);
  app.route('/', info);
  app.route('/', userProfile);
 
  return app;
};
 
export default apiProtected;