Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 87c1bdd1

Přidáno uživatelem Jakub Hlaváč před téměř 4 roky(ů)

Re #8728 - Implemetace autorizace přes nové API endpointy

  • login with nes endpoints
    + getting user info from endpoint
    + defining new endpoints to OpenAPI

Zobrazit rozdíly:

nginx.conf
52 52

  
53 53
    }
54 54

  
55
        location /api/SensLogV1/OGCSensorThings {
56
                  proxy_set_header X-Forwarded-Host $host;
57
                  proxy_set_header X-Forwarded-Server $host;
58
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
59
                  #proxy_pass http://<ContainerName>:<PortNumber>;
60
                  # In our case Container name is as we setup in docker-compose `beservice` and port 8080
61
                  proxy_pass http://51.15.45.95:9080;
62
                  proxy_max_temp_file_size "1024m";
63
                  proxy_read_timeout       "60s";
64

  
65
                  add_header X-Frame-Options SAMEORIGIN always;
66

  
67
        }
68

  
69
        location /analytics {
70
                  proxy_set_header X-Forwarded-Host $host;
71
                  proxy_set_header X-Forwarded-Server $host;
72
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
73
                  #proxy_pass http://<ContainerName>:<PortNumber>;
74
                  # In our case Container name is as we setup in docker-compose `beservice` and port 8080
75
                  proxy_pass http://51.15.45.95:9090;
76
                  proxy_max_temp_file_size "1024m";
77
                  proxy_read_timeout       "60s";
78

  
79
                  add_header X-Frame-Options SAMEORIGIN always;
80

  
81
        }
55
    location /api/SensLogV1/OGCSensorThings {
56
              proxy_set_header X-Forwarded-Host $host;
57
              proxy_set_header X-Forwarded-Server $host;
58
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
59
              #proxy_pass http://<ContainerName>:<PortNumber>;
60
              # In our case Container name is as we setup in docker-compose `beservice` and port 8080
61
              proxy_pass http://51.15.45.95:9080;
62
              proxy_max_temp_file_size "1024m";
63
              proxy_read_timeout       "60s";
64

  
65
              add_header X-Frame-Options SAMEORIGIN always;
66

  
67
    }
68

  
69
    location /analytics {
70
              proxy_set_header X-Forwarded-Host $host;
71
              proxy_set_header X-Forwarded-Server $host;
72
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
73
              #proxy_pass http://<ContainerName>:<PortNumber>;
74
              # In our case Container name is as we setup in docker-compose `beservice` and port 8080
75
              proxy_pass http://51.15.45.95:9090;
76
              proxy_max_temp_file_size "1024m";
77
              proxy_read_timeout       "60s";
78

  
79
              add_header X-Frame-Options SAMEORIGIN always;
80

  
81
    }
82

  
83
    location /senslog15 {
84
              proxy_set_header X-Forwarded-Host $host;
85
              proxy_set_header X-Forwarded-Server $host;
86
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
87
              #proxy_pass http://<ContainerName>:<PortNumber>;
88
              # In our case Container name is as we setup in docker-compose `beservice` and port 8080
89
              proxy_pass http://51.15.45.95:8080;
90
              proxy_max_temp_file_size "1024m";
91
              proxy_read_timeout       "60s";
92

  
93
              add_header X-Frame-Options SAMEORIGIN always;
94

  
95
    }
82 96
  }
83 97
}
proxy-config.json
14 14
  "/analytics": {
15 15
    "target": "http://51.15.45.95:9090",
16 16
    "secure": false
17
  },
18
  "/senslog15": {
19
    "target": "http://51.15.45.95:8080",
20
    "secure": false
17 21
  }
18 22
}
src/app/auth/guards/role.guard.ts
23 23
    state: RouterStateSnapshot
24 24
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
25 25
    const expectedRole: string[] = routeSnapshot.data.expectedRole;
