如何显示仅授权用户的数据?

时间:2018-10-23 09:02:54

标签: node.js angular

如何实现仅显示授权用户数据(作为配置文件)的功能。告诉我什么以及如何解决它,以便授权用户可以显示数据。

Nodejs:

型号:

module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define('users', {
        login: {
            type: Sequelize.STRING(40),
            required: true,
            unique: true
        },
        password: {
            type: Sequelize.STRING(100),
            required: true,

        },
        roles: {
            type: Sequelize.STRING(100),
            required: true
        },
        full_name: {
            type: Sequelize.STRING(100),
            required: true
        },
        photoSrc: {
            type: Sequelize.STRING(200),
            default: ''
        }
    })
    return User
}

user.controller:

const db = require('../database/database')
const User = db.users

module.exports.authUser = async function(req, res) {
    try {
        const users = await User.find({user: req.user.id})
        res.status(200).json(users)
    } catch(e) {
        errorHandler(res, e)
    }
}

路线:

const express = require('express')
const controller = require('../controllers/user')
const passport = require('passport')
const router = express.Router()

//http://localhost:5000/api/users/
router.get('/', passport.authenticate('jwt', {session: false}), controller.authUser)

module.exports = router

用户登录并尝试打开配置文件后,终端中显示错误:

  

TypeError:User.findById不是函数

  const JwtStrategy = require('passport-jwt').Strategy
    const ExtractJwt = require('passport-jwt').ExtractJwt
    const User = require('../models/User')

    const options = {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 
      secretOrKey: process.env.SECRET_OR_KEY
    }

    module.exports = passport => {
      passport.use(
          new JwtStrategy(options, async (payload, done) => {
              try {
                  const user = await User.findById(payload.userId).select('login id')

                  if (user) {
                      done(null, user)
                  } else {
                      done(null, false)
                  }
              } catch(e) {
                  console.log(e)
              }
          })
      )
    }

角度6:

服务:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { User } from "../interfaces";
import { Observable } from "rxjs";

@Injectable({
    providedIn: 'root'
})

export class UsersService {
    constructor(private http: HttpClient) {
    }

    fetch(): Observable<User[]> {
       return this.http.get<User[]>('/api/users/')
    }

}

component.ts:

import { Component, OnInit } from '@angular/core';
import { UsersService } from '../shared/services/users.service';
import { Category } from '../shared/interfaces';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-users-page',
  templateUrl: './users-page.component.html',
  styleUrls: ['./users-page.component.css']
})
export class UsersPageComponent implements OnInit {

  users$: Observable<User[]>

  constructor(private usersService: UsersService,) { }

  ngOnInit() {

    this.users$ = this.usersService.fetch() 
  }

}

component.html:

  <div class="row" *ngIf="users$ | async as users">
      <div class="col s12">
          <div class="collection" >
              <a *ngFor="let user of users" class="collection-item">{{user.full_name}}</a>
          </div>
      </div>
  </div>

0 个答案:

没有答案