Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BK]: Add Session Management (API and Middleware) #13

Closed
KevinLatino opened this issue Dec 12, 2024 · 39 comments · Fixed by #23
Closed

[BK]: Add Session Management (API and Middleware) #13

KevinLatino opened this issue Dec 12, 2024 · 39 comments · Fixed by #23
Assignees

Comments

@KevinLatino
Copy link
Member

Important

Before applying, please read the Contributors Guide. Following the guide increases your chances of being assigned to this task.

Description Store user sessions in the database and validate them in middleware.

Entity Definition

import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { User } from './User';

@Entity('sessions')
export class Session {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => User)
  user: User;

  @Column({ unique: true })
  token: string;

  @Column()
  expiresAt: Date;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

Middleware Implementation

import { Request, Response, NextFunction } from 'express';
import SessionService from '@/services/SessionService';

interface AuthenticatedRequest extends Request {
  user?: { id: number; role: string };
}

export const sessionMiddleware = async (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) {
    res.status(401).json({ message: 'Authentication token is missing' });
    return;
  }

  try {
    const sessionService = new SessionService();
    const session = await sessionService.validateSession(token);

    if (!session) {
      res.status(401).json({ message: 'Session expired or invalid' });
      return;
    }

    req.user = { id: session.user.id, role: session.user.role };
    next();
  } catch (error) {
    res.status(500).json({ message: 'Internal server error' });
  }
};

Tasks

  1. Create a Session entity in TypeORM.
  2. Implement SessionService with methods to:
    • Validate session tokens.
    • Create new sessions upon login.
  3. Implement sessionMiddleware to validate session tokens and attach user data to requests.

Acceptance Criteria

  • Sessions are stored in the database and validated in middleware.
  • Middleware rejects expired or invalid tokens with a 401 response.
  • All tests pass with >80% code coverage.

@Supa-mega
Copy link

I’d like to help with this.

@Shukazuby
Copy link

I am Zubaidat, a backend developer with expertise in TypeORM and secure session handling.

Approach to Solve the Issue:

I will create a Session entity in TypeORM and implement a SessionService with methods for validating session tokens and creating new sessions during login. The sessionMiddleware will validate tokens and attach user data to requests. The implementation will follow best practices for database efficiency and security.

ETA:
I can complete this task in 48hrs , including development and testing.

@ShantelPeters
Copy link

ShantelPeters commented Dec 12, 2024

May I pick this up?

I am full stack developer with strong experience in Cairo , solidity ,JavaScript,typescript ,react , python etc… looking forward to contributing as this would be my first time contributing to this project…

ETA : 3 days

@Amarjeet325
Copy link

Is it okay if I tackle this?

@diegoTech14
Copy link

Hello @KevinLatino my name is Diego Duarte Fernández, I'm a software engineer from Costa Rica and Dojo Coding member, I have experience with technologies like Express, Prisma ORM, TypeScript, I've created several APIs using ORMS, tokens and middlewares also I'm maintainer of SafeTrust project which is a security deposit service project. 🤖

I would love to tackle this issue and contribute for your amazing project.

Step by step for this issue:

  1. Follow and improve entity: I will follow the entity definition and if it possible improve it to ensure that works great.

  2. I will implement the middleware to process the authentication/authorization.

  3. I'm going to make sure that the token is created every time you log in.

  4. Testing: I will test the middleware and the token to ensure that everything is okay.

  5. If it is needed I will document the middleware and the token process management.

ETA: 72 hours
Thanks for your consideration.

Best regards, Diego Duarte Fernández. ✨

@blessingbytes
Copy link

i would love to be given the opportunity to tackle this task

@Benjtalkshow
Copy link

I am a Full Stack Developer with a strong background in blockchain and extensive experience in Next.js/React, TypeScript, and Rust. I’ve made over 49 contributions to over 17 projects in the OnlyDust ecosystem, solving complex issues and delivering efficient, scalable solutions.

I can handle this task.
ETA is 3days.

@Michaelkingsdev
Copy link

I can handle this particular task.

@RajeshRk18
Copy link

RajeshRk18 commented Dec 12, 2024

About me

I am a backend developer having experience in Typescript, Rust and Python. I have worked on APIs and various middleware projects.

How I will solve this issue?

Here is how I will solve the issue:

  • Track sessions with user, unique token, and expiration details.
  • Generate secure, time-limited tokens when users authenticate.
  • Validate tokens, and block unauthorized access
  • Verify credentials, create sessions, and manage login/logout flows.
  • Implement token validation, role-based access, and prevent unauthorized entry.

