Angular-如何在Laravelbackend中使登录用户仅查看具有其用户ID的相关数据

时间:2019-06-19 10:46:01

标签: angular laravel api

我设计了一个具有Laravel后端和Angular前端的应用程序。 每个表都有user_idusers表中的ID相关的User Model类。除了具有用户ID为1的admin之外,所有内容都将显示。我希望任何登录的用户都只能看到自己的数据。每个表上的user_id等于他的登录名user_id

角度:auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

// App imports
import { environment } from '../../environments/environment.prod';
import { User } from '../models/user';
// Setup headers
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public currentUser: User;
  private readonly apiUrl = environment.apiUrl;
  private registerUrl = this.apiUrl + '/register';
  private loginUrl = this.apiUrl + '/login';

  constructor(
    private http: HttpClient,
    private router: Router) {}

  onRegister(user: User): Observable<User> {

    const request = JSON.stringify(
      { name: user.name, username: user.username, email: user.email, password: user.password }
    );

    return this.http.post(this.registerUrl, request, httpOptions)
      .pipe(
        map((response: User) => {
          // Receive jwt token in the response
          const token: string = response['access_token'];
          // If we have a token, proceed
          if (token) {
            this.setToken(token);
            this.getUser().subscribe();
          }
          return response;
        }),
        catchError(error => this.handleError(error))
      );
  }

  onLogin(user: User): Observable<User> {

    const request = JSON.stringify(
      { email: user.email, password: user.password }
    );

    return this.http.post(this.loginUrl, request, httpOptions)
      .pipe(
        map((response: User) => {
          // Receive jwt token in the response
          const token: string = response['access_token'];
          // If we have a token, proceed
          if (token) {
            this.setToken(token);
            this.getUser().subscribe();
          }
          return response;
        }),
        catchError(error => this.handleError(error))
      );
  }

  onLogout(): Observable<User> {
    return this.http.post(this.apiUrl + '/logout', httpOptions).pipe(
      tap(
        () => {
          localStorage.removeItem('token');
          this.router.navigate(['/']);
        }
      )
    );
  }

  setToken(token: string): void {
    return localStorage.setItem('token', token );
  }

  getToken(): string {
    return localStorage.getItem('token');
  }

  getUser(): Observable<User> {
    return this.http.get(this.apiUrl + '/me').pipe(
      tap(
        (user: User) => {
          this.currentUser = user;
        }
      )
    );
  }

  isAuthenticated(): boolean {
    // get the token
    const token: string = this.getToken();
    if (token) {
      return true;
    }
    return false;
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side error.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend error.
        return throwError(error);
    }
    // return a custom error message
    return throwError('Ohps something wrong happen here; please try again later.');
  }
}

login.component.ts


import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { FlashMessagesService } from 'angular2-flash-messages';
import { ActivatedRoute, Router } from '@angular/router';
import {UserService} from '../../services/user.service';
import { SnotifyService } from 'ng-snotify';

// App imports
import { AuthService } from '../../services/auth.service';
import { User } from '../../models/user';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  user: User = new User();
  error: any;
  returnUrl: string;

  constructor(
    private authService: AuthService,
    private router: Router,
    private route: ActivatedRoute,
    private notify: SnotifyService
    ) { }  


  ngOnInit() {
    //  Set the return url
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/home';
  }

  onSubmit(loginForm): void {
    this.authService.onLogin(this.user).subscribe(
      (response) => {
        // get return url from route parameters or default to '/'
        this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})        
        this.router.navigate([this.returnUrl]);
      },
      (error) => {
        this.error = error.error;
      }
    );
    // Clear form fields
    loginForm.reset();
  }  

}

    public function login(Request $request)
{

    $validator = Validator::make($request->all(), [
        'email' => 'required|string|email|max:255',
        'password'=> 'required'
    ]);

    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);
    }

    $credentials = $request->only(['email', 'password']);

    if (!$token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Invalid Credentials'], 400);
    }

    $current_user = $request->email;

    return response()->json([
    'access_token' => $token,
    'token_type' => 'bearer',
    'current_user' => $current_user,
    'expires_in' => auth()->factory()->getTTL() * 60
    ], 200);
}  


public function indexShortcode()
{
    $shortcodes = Shortcode::all();
    return $shortcodes;
} 

public function indexSmsmo()
{
    $smsmos = Smsmo::all();
    return $smsmos;
}

如果登录user()->id1,则该用户是Admin,应该看到每个表上的所有数据,但是如果不是1,则登录的用户只能看到{{ 1}}等于他的登录ID。

1 个答案:

答案 0 :(得分:0)

您可以按如下所示进行修改:

scipy.io.wavfile

,您需要从客户端或前端在带有载体的标头中发送令牌