26
    if (expectedRole.includes(this.authService.getUser().userInfo.rights.toString())) {
26
    if (expectedRole.includes(this.authService.getUser().userInfo.rightsId.toString())) {
27 27
      console.log('You have enough rights!');
28 28
     return true;
29 29
    }
src/app/auth/interceptors/auth.interceptor.ts
40 40
    return next.handle(request)
41 41
      .pipe(
42 42
        catchError(err => {
43
          if ((err instanceof HttpErrorResponse && err.status === 504 || err.status === 502 || err.status === 0 || err.status === 500)) {
43
          if ((err instanceof HttpErrorResponse && err.status === 504 || err.status === 502 || err.status === 401 ||
44
            err.status === 0 || err.status === 500)) {
44 45
            return this.handleError(request, next);
45 46
          } else {
46 47
            return throwError(err);
src/app/auth/models/user.ts
1 1
/* tslint:disable */
2 2
/* eslint-disable */
3 3
import {UserInfo} from '../../shared/api/endpoints/models/user-info';
4
import {UserCookie} from '../../shared/api/endpoints/models/user-cookie';
4 5

  
5 6
export interface User {
6 7
  userInfo?: UserInfo;
7 8
  isLoggedIn?: boolean;
8
  userName?: string
9
  userCookie?: UserCookie
9 10
}
src/app/auth/services/auth.service.ts
9 9
import {UserInfo} from '../../shared/api/endpoints/models/user-info';
10 10
import {User} from '../models/user';
11 11
import {GlobalVariable} from '../../globals';
12
import {UserCookie} from '../../shared/api/endpoints/models/user-cookie';
12 13

  
13 14
@Injectable({
14 15
  providedIn: 'root'
......
26 27

  
27 28
  setFromCookie() {
28 29
    const user: User = {
29
      userInfo: {
30
        rights: JSON.parse(localStorage.getItem(GlobalVariable.RIGHTS)),
30
      userCookie: {
31
        rightsID: JSON.parse(localStorage.getItem(GlobalVariable.RIGHTS)),
31 32
        language: this.cookieService.get(GlobalVariable.LANGUAGE),
32 33
        audio: JSON.parse(this.cookieService.get(GlobalVariable.AUDIO)),
33 34
        sessionid: this.cookieService.get(GlobalVariable.SESSION_ID)
34 35
      },
35
      userName: localStorage.getItem(GlobalVariable.USER_NAME),
36 36
      isLoggedIn: true
37 37
    }
38 38
    this.userState.setUser(user);
39 39
  }
40 40

  
41 41
  getUser() {
42
    console.log('Auth Service', this.userState.getUser());
42
    console.log('Auth Service');
43 43
    if (!this.userState.getUser() && this.cookieService.get(GlobalVariable.SESSION_ID)) {
44 44
      console.log('Session in cookie!');
45 45
      this.setFromCookie();
......
54 54
  doLogin(loginInput): Observable<boolean> {
55 55
    return this.loginService.login$Response(loginInput)
56 56
      .pipe(
57
        tap((userInfo: HttpResponse<UserInfo>) => this.setUserFromResponse(userInfo.body, loginInput.username)),
57
        tap((userCookie: HttpResponse<UserCookie>) => this.setUserFromResponse(userCookie.body, loginInput.username)),
58 58
        mapTo(true),
59 59
        catchError(() => {
60 60
          return of<boolean>(false);
......
62 62
      );
63 63
  }
64 64

  
65
  setUserFromResponse(userInfo: UserInfo, username): UserInfo {
66
    userInfo = this.setRights(userInfo, username);
65
  setUserFromResponse(userCookie: UserCookie, username): UserCookie {
67 66
    console.log('Setting user from login!');
68 67
    this.userState.setUser({
69
      userInfo,
70
      isLoggedIn: true,
71
      userName: username
68
      userCookie,
69
      isLoggedIn: true
72 70
    });
73
    this.setSessionStorage(userInfo, username);
74
    return userInfo;
71
    this.setSessionStorage(userCookie, username);
72
    return userCookie;
75 73
  }
76 74

  
77 75
  doLogout() {
......
81 79
    this.router.navigate(['/login']);
82 80
  }
83 81

  
84
  setSessionStorage(userInfo: UserInfo, username) {
82
  setSessionStorage(userCookie: UserCookie, username) {
85 83
    localStorage.setItem(GlobalVariable.USER_NAME, username)
86
    localStorage.setItem(GlobalVariable.RIGHTS, userInfo.rights.toString());
87
  }
88

  
89
  setRights(userInfo: UserInfo, username: string): UserInfo {
90
    // TODO - todle je pene naho... naprd
91
    if (username === 'kiv') {
92
      userInfo.rights = 1;
93
    } else {
94
      userInfo.rights = 2;
95
    }
96
    return userInfo;
84
    localStorage.setItem(GlobalVariable.RIGHTS, userCookie.rightsID.toString());
97 85
  }
98 86
}
src/app/auth/states/user.state.ts
1 1
import {Injectable} from '@angular/core';
2 2
import {BehaviorSubject, Observable} from 'rxjs';
3 3
import {User} from '../models/user';
4
import {AuthService} from '../services/auth.service';
5
import {LoginService} from '../../shared/api/endpoints/services/login.service';
4 6

  
5 7
@Injectable({
6 8
  providedIn: 'root'
......
8 10
export class UserState {
9 11
  private userState$: BehaviorSubject<User> = new BehaviorSubject<User>(null);
10 12

  
11
  constructor() {}
13
  constructor(
14
    private loginService: LoginService
15
  ) {}
12 16

  
13 17
  setUser(user: User): void {
14 18
    this.userState$.next(user);
......
23 27
  }
24 28

  
25 29
  getUser$(refresh: boolean = false): Observable<User> {
30
   if (this.userState$.getValue()){
31
      this.loginService.getUserInfo().subscribe(res => this.userState$.next({...this.userState$.getValue(), userInfo: res}));
32
    }
26 33
    return this.userState$.asObservable();
27 34
  }
28 35

  
src/app/dashboard/components/dashboard.component.ts
5 5
import {Lastpos} from '../../shared/api/endpoints/models/lastpos';
6 6
import {Sensor} from '../../shared/api/endpoints/models/sensor';
7 7
import {Unit} from '../../shared/api/endpoints/models/unit';
8
import {GroupService} from '../../shared/api/endpoints/services/group.service';
9 8
import {DataService} from '../../shared/api/endpoints/services/data.service';
10 9
import {tap} from 'rxjs/operators';
11 10

  
......
22 21
  editedUnit: Unit;
23 22

  
24 23
  constructor(
25
    private groupService: GroupService,
26 24
    private dataService: DataService
27 25
  ) {
28 26
  }
......
31 29
    this.getUnits();
32 30
  }
33 31

  
34
  getGroups() {
35
    console.log('Get Groups');
36
    this.groupService.getGroups({Operation: 'GetGroups'}).pipe(
37
      tap(data => this.groups = data)
38
    ).subscribe();
39
  }
40

  
41 32
  getUnits() {
42 33
    this.dataService.getData().pipe(
43 34
      tap(data => {
src/app/shared/api/endpoints/api.module.ts
6 6

  
7 7
import { LoginService } from './services/login.service';
8 8
import { GroupService } from './services/group.service';
9
import { ObservationService } from './services/observation.service';
10 9
import { DataService } from './services/data.service';
11 10
import { AnalyticsService } from './services/analytics.service';
12 11

  
......
20 19
  providers: [
21 20
    LoginService,
22 21
    GroupService,
23
    ObservationService,
24 22
    DataService,
25 23
    AnalyticsService,
26 24
    ApiConfiguration
src/app/shared/api/endpoints/models.ts
1
export { UserCookie } from './models/user-cookie';
1 2
export { UserInfo } from './models/user-info';
2 3
export { Group } from './models/group';
3 4
export { Unit } from './models/unit';
......
9 10
export { Lastpos } from './models/lastpos';
10 11
export { GeneralInfo } from './models/general-info';
11 12
export { Drivers } from './models/drivers';
12
export { Observation } from './models/observation';
13 13
export { Sensors } from './models/sensors';
14 14
export { SensorsData } from './models/sensors-data';
15 15
export { Data } from './models/data';
16
export { Obser } from './models/obser';
16
export { Observation } from './models/observation';
17 17
export { Statistics } from './models/statistics';
src/app/shared/api/endpoints/models/data.ts
1 1
/* tslint:disable */
2 2
/* eslint-disable */
3
import { Obser } from './obser';
3
import { Observation } from './observation';
4 4
export interface Data {
5
  observation?: Obser;
5
  observation?: Observation;
6 6
}
src/app/shared/api/endpoints/models/obser.ts
1
/* tslint:disable */
2
/* eslint-disable */
3
export interface Obser {
4
  avg?: number;
5
  max?: number;
6
  min?: number;
7
  sum?: number;
8
  timestamp?: string;
9
}
src/app/shared/api/endpoints/models/observation.ts
1 1
/* tslint:disable */
2 2
/* eslint-disable */
3 3
export interface Observation {
4
  gid?: number;
5
  time?: string;
6
  value?: number;
4
  avg?: number;
5
  max?: number;
6
  min?: number;
7
  sum?: number;
8
  timestamp?: string;
7 9
}
src/app/shared/api/endpoints/models/user-cookie.ts
1
/* tslint:disable */
2
/* eslint-disable */
3
export interface UserCookie {
4
  audio?: boolean;
5
  language?: string;
6
  rightsID?: number;
7
  sessionid?: string;
8
}
src/app/shared/api/endpoints/models/user-info.ts
1 1
/* tslint:disable */
2 2
/* eslint-disable */
3 3
export interface UserInfo {
4
  audio?: boolean;
5
  language?: string;
6
  rights?: number;
7
  sessionid?: string;
4
  groupId?: number;
5
  rightsId?: number;
6
  userId?: number;
7
  userName?: string;
8
  userPass?: string;
9
  userRealName?: string;
8 10
}
src/app/shared/api/endpoints/services.ts
1 1
export { LoginService } from './services/login.service';
2 2
export { GroupService } from './services/group.service';
3
export { ObservationService } from './services/observation.service';
4 3
export { DataService } from './services/data.service';
5 4
export { AnalyticsService } from './services/analytics.service';
src/app/shared/api/endpoints/services/login.service.ts
9 9
import { Observable } from 'rxjs';
10 10
import { map, filter } from 'rxjs/operators';
11 11

  
12
import { UserCookie } from '../models/user-cookie';
12 13
import { UserInfo } from '../models/user-info';
13 14

  
14 15

  
......
29 30
  /**
30 31
   * Path part for operation login
31 32
   */
32
  static readonly LoginPath = '/senslog1/ControllerServlet';
33
  static readonly LoginPath = '/senslog15/ControllerServlet';
33 34

  
34 35
  /**
35 36
   * Authorize login.
......
52 53
     * User password
53 54
     */
54 55
    password?: string;
55
  }): Observable<StrictHttpResponse<UserInfo>> {
56
  }): Observable<StrictHttpResponse<UserCookie>> {
56 57

  
57 58
    const rb = new RequestBuilder(this.rootUrl, LoginService.LoginPath, 'post');
58 59
    if (params) {
......
66 67
    })).pipe(
67 68
      filter((r: any) => r instanceof HttpResponse),
68 69
      map((r: HttpResponse<any>) => {
69
        return r as StrictHttpResponse<UserInfo>;
70
        return r as StrictHttpResponse<UserCookie>;
70 71
      })
71 72
    );
72 73
  }
......
92 93
     * User password
93 94
     */
94 95
    password?: string;
95
  }): Observable<UserInfo> {
96
  }): Observable<UserCookie> {
96 97

  
97 98
    return this.login$Response(params).pipe(
99
      map((r: StrictHttpResponse<UserCookie>) => r.body as UserCookie)
100
    );
101
  }
102

  
103
  /**
104
   * Path part for operation getUserInfo
105
   */
106
  static readonly GetUserInfoPath = '/senslog15/rest/user';
107

  
108
  /**
109
   * User information.
110
   *
111
   *
112
   *
113
   * This method provides access to the full `HttpResponse`, allowing access to response headers.
114
   * To access only the response body, use `getUserInfo()` instead.
115
   *
116
   * This method doesn't expect any request body.
117
   */
118
  getUserInfo$Response(params?: {
119
  }): Observable<StrictHttpResponse<UserInfo>> {
120

  
121
    const rb = new RequestBuilder(this.rootUrl, LoginService.GetUserInfoPath, 'get');
122
    if (params) {
123
    }
124

  
125
    return this.http.request(rb.build({
126
      responseType: 'json',
127
      accept: 'application/json'
128
    })).pipe(
129
      filter((r: any) => r instanceof HttpResponse),
130
      map((r: HttpResponse<any>) => {
131
        return r as StrictHttpResponse<UserInfo>;
132
      })
133
    );
134
  }
135

  
136
  /**
137
   * User information.
138
   *
139
   *
140
   *
141
   * This method provides access to only to the response body.
142
   * To access the full response (for headers, for example), `getUserInfo$Response()` instead.
143
   *
144
   * This method doesn't expect any request body.
145
   */
146
  getUserInfo(params?: {
147
  }): Observable<UserInfo> {
148

  
149
    return this.getUserInfo$Response(params).pipe(
98 150
      map((r: StrictHttpResponse<UserInfo>) => r.body as UserInfo)
99 151
    );
100 152
  }
src/app/shared/api/endpoints/services/observation.service.ts
1
/* tslint:disable */
2
/* eslint-disable */
3
import { Injectable } from '@angular/core';
4
import { HttpClient, HttpResponse } from '@angular/common/http';
5
import { BaseService } from '../base-service';
6
import { ApiConfiguration } from '../api-configuration';
7
import { StrictHttpResponse } from '../strict-http-response';
8
import { RequestBuilder } from '../request-builder';
9
import { Observable } from 'rxjs';
10
import { map, filter } from 'rxjs/operators';
11

  
12
import { Observation } from '../models/observation';
13

  
14

  
15
/**
16
 * Observations endpoints
17
 */
18
@Injectable({
19
  providedIn: 'root',
20
})
21
export class ObservationService extends BaseService {
22
  constructor(
23
    config: ApiConfiguration,
24
    http: HttpClient
25
  ) {
26
    super(config, http);
27
  }
28

  
29
  /**
30
   * Path part for operation getObservation
31
   */
32
  static readonly GetObservationPath = '/senslog1/SensorService?Operation=GetObservations';
33

  
34
  /**
35
   * Get observation.
36
   *
37
   *
38
   *
39
   * This method provides access to the full `HttpResponse`, allowing access to response headers.
40
   * To access only the response body, use `getObservation()` instead.
41
   *
42
   * This method doesn't expect any request body.
43
   */
44
  getObservation$Response(params: {
45
    unit_id: number;
46
    sensor_id: number;
47
    from?: string;
48
    to?: string;
49
  }): Observable<StrictHttpResponse<Array<Observation>>> {
50

  
51
    const rb = new RequestBuilder(this.rootUrl, ObservationService.GetObservationPath, 'get');
52
    if (params) {
53
      rb.query('unit_id', params.unit_id, {});
54
      rb.query('sensor_id', params.sensor_id, {});
55
      rb.query('from', params.from, {});
56
      rb.query('to', params.to, {});
57
    }
58

  
59
    return this.http.request(rb.build({
60
      responseType: 'json',
61
      accept: 'application/json'
62
    })).pipe(
63
      filter((r: any) => r instanceof HttpResponse),
64
      map((r: HttpResponse<any>) => {
65
        return r as StrictHttpResponse<Array<Observation>>;
66
      })
67
    );
68
  }
69

  
70
  /**
71
   * Get observation.
72
   *
73
   *
74
   *
75
   * This method provides access to only to the response body.
76
   * To access the full response (for headers, for example), `getObservation$Response()` instead.
77
   *
78
   * This method doesn't expect any request body.
79
   */
80
  getObservation(params: {
81
    unit_id: number;
82
    sensor_id: number;
83
    from?: string;
84
    to?: string;
85
  }): Observable<Array<Observation>> {
86

  
87
    return this.getObservation$Response(params).pipe(
88
      map((r: StrictHttpResponse<Array<Observation>>) => r.body as Array<Observation>)
89
    );
90
  }
91

  
92
}
src/app/shared/api/openapi.yaml
23 23
  description: Analitics endpoints
24 24

  
25 25
paths:
26
  /senslog1/ControllerServlet:
26
  /senslog15/ControllerServlet:
27 27
    post:
28 28
      tags:
29 29
      - login
......
40 40
          schema:
41 41
            type: string
42 42
          description: User password
43
      responses:
44
        200:
45
          description: successful operation
46
          content:
47
            application/json:
48
              schema:
49
                $ref: '#/components/schemas/UserCookie'
50

  
51
  /senslog15/rest/user:
52
    get:
53
      tags:
54
        - login
55
      summary: User information
56
      operationId: getUserInfo
43 57
      responses:
44 58
        200:
45 59
          description: successful operation
......
80 94
                items:
81 95
                  $ref: '#/components/schemas/Group'
82 96

  
83
  /senslog1/SensorService?Operation=GetObservations:
84
    get:
85
      tags:
86
        - observation
87
      summary: Get observation
88
      operationId: getObservation
89
      parameters:
90
        - in: query
91
          name: unit_id
92
          required: true
93
          schema:
94
            type: integer
95
        - in: query
96
          name: sensor_id
97
          required: true
98
          schema:
99
            type: integer
100
        - in: query
101
          name: from
102
          schema:
103
            type: string
104
        - in: query
105
          name: to
106
          schema:
107
            type: string
108
      responses:
109
        200:
110
          description: Get observation for unitId and sensorId
111
          content:
112
            application/json:
113
              schema:
114
                type: array
115
                items:
116
                  $ref: '#/components/schemas/Observation'
117

  
118 97
  /senslog1/DataService?Operation=GetUnits:
119 98
    get:
120 99
      tags:
......
189 168

  
190 169
components:
191 170
  schemas:
192
    UserInfo:
171
    UserCookie:
193 172
      type: object
194 173
      properties:
195 174
        sessionid:
......
198 177
          type: string
199 178
        audio:
200 179
          type: boolean
201
        rights:
180
        rightsID:
181
          type: integer
182

  
183
    UserInfo:
184
      type: object
185
      properties:
186
        userId:
187
          type: integer
188
        userName:
189
          type: string
190
        userPass:
191
          type: string
192
        userRealName:
193
          type: string
194
        groupId:
195
          type: integer
196
        "rightsId":
202 197
          type: integer
203 198

  
204 199
    Group:
......
303 298
    Drivers:
304 299
      type: array
305 300

  
306
    Observation:
307
      type: object
308
      properties:
309
        gid:
310
          type: integer
311
        time:
312
          type: string
313
          format: date-time
314
        value:
315
          type: number
316

  
317 301
    Sensors:
318 302
      type: object
319 303
      properties:
......
334 318
      type: object
335 319
      properties:
336 320
        observation:
337
          $ref: '#/components/schemas/Obser'
321
          $ref: '#/components/schemas/Observation'
338 322

  
339
    Obser:
323
    Observation:
340 324
      type: object
341 325
      properties:
342 326
        min:
src/app/shared/nav-bar/components/nav-bar.component.html
10 10
            <li class="nav-item">
11 11
              <a class="nav-link" [routerLink]="['/dashboard']"><h2>Dashboard</h2></a>
12 12
            </li>
13
            <li *ngIf="loggedUser.userInfo.rights == 1" class="nav-item">
13
            <li *ngIf="loggedUser?.userInfo?.rightsId == 1" class="nav-item">
14 14
              <a class="nav-link" [routerLink]="['/administration']"><h2>Administration</h2></a>
15 15
            </li>
16 16
          </ul>
......
20 20
          </a>
21 21
          <ul class="navbar-nav right">
22 22
            <li class="nav-item">
23
              <a class="nav-link" href="#"><h2>User:&nbsp;<strong>{{loggedUser?.userName?.toUpperCase()}}</strong></h2></a>
23
              <a class="nav-link" href="#"><h2>User:&nbsp;<strong>{{loggedUser?.userInfo?.userName.toUpperCase()}}</strong></h2></a>
24 24
            </li>
25 25
            <li class="nav-item">
26 26
              <a class='nav-link' [routerLink]="['/login']" (click)="logOut()"><h2>Logout</h2></a>

Také k dispozici: Unified diff