瀏覽代碼

前端功能添加完成,可能还需调试调试小问题, 不影响整体结构和功能

徐明 5 年之前
父節點
當前提交
b4784c616d

+ 48 - 0
CasinosManager/src/app/account/account.component.css

@@ -0,0 +1,48 @@
+.carousel-inner img {
+    width:100%;
+    height:100%;
+}
+.jumbotron {
+    margin-top: 10px;
+    margin-bottom: 0px;
+    padding-top: 10px;
+}
+#demo {
+    width:100%;
+    height: 350px;
+}
+.row {
+    height: 350px;
+}
+.left {
+    float: left;
+    width: 70%;
+    max-width: 1000px;;
+}
+.right {
+    float: left;
+    width: 30%;
+}
+.card{
+    height: 350px;
+}
+
+.footer {
+    position: absolute;
+    bottom: 0;
+    height: 60px;
+}
+.jumheight1 {
+    height: 140px;
+}
+.jumheight2 {
+    height: 100px;
+}
+.end_name {
+    margin-bottom: 5px;
+}
+.footer2 {
+    padding-top: 100px;
+    text-align: center;
+
+}

+ 36 - 3
CasinosManager/src/app/account/account.component.html

@@ -1,3 +1,36 @@
-<p>
-  account works!
-</p>
+<div>
+    <div class="jumbotron text-info bg-light jumheight1">
+        <p>一个简单的示例系统</p>
+      </div>
+    <div class="row">
+      <div class="left">
+          <img src="http://static.runoob.com/images/mix/img_fjords_wide.jpg">
+        </div>
+        <div class="right">
+          <div class="card">
+              <div class="card-header">
+                  用户登陆
+                </div>
+                <div  class="card-body">
+                    <form>
+                        <div class="form-group">
+                          <label for="name">用户名</label>
+                          <input type="name" class="form-control" id="name" name="name" placeholder="Enter Account"  [(ngModel)]="authenticateModel.username">
+                        </div>
+                        <div class="form-group">
+                          <label for="password">密码</label>
+                          <input type="password" class="form-control" id="password" name="password" placeholder="Password"  [(ngModel)]="authenticateModel.password">
+                        </div>
+                        <div class="form-group">
+                            <button type="button" class="btn btn-primary" (click)="authenticate()">登录</button>
+                          </div>
+                      </form>
+                </div>
+          </div>
+        </div>
+    </div>
+    <div class="jumbotron bg-light jumheight2">
+        <p class="footer2">@Master_huangyx</p>
+      </div>
+</div>
+

+ 29 - 1
CasinosManager/src/app/account/account.component.ts

@@ -1,4 +1,7 @@
 import { Component, OnInit } from '@angular/core';
+import { Router } from '@angular/router';
+import { TokenAuthService, AuthenticateModel, AuthenticateResult, UserInfo } from '../shared/service-proxy/token-auth.service'
+import { AppSessionService } from '../shared/auth/app-session.service'
 
 @Component({
   selector: 'app-account',
@@ -7,9 +10,34 @@ import { Component, OnInit } from '@angular/core';
 })
 export class AccountComponent implements OnInit {
 
-  constructor() { }
+  authenticateModel: AuthenticateModel = new AuthenticateModel();
+
+  constructor(
+    private _tokenAuthService: TokenAuthService,
+    private _sessionService: AppSessionService,
+    private _router: Router,
+  ) { }
 
   ngOnInit() {
   }
 
+  authenticate(): void {
+
+    this._tokenAuthService
+      .authenticate(this.authenticateModel)
+      .subscribe((result: AuthenticateResult) => {
+        if (result) {
+          this.setCookie("auth_token", result.access_token, result.expires_in);
+          this._sessionService.init().then(() => {
+            this._router.navigate(['content'])
+          })
+        }
+      });
+  }
+
+  setCookie(name, value, expires): void {
+    var exp = new Date();
+    exp.setTime(exp.getTime() + expires * 1000);
+    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toDateString();
+  }
 }

+ 4 - 2
CasinosManager/src/app/content/content-routing.module.ts

@@ -1,13 +1,15 @@
 import { NgModule } from '@angular/core';
 import { Routes, RouterModule } from '@angular/router';
 
+import { AppRouteGuard } from '../shared/auth/auth-route-guard';
+
 import { StudentComponent } from './student/student.component';
 import { CourseComponent } from './course/course.component';
 
 const routes: Routes = [
   { path: '', redirectTo: 'student', pathMatch: 'full' },
-  { path: 'student', component: StudentComponent },
-  { path: 'course', component: CourseComponent },
+  { path: 'student', component: StudentComponent, canActivate: [AppRouteGuard] },
+  { path: 'course', component: CourseComponent, canActivate: [AppRouteGuard] },
 ]
 
 

+ 35 - 0
CasinosManager/src/app/shared/auth/app-session.service.ts