ETA: 2days

@psychemist
Copy link

Hi. I am a fullstack web developer and a recent alumni of Web3Bridge, the largest and most sought after blockchain developer community in Africa. I am a new contributor to OnlyDust and would love to take on this task to increase my knowledge base and contribute to open source projects.

I would solve this task by:

  1. Creating a Session entity by importing the object from TypeORM
  2. Implementing the SessionService and sessionMiddleware that create and validate session tokens.
  3. Running tests to ensure full coverage before submitting my pull request.

I aim to complete this task within 3 hours after being assigned and setting up my development environment.

Thank you for the opportunity and I look forward to working with you.

@od-hunter
Copy link

Hi, please can I be assigned this please? This would be my first time contributing to this project and I would love to be the given the opportunity to contribute. I have experience in html, css, JavaScript,TypeScript and solidity, and Cairo.

To solve this issue, I’ll take the following steps:
1.⁠ ⁠I’ll define a TypeORM entity to store session data, including a token and expiration time.
2.⁠ ⁠⁠I’ll generate a JWT token, store it in the sessions table, and set an expiration date. Then, I’ll validate the session by verifying the token and checking the session's expiration.
3.⁠ ⁠⁠I’ll extract the token from the authorization header, then call SessionService to validate the token. If valid, I’ll attach user data (id, role) to the request object; otherwise, I’ll return a 401 unauthorized response.
4.⁠ ⁠⁠Lastly, I’ll apply sessionMiddleware to routes that require authentication, to ensure only authenticated users can access them.

ETA: 3days
Kindly assign me please, I’m ready to work.

@gregemax
Copy link

May I be assigned to this task? I have experience in backend development with TypeScript, TypeORM, and implementing middleware. I’m confident in creating the Session entity, SessionService, and sessionMiddleware to ensure secure and efficient session management. I’ll also ensure test coverage exceeds 80%.

@mimisavage
Copy link

Can I work on this, please?

@Nityam573
Copy link

May I take care of this?

@1nonlypiece
Copy link

Can I take care of this issue?

@BrunoAmbricca
Copy link

BrunoAmbricca commented Dec 12, 2024

I will learn the existing code and research the best approach for this issue

@mariocodecr
Copy link

Hii! My name is Mario Araya, I’m a Software Developer with 2+ years of experience. I have worked with backend technologies such as Cairo, Java, and C#, as well as frontend development using React, NextJS, and JavaScript/TypeScript. I’ve made contributions to open-source projects, completed a Starknet Bootcamp, exercises on NodeGuardians, finished Starklings, and participated in multiple hackathons. I’m also a member of the Dojo Coding community here in Costa Rica.

I will create a Session entity using typeorm with fields for id, user, token, expiresAt, and timestamp columns. Implement a SessionService with methods to validate session tokens by checking their presence and expiration in the database and to create new sessions during user login. Develop a sessionMiddleware to extract and validate the Authorization header token using the service, rejecting requests with invalid or expired tokens and attaching authenticated user data to the request object for valid sessions.

@ikezuby2012
Copy link

Hello, my name is nnubia nzube, I'm a full-stack developer with nearly 4 years of experience working with JavaScript, TypeScript, c#, Express.js, and recently exploring Cairo for blockchain development. I’m passionate about building robust and scalable applications while ensuring clean and maintainable code.

For this issue, my approach would be to create a middleware that:

Checks if a token is present in the request headers.
Validates the token for authenticity and expiration.
Stores the validated token in the session for future use.

ETA: 3 days

@emarc99
Copy link

emarc99 commented Dec 12, 2024

Could I take over this issue? ETA 3 days

@kayceeDev
Copy link

kayceeDev commented Dec 12, 2024

Can I tackle this one?

I am a senior backend engineer.
I will utilize my experience in Nest.js and typescript to build a robust middleware for session service,

I will utilize my database skills to save the session in a database with expiry periods.

My ETA: 3 Days

@sonkeydotcom
Copy link

Hi. Id like to take this task

@olisaagbafor
Copy link

Hello StarShop Team,

I’m Olisa Agbafor, a backend developer with expertise in building secure APIs, middleware, and session management using Node.js, Express, and TypeORM. I would love to contribute to this task.

My Approach:
Entity Definition:

