You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于user_id的Angular Dashboard跳转及组件权限控制问题

Solution for Conditional Dashboard Redirect & User-Specific Data Access in Angular + Laravel

Got it, let's break this down into manageable steps. You need two core features: redirecting to the correct dashboard after login based on user_id, and ensuring regular users only see records linked to their user_id. Here's how to implement both:

1. Update Laravel Login to Return User Data

Right now your login endpoint only returns a token—we need to include the authenticated user's details (specifically id) so Angular can make the redirect decision.

Modify your Laravel login method:

public function login() { 
    $credentials = request(['email', 'password']); 
    if (!$token = auth()->attempt($credentials)) { 
        return response()->json(['error' => 'Email or Password doesn\'t exist'], 401); 
    } 

    // Return token + user data together
    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60,
        'user' => auth()->user() // This gives us the logged-in user's data
    ]);
}

2. Angular: Conditional Redirect After Login

Now update your Angular login component to check the user_id (from the Laravel response) and redirect to the right dashboard. Also, save the user data for later permission checks.

Modify login.component.ts's handleResponse method:

handleResponse(data){ 
    this.Token.handle(data.access_token);
    // Save user data to localStorage for future checks
    localStorage.setItem('currentUser', JSON.stringify(data.user));
    this.Auth.changeAuthStatus(true);
    
    // Redirect based on user_id
    if (data.user.id === 1) {
        this.router.navigateByUrl('/admindashboard');
    } else {
        this.router.navigateByUrl('/user-dashboard');
    }
}

3. Angular: Fetch User-Specific Data

Update your Angular service methods to fetch data based on the user's role. For admins, fetch all records; for regular users, only fetch records where user_id matches their own.

Example service methods (adjust for Student/Assignment):

// In your data service (e.g., DataService)
getStudents() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    if (currentUser.id === 1) {
        // Admin gets all students
        return this.http.get(`${this.baseUrl}/students`);
    } else {
        // Regular user gets only their students
        return this.http.get(`${this.baseUrl}/students?user_id=${currentUser.id}`);
    }
}

getAssignments() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    if (currentUser.id === 1) {
        return this.http.get(`${this.baseUrl}/assignments`);
    } else {
        return this.http.get(`${this.baseUrl}/assignments?user_id=${currentUser.id}`);
    }
}

4. Laravel: Filter Data for Regular Users

Update your Laravel controllers to return filtered data based on the authenticated user. This ensures even if someone manipulates the frontend request, the backend enforces permission.

Example StudentController index method:

public function index() {
    $user = auth()->user();
    
    if ($user->id === 1) {
        // Admin gets all students
        return Student::all();
    } else {
        // Regular user gets only their linked students
        return Student::where('user_id', $user->id)->get();
    }
}

Do the same for AssignmentController:

public function index() {
    $user = auth()->user();
    
    if ($user->id === 1) {
        return Assignment::all();
    } else {
        return Assignment::where('user_id', $user->id)->get();
    }
}

5. Add Route Guards to Prevent Unauthorized Access

To stop users from manually typing the URL to access the wrong dashboard, add an Angular route guard.

First, create auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router: Router) {}

    canActivate(): boolean {
        if (!this.authService.isLoggedIn()) {
            this.router.navigate(['/login']);
            return false;
        }

        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        const requestedUrl = this.router.url;

        // Block non-admins from accessing admin dashboard
        if (requestedUrl.includes('admindashboard') && currentUser.id !== 1) {
            this.router.navigate(['/user-dashboard']);
            return false;
        }

        return true;
    }
}

Update your AuthService to include an isLoggedIn method:

isLoggedIn(): boolean {
    const token = this.Token.getToken();
    const currentUser = localStorage.getItem('currentUser');
    return !!token && !!currentUser; // Returns true if both exist
}

Finally, add the guard to your routes:

const routes: Routes = [
    { path: 'login', component: LoginComponent },
    { path: 'admindashboard', component: AdminDashboardComponent, canActivate: [AuthGuard] },
    { path: 'user-dashboard', component: UserDashboardComponent, canActivate: [AuthGuard] },
    // Add other routes here
];

That's it! Now your app will redirect users to the correct dashboard on login, and regular users will only see data linked to their user_id, with backend enforcement to prevent unauthorized access.

内容的提问来源于stack exchange,提问作者user11352561

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:44:25