@@ -0,0 +1,35 @@
+import { Injectable } from '@angular/core';
+import { Router } from '@angular/router';
+import { TokenAuthService, UserInfo } from '../service-proxy/token-auth.service'
+
+@Injectable({
+  providedIn: 'root',
+})
+export class AppSessionService {
+
+  private _user: UserInfo;
+
+  constructor(private _service: TokenAuthService,
+    private _router: Router,) {
+    this._service.authenticateUser().subscribe(result=>{
+      this._user = result;
+    });
+  }
+
+  get user(): UserInfo {
+    console.log("_user:" + this._user);
+    return this._user;
+  }
+
+  init(): Promise<boolean> {
+    return new Promise<boolean>((resolve, reject) => {
+        this._service.authenticateUser().toPromise().then((result: UserInfo) => {
+            this._user = result;    
+            console.log(this._router.url);    
+            resolve(true);
+        }, (err) => {
+            reject(err);
+        });
+    });
+}
+}

+ 36 - 0
CasinosManager/src/app/shared/auth/auth-route-guard.ts

@@ -0,0 +1,36 @@
+import { Injectable } from '@angular/core';
+import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';
+import { AppSessionService } from './app-session.service'
+
+@Injectable({
+  providedIn: 'root',
+})
+export class AppRouteGuard implements CanActivate, CanActivateChild {
+
+  constructor(
+    private _router: Router,
+    private _sessionService: AppSessionService) {
+  }
+
+  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
+    console.log(route.url);
+    if (!this._sessionService.user) {
+      this._router.navigate(['/account']);
+      return false;
+    }else{
+      return true;
+    }
+  }
+
+  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
+    return this.canActivate(route, state);
+  }
+
+  selectBestRoute(): string {
+    if (!this._sessionService.user) {
+      return '/account';
+    }
+
+    return '/content';
+  }
+}

+ 11 - 1
CasinosManager/src/app/shared/service-proxy/student.service.ts

@@ -22,7 +22,7 @@ export class StudentService {
       headers : new HttpHeaders({
         "Content-Type": "application/json",
         "Accept": "application/json",
-        "Authorization": "token " + "aaaa"
+        "Authorization": "Bearer " +  this.getCookie("auth_token")
     })
     };
 
@@ -32,6 +32,16 @@ export class StudentService {
     );
   }
 
+  private getCookie(name) {
+    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
+    if (arr = document.cookie.match(reg)) {
+        return unescape(arr[2]);
+    }
+    else {
+        return null;
+    }
+  }
+
   protected handleError<T>(operation = 'operation', result?: T) {
     return (error: any): Observable<T> => {
 

+ 93 - 0
CasinosManager/src/app/shared/service-proxy/token-auth.service.ts

@@ -0,0 +1,93 @@
+import { Injectable } from '@angular/core';
+import { Observable, of} from 'rxjs';
+import { catchError, tap } from 'rxjs/operators';
+import { HttpClient, HttpHeaders, HttpResponseBase, HttpResponse } from '@angular/common/http';
+
+@Injectable({
+  providedIn: 'root'
+})
+export class TokenAuthService{
+
+  private baseUrl: string;
+
+  constructor(private http: HttpClient) {
+    this.http = http;
+    this.baseUrl = "http://localhost:53002";
+  }
+
+  authenticate(authenticateModel:AuthenticateModel): Observable<AuthenticateResult> {
+    let url = this.baseUrl + "/connect/token";
+
+    return this.http.post<AuthenticateResult>(url, authenticateModel).pipe(
+      tap(item => console.log("authenticate user")),
+      catchError(this.handleError<AuthenticateResult>("authenticate user"))
+    );
+  }
+
+  authenticateUser(): Observable<UserInfo> {
+    let url = "http://localhost:54225/api/identity";
+
+    let options_ = {
+      headers : new HttpHeaders({
+        "Content-Type": "application/json",
+        "Accept": "application/json",
+        "Authorization": "Bearer " + this.getCookie("auth_token")
+    })
+    };
+
+    return this.http.get<UserInfo>(url).pipe(
+      tap(item => console.log("authenticate user")),
+      catchError(this.handleError<UserInfo>("authenticate user"))
+    );
+  }
+
+  private getCookie(name) {
+    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
+    if (arr = document.cookie.match(reg)) {
+        return unescape(arr[2]);
+    }
+    else {
+        return null;
+    }
+  }
+
+  private handleError<T>(operation = 'operation', result?: T) {
+    return (error: any): Observable<T> => {
+
+      // TODO: send the error to remote logging infrastructure
+      console.error(error); // log to console instead
+
+      // Let the app keep running by returning an empty result.
+      return of(result as T);
+    };
+  }
+}
+
+export class AuthenticateModel {
+  username: string;
+  password: string;
+  client_id: string;
+  client_secret: string;
+  grant_type: string;
+  scope: string;
+
+  constructor(){
+    this.client_id = "angular.client";
+    this.client_secret = "secret";
+    this.grant_type = "password";
+    this.scope = "CasinosApi";
+  }
+}
+
+export class AuthenticateResult{
+  access_token: string;
+  expires_in: string;
+  token_type: string;
+}
+
+export class UserInfo{
+  userId: string;
+  userName: string;
+  name: string;
+ 
+}