Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-instant-1· AnthropicHugging Face Arena Human Preference 55K

using nestjs, I'd like to build a user authentication , can you do that for me ?

  1. User

    using nestjs, I'd like to build a user authentication , can you do that for me ?

  2. Claude Assistant

    Here is some sample NestJS code to implement basic user authentication:

    1. Create a User entity:
    @Entity()
    export class User {
    
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column()
      username: string;
    
      @Column()
      password: string;
    
    }
    
    1. Create a AuthService:
    @Injectable()
    export class AuthService {
    
      constructor(
        @InjectRepository(User)
        private usersRepository: Repository<User>
      ) {}
    
      async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.usersRepository.findOne({ username });
        if (user && user.password === pass) {
          return user;
        }
        return null;
      }
    
    }
    
    1. Create AuthGuard:
    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private authService: AuthService) {}
    
      canActivate(
        context: ExecutionContext
      ): boolean | Promise<boolean> {
        
        const request = context.switchToHttp().getRequest();
        const user = this.authService.validateUser(
          request.body.username, 
          request.body.password
        );
    
        if (user) {
          request.user = user;
          return true;
        }
    
        return false;
      }
    
    }
    
    1. Protect routes with AuthGuard:
    @UseGuards(AuthGuard)
    @Controller('protected')
    export class ProtectedController {
    
      @Get()
      getProtected() {
        return 'Protected route!'; 
      }
    
    }
    

    This provides a basic authentication flow. You can enhance it further with JWT tokens, refresh tokens, etc.