如果不满足条件则拒绝PUT请求

时间:2019-12-03 22:01:09

标签: express mongoose

如果登录的用户尝试更新其电子邮件地址,我在拒绝PUT请求时遇到问题。我想确保只有授权用户才能更新自己的电子邮件。它似乎不喜欢我的res.end()或return;如何在更新之前编写我的代码来满足此条件?

app.js


app.patch('/:id', (req, res) => {

if(req.body.oldEmail){

  let user = req.body.id;
  if (user.email !== req.body.oldEmail) {
      res.sendStatus(401);
  } else {
      User.update(
          {email: req.body.oldEmail},
          {email: req.body.newEmail}

      ).then(user => {
          console.log(user);
          res.json(user);
      }).catch(err => console.log(err));
  }
}

auth.service.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Router } from "@angular/router";
import { Subject } from "rxjs";

import { AuthData } from "./auth-data.model";
import { AuthDataLogin } from "./auth-data-login.model";
import { LoginService } from "./login/login.service";

@Injectable({ providedIn: "root" })
export class AuthService {
  private isAuthenticated = false;
  private token: string;
  private tokenTimer: any;
  private userName: string;
  private authStatusListener = new Subject<boolean>();
  private userId: string;
  constructor(
    private http: HttpClient,
    private router: Router,
    private loginService: LoginService
  ) {}

  getToken() {
    return this.token;
  }

  getIsAuth() {
    return this.isAuthenticated;
  }

  getUserId() {
    return this.userId;
  }
  getAuthStatusListener() {
    return this.authStatusListener.asObservable();
  }

  createUser(
    email: string,
    password: string,
    instagramName: string,
    over21: boolean,
    role: string
  ) {
    const authData: AuthData = {
      email: email,
      password: password,
      instagramName: instagramName,
      over21: over21,
      role: role,
      fullName: "Not Added Yet",
      address1: "none",
      address2: "none",
      city: "none",
      state: "none",
      zip: "none"
    };
    this.http
      .post("http://localhost:3000/api/user/signup", authData)
      .subscribe(response => {
        console.log(response);
      });
  }

  login(email: string, password: string) {
    const authData: AuthDataLogin = { email: email, password: password };
    this.http
      .post<{
        token: string;
        expiresIn: number;
        userId: string;
        instagramName: string;
      }>("http://localhost:3000/api/user/login", authData)
      .subscribe(response => {
        const token = response.token;
        console.log("Response");
        console.log(response);
        //    this.userName = response;
        //   console.log(this.userName);
        this.userName = response.instagramName;

        console.log(this.userName);
        this.token = token;
        if (token) {
          const expiresInDuration = response.expiresIn;
          this.setAuthTimer(expiresInDuration);
          this.isAuthenticated = true;
          this.userId = response.userId;
          this.userName = response.instagramName;
          this.authStatusListener.next(true);
          const now = new Date();
          const expirationDate = new Date(
            now.getTime() + expiresInDuration * 1000
          );
          console.log(expirationDate);
          this.saveAuthData(token, expirationDate, this.userId);
          this.router.navigate(["/"]);
          let key = "UserID";
        }
      });
  }

  autoAuthUser() {
    const authInformation = this.getAuthData();
    if (!authInformation) {
      return;
    }
    const now = new Date();
    const expiresIn = authInformation.expirationDate.getTime() - now.getTime();
    if (expiresIn > 0) {
      this.token = authInformation.token;
      this.isAuthenticated = true;
      this.userId = authInformation.userId;
      this.setAuthTimer(expiresIn / 1000);
      this.authStatusListener.next(true);
    }
  }

  logout() {
    this.token = null;
    this.isAuthenticated = false;
    this.authStatusListener.next(false);
    clearTimeout(this.tokenTimer);
    this.clearAuthData();
    this.userId = null;
    //location.reload();
    this.router.navigate(["/login"]);
  }

  private setAuthTimer(duration: number) {
    //console.log("Setting timer: " + duration);
    this.tokenTimer = setTimeout(() => {
      this.logout();
    }, duration * 1000);
  }

  private saveAuthData(token: string, expirationDate: Date, userId: string) {
    localStorage.setItem("token", token);
    localStorage.setItem("expiration", expirationDate.toISOString());
    localStorage.setItem("userId: ", userId);
    localStorage.setItem("username", this.userName);
  }

  private clearAuthData() {
    localStorage.removeItem("token");
    localStorage.removeItem("expiration");
    localStorage.removeItem("userId");
    localStorage.removeItem("username");
  }

  private getAuthData() {
    const token = localStorage.getItem("token");
    const expirationDate = localStorage.getItem("expiration");
    const userId = localStorage.getItem("userId: ");
    if (!token || !expirationDate) {
      return;
    }
    return {
      token: token,
      expirationDate: new Date(expirationDate),
      userId: userId
    };
  }
}

1 个答案:

答案 0 :(得分:2)

您的代码有几个问题:

  1. 在检查用户电子邮件是否相同之前,您似乎正在更新电子邮件地址。
  2. 您应该使用res.sendStatus(401)而不是res.end()

尝试将您的代码更改为类似的代码,然后查看是否满足您的要求:

app.put('/email/:id', (req, res) => {
    let user = // get the user first to check the email.
    if (user.email !== req.body.oldEmail) {
        res.sendStatus(401);
    } else {
        User.update(
            {email: req.body.oldEmail},
            {email: req.body.newEmail}

        ).then(user => {
            console.log(user);
            res.json(user);
        }).catch(err => console.log(err));
    }
});