Define the Session entity with proper relationships to the User entity, ensuring unique constraints on tokens and timestamps for creation and updates.
SessionService Implementation:

Create methods to validate session tokens and generate new sessions upon user login, ensuring robust security measures.
Middleware Development:

Implement sessionMiddleware to validate session tokens and attach user data to requests. Handle errors for expired or invalid tokens with proper responses.
Testing:

Write comprehensive unit and integration tests with Jest to ensure all scenarios, including expired and invalid tokens, are covered. Ensure >80% test coverage.
ETA:
I estimate the task will be completed in 3 days, including testing and documentation.

Looking forward to your approval and contributing to the project. Thank you!

Best regards,
Olisa Agbafor

@josephpdf
Copy link
Contributor

Hi @KevinLatino
I'm Joseph Poveda, a member of the Dojo Coding community, I have experience in different programming languages ​​and have contributed to different OSS projects.
To solve the issue I propose

  1. Create the Session Entity:
    • Use the provided TypeORM structure to define the Session entity.
    • Ensure all necessary fields like id, user, token, expiresAt, createdAt, and updatedAt are correctly implemented.
  2. Implement the SessionService:
    • Develop methods to validate session tokens and create new sessions upon login.
    • Integrate database queries to fetch and verify session data.
  3. Develop Middleware:
    • Use the sessionMiddleware to check the token's validity.
    • Attach user information to the request for further processing.
  4. Test Thoroughly:
    • Write unit tests to validate middleware functionality and service methods, ensuring >80% code coverage.
  5. Submit PR:
    • Ensure code follows guidelines, passes tests, and document the implementation in the README.

@khayss
Copy link

khayss commented Dec 12, 2024

I'm a fullstack developer with preference for backends and smart contracts. I've built and collaborated on backends written in Rust and NodeJS, including production grade servers.

Here are the step I'll take to tackle this issue.

  • Create a Session entity in TypeORM.
  • Implement a service for the created entity. This will handle validations of sessions and creation of new ones.
  • Implement a strong middleware to validate sessions and inject user data to requests.

I'm looking forward to working on this issue.

@DuendexCR
Copy link

I’d like to work on this.

@Villarley Villarley changed the title Add Session Management (API and Middleware) [BK]: Add Session Management (API and Middleware) Dec 13, 2024
@caxtonacollins
Copy link

I am a Full Stack Developer with two years of professional experience, specializing in web3. I have strong background in blockchain and extensive experience in Next.js/React, TypeScript, Cairo and Rust.

To solve this, I'll first define session entities using the provided typeORM models, will then implement session service which wil include session token validation and creation of new sessions upto login.
I will also implement session middleware and write unit test for session methods like validateSession and createSession.

ETA is 2days.

@akintewe
Copy link

Hello, may I be assigned to this task? I have experience in backend development with TypeScript, TypeORM, and implementing middleware.
I have read the requirements and i have worked on sessions in the past which would make it easier for me to tackle.
I’m confident in creating the Session entity, SessionService, and sessionMiddleware to ensure secure and efficient session management. My ETA is 24 hours

@Jagadeeshftw
Copy link

I'd love to work on this!

@3th-Enjay
Copy link

Is this issue still available? i understand what needs to be done and can handle it

@DioChuks
Copy link

Can I take this issue?

@Ahmad940
Copy link

I’d like to help with this, experienced typescript and backend developer,
I will be creating a new middleware folder to abstract aware middlewares, and apply to all route, and service for validation the user session retrieved from header.

@Dorcas18
Copy link

May I handle this issue?

@ekumamatthew
Copy link

I'd like to take this issue.

@Joewizy
Copy link

Joewizy commented Dec 13, 2024

Could I be assigned to this?

@ryzen-xp
Copy link

Can I attempt this issue?

@martinvibes
Copy link

i'm a frontend dev and blockchain dev
May I try my hand at this?
i would love to work on this and get it done

@vestor-dev
Copy link

Could I be assigned to this?
Would love to tackle this!
kindly assign :)

@Amarjeet325
Copy link

Hi , I am a full stack developer is a versatile professional skilled in both front-end and back-end development, capable of designing user interfaces, building robust server-side applications, and managing databases.
Can I take this from here? Thank you !

@Villarley
Copy link
Contributor

hey @josephpdf
Task assigned to you. Let me know if you need further clarification or additional support!😊

Here is our telegram group, please join https://t.me/starshopcr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.