authentication suppoert - jwt

This commit is contained in:
PawelJa 2019-01-10 20:06:30 +01:00
parent a83ee5e9bc
commit 8e3024e8b1
21 changed files with 342 additions and 153 deletions

View File

@ -1,10 +1,9 @@
import { BrowserModule } from '@angular/platform-browser';
import {CUSTOM_ELEMENTS_SCHEMA, LOCALE_ID, NgModule} from '@angular/core';
import { AppComponent } from './app.component';
import { AddTermsComponent } from './components/add-terms/add-terms.component';
import {RouterModule} from '@angular/router';
import {appRoutes} from './app.router.module';
import {BrowserModule} from '@angular/platform-browser';
import {CUSTOM_ELEMENTS_SCHEMA, NgModule} from '@angular/core';
import {MAT_DATE_LOCALE} from '@angular/material';
import {AppComponent} from './app.component';
import {AddTermsComponent} from './components/add-terms/add-terms.component';
import {AppRoutingModule} from './app.router.module';
import {MaterialModule} from './material.module';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@ -13,9 +12,23 @@ import {TestComponent} from './components/test/test.component';
import {NavBarComponent} from './components/nav-bar/nav-bar.component';
import {TermListComponent} from './components/term-list/term-list.component';
import {CreateQueryComponent} from './components/dialogs/create-query/create-query.component';
import { AdminMenuComponent } from './components/admin-menu/admin-menu.component';
import { TermListAdminComponent } from './components/term-list-admin/term-list-admin.component';
import { EditTermAdminComponent } from './components/dialogs/edit-term-admin/edit-term-admin.component';
import {AdminMenuComponent} from './components/admin-menu/admin-menu.component';
import {TermListAdminComponent} from './components/term-list-admin/term-list-admin.component';
import {EditTermAdminComponent} from './components/dialogs/edit-term-admin/edit-term-admin.component';
import {AngularFireModule} from 'angularfire2';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {LoginComponent} from './components/login/login.component';
import {AuthService} from './services/auth.service';
import {AuthGuardsService} from './services/auth-guards.service';
const config = {
apiKey: 'AIzaSyBuOHXooBv4bsWWgEZxd7Y86TrxkrbYZIU',
authDomain: 'szt-visio.firebaseapp.com',
databaseURL: 'https://szt-visio.firebaseio.com',
projectId: 'szt-visio',
storageBucket: 'szt-visio.appspot.com',
messagingSenderId: '298719712363'
};
@NgModule({
declarations: [
@ -27,7 +40,8 @@ import { EditTermAdminComponent } from './components/dialogs/edit-term-admin/edi
TestComponent,
AdminMenuComponent,
TermListAdminComponent,
EditTermAdminComponent
EditTermAdminComponent,
LoginComponent
],
imports: [
BrowserModule,
@ -36,14 +50,14 @@ import { EditTermAdminComponent } from './components/dialogs/edit-term-admin/edi
ReactiveFormsModule,
BrowserAnimationsModule,
HttpClientModule,
RouterModule.forRoot(
appRoutes,
// { enableTracking: true }
)
AppRoutingModule,
AngularFireModule.initializeApp(config),
AngularFireAuthModule
],
entryComponents: [CreateQueryComponent, EditTermAdminComponent],
providers: [ ],
providers: [AuthService, AuthGuardsService, {provide: MAT_DATE_LOCALE, useValue: 'pl-PL'}],
bootstrap: [AppComponent],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
export class AppModule {
}

View File

@ -1,29 +1,44 @@
import {AddTermsComponent} from './components/add-terms/add-terms.component';
import {Routes} from '@angular/router';
import {RouterModule, Routes} from '@angular/router';
import {TestComponent} from './components/test/test.component';
import {TermListComponent} from './components/term-list/term-list.component';
import {AdminMenuComponent} from './components/admin-menu/admin-menu.component';
import {TermListAdminComponent} from './components/term-list-admin/term-list-admin.component';
import {NgModule} from '@angular/core';
import {LoginComponent} from './components/login/login.component';
import {AuthGuardsService} from './services/auth-guards.service';
export const appRoutes: Routes = [
{
path: 'list-term',
component: TermListComponent
},
{
path: 'test',
component: TestComponent
},
{
path: 'admin',
component: AdminMenuComponent
component: AdminMenuComponent,
canActivate: [AuthGuardsService],
children: [
{
path: 'add-term',
component: AddTermsComponent
},
{
path: 'term-list-admin',
component: TermListAdminComponent
}
]
},
{
path: 'admin/add-term',
component: AddTermsComponent
},
{
path: 'admin/term-list-admin',
component: TermListAdminComponent
path: 'login',
component: LoginComponent
}
]
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

View File

@ -1,6 +1,8 @@
import { Component, OnInit } from '@angular/core';
import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup, FormGroupDirective, NgForm, Validators} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material';
import {ErrorStateMatcher, MatSnackBar} from '@angular/material';
import {TermAdminService} from '../../services/termin-admin-service.service';
import {NewTerms} from '../../models/NewTerms';
@Component({
selector: 'app-add-terms',
@ -12,23 +14,23 @@ export class AddTermsComponent implements OnInit {
form: FormGroup;
yearItems = [ 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030 ];
yearItems = [2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030];
months = [
{ key: 1, value: 'Styczeń'},
{ key: 2, value: 'Luty'},
{ key: 3, value: 'Marzec'},
{ key: 4, value: 'Kwieceń'},
{ key: 5, value: 'Maj'},
{ key: 6, value: 'Czerwiec'},
{ key: 7, value: 'Lipiec'},
{ key: 8, value: 'Sierpień'},
{ key: 9, value: 'Wrzesień'},
{ key: 10, value: 'Październik'},
{ key: 11, value: 'Listopad'},
{ key: 12, value: 'Grudzień'}
]
{key: 1, value: 'Styczeń'},
{key: 2, value: 'Luty'},
{key: 3, value: 'Marzec'},
{key: 4, value: 'Kwieceń'},
{key: 5, value: 'Maj'},
{key: 6, value: 'Czerwiec'},
{key: 7, value: 'Lipiec'},
{key: 8, value: 'Sierpień'},
{key: 9, value: 'Wrzesień'},
{key: 10, value: 'Październik'},
{key: 11, value: 'Listopad'},
{key: 12, value: 'Grudzień'}
];
constructor(private formBuilder: FormBuilder) {
constructor(private formBuilder: FormBuilder, private termAdminService: TermAdminService, public snackBar: MatSnackBar) {
const controls = this.months.map(c => new FormControl(false));
this.form = this.formBuilder.group({
@ -46,28 +48,20 @@ export class AddTermsComponent implements OnInit {
.map((v, i) => v ? this.months[i].key : null)
.filter(v => v !== null);
console.log(selectedOrderIds);
console.log(this.form.controls.year.value);
const newTerms = new NewTerms();
newTerms.year = this.form.controls.year.value;
newTerms.months = selectedOrderIds;
this.termAdminService.createTerm(newTerms).subscribe(
x => {
this.openSnackBar('Dodano terminy !');
},
error => this.openSnackBar('Coś poszło nie tak.. Sprawdź poprawność terminów i spróbuj ponownie'));
}
createForm() {
// this.form = new FormGroup({
// year: new FormControl(null, Validators.required),
// months: new FormControl(false, Validators.requiredTrue),
// 1: new FormControl(false),
// 2: new FormControl(false),
// 3: new FormControl(false),
// 4: new FormControl(false),
// 5: new FormControl(false),
// 6: new FormControl(false),
// 7: new FormControl(false),
// 8: new FormControl(false),
// 9: new FormControl(false),
// 10: new FormControl(false),
// 11: new FormControl(false),
// 12: new FormControl(false)
// });
openSnackBar(message: string) {
this.snackBar.open(message, null, {
duration: 2500,
});
}
do() {
@ -75,9 +69,3 @@ export class AddTermsComponent implements OnInit {
}
}
// export class MyErrorStateMatcher implements ErrorStateMatcher {
// isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
// const isSubmitted = form && form.submitted;
// return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
// }
// }

View File

@ -1,5 +1,6 @@
<a routerLink="add-term">Dodaj terminy</a>
<a routerLink="term-list-admin">Terminy</a>
<a routerLink="test">Test</a>
<br>
<br>
<router-outlet></router-outlet>

View File

@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
@Component({
selector: 'app-admin-menu',
@ -7,9 +8,13 @@ import { Component, OnInit } from '@angular/core';
})
export class AdminMenuComponent implements OnInit {
constructor() { }
constructor(public authService: AuthService) { }
ngOnInit() {
}
logout() {
this.authService.logout();
}
}

View File

@ -3,11 +3,35 @@ import {MAT_DIALOG_DATA, MatDialogRef, MatSnackBar} from '@angular/material';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {Query} from '../../../models/Query';
import {QueryService} from '../../../services/query.service';
// @ts-ignore
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'LL',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'app-create-query',
templateUrl: './create-query.component.html',
styleUrls: ['./create-query.component.css']
styleUrls: ['./create-query.component.css'],
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class CreateQueryComponent {

View File

@ -1,8 +1,9 @@
import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {MAT_DIALOG_DATA, MatDialogRef, MatSnackBar} from '@angular/material';
import {Term} from '../../../models/Term';
import {FormControl, FormGroup, Validator, Validators} from '@angular/forms';
import {TermAdminService} from '../../../services/termin-admin-service.service';
import {TermListAdminComponent} from '../../term-list-admin/term-list-admin.component';
@Component({
selector: 'app-edit-term-admin',
@ -15,7 +16,7 @@ export class EditTermAdminComponent implements OnInit {
statuses = ['wolny', 'zarezerwowany'];
constructor(private dialogRef: MatDialogRef<EditTermAdminComponent>,
@Inject(MAT_DIALOG_DATA) public data: Term, private termAdminService: TermAdminService) {
@Inject(MAT_DIALOG_DATA) public data: Term, private termAdminService: TermAdminService, public snackBar: MatSnackBar) {
}
ngOnInit() {
@ -33,11 +34,24 @@ export class EditTermAdminComponent implements OnInit {
onSubmit() {
const term = new Term();
const dateTemp = new Date(this.form.controls.date.value);
term.date = dateTemp.getFullYear() + '-' + dateTemp.getMonth() + 1 + '-' + dateTemp.getDay();
// const year = String(dateTemp.getFullYear());
// @ts-ignore
term.date = String(dateTemp.getFullYear() + '-' + dateTemp.getMonth() + 1 + '-' + dateTemp.getDay());
term.status = this.form.controls.status.value;
term.contractno = this.form.controls.contractno.value;
console.log(term);
this.termAdminService.updateTerm(term);
this.termAdminService.updateTerm(term).subscribe(
x => {
this.openSnackBar('Zapisano zmiany !');
this.onAbort();
},
error => this.openSnackBar('Coś poszło nie tak.. Spróbuj ponownie'));
}
openSnackBar(message: string) {
this.snackBar.open(message, null, {
duration: 2500,
});
}
}

View File

@ -0,0 +1,17 @@
<!--<div *ngIf="authService.user">-->
<form #formData="ngForm">
<label>Email</label>
<input ngModel type="email" name="email" required>
<br>
<label>Hasło</label>
<input ngModel type="password" name="password" required>
<button (click)="login(formData)" [disabled]="formData.invalid">Zaloguj</button>
<button (click)="register()">Rejestracja</button>
</form>
<!--</div>-->
<div *ngIf="authService.user">
<button (click)="logout()">Wyloguj</button>
</div>
sadsadas

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,28 @@
import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {NgForm} from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(public authService: AuthService) { }
ngOnInit() {
}
login(formData: NgForm) {
this.authService.login(formData.controls.email.value, formData.controls.password.value);
}
register() {
this.authService.register();
}
logout() {
}
}

View File

@ -2,6 +2,9 @@
<a routerLink="/list-term">Terminarz</a>
<a routerLink="/test">Add term2</a>
<form class="form-inline">
<div *ngIf="authService.user" style="margin-right: 10px">
<button (click)="logout()" type="button" class="btn btn-sm btn-info">Wyloguj</button>
</div>
<button class="btn btn-sm btn-outline-info my-2 my-sm-9" type="button" routerLink="admin">Admin panel</button>
</form>
</nav>

View File

@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
@Component({
selector: 'app-nav-bar',
@ -7,9 +8,12 @@ import { Component, OnInit } from '@angular/core';
})
export class NavBarComponent implements OnInit {
constructor() { }
constructor(public authService: AuthService) { }
ngOnInit() {
}
logout() {
this.authService.logout();
}
}

View File

@ -19,7 +19,6 @@
</mat-form-field>
<button mat-raised-button color="primary" (click)="search()" [disabled]="form.invalid">Szukaj</button>
</form>
<button mat-raised-button color="primary" (click)="openDialog()">Zarezerwuj termin</button>
</div>
<br>
<div style="margin: 0 auto; width: 80%">

View File

@ -1,10 +1,10 @@
import { Component, OnInit } from '@angular/core';
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {Month} from '../../models/Month';
import {Observable} from 'rxjs';
import {Term} from '../../models/Term';
import {TermService} from '../../services/term.service';
import {MatDialog} from '@angular/material';
import {MatDialog, MatSnackBar} from '@angular/material';
import {DataSources} from '../environments/DataSources';
import {CreateQueryComponent} from '../dialogs/create-query/create-query.component';
import {PeriodicElement} from '../term-list/term-list.component';
@ -24,7 +24,7 @@ export class TermListAdminComponent implements OnInit {
allTerms$: Observable<Array<Term>>;
constructor(private termService: TermService, private termAdminService: TermAdminService, public dialog: MatDialog) {
constructor(private termService: TermService, private termAdminService: TermAdminService, public dialog: MatDialog, public snackBar: MatSnackBar) {
this.yearsList = DataSources.yearsList;
this.monthsList = DataSources.monthsList;
}
@ -39,26 +39,24 @@ export class TermListAdminComponent implements OnInit {
}
search() {
console.log(this.form.value);
this.termService.getTerms(this.form.controls.year.value, this.form.controls.month.value);
}
editTerm(event: Term) {
console.log('asdasdasd');
this.openDialog(event);
}
deleteTerm(event: Term) {
const date = new Date(event.date);
event.date = date.getFullYear() + '-' + date.getMonth() + 1 + '-' + date.getDay();
event.date = event.date;
event.status = 'wolny';
event.contractno = '';
console.log('data ', event.date);
this.termAdminService.deleteTerm(event);
}
post() {
this.termAdminService.postTest();
this.termAdminService.deleteTerm(event).subscribe(
x => {
this.openSnackBar('Zwolniono termin !');
},
error => {
this.openSnackBar('Coś poszło nie tak.. Spróbuj ponownie');
});
}
openDialog(term: Term): void {
@ -72,4 +70,10 @@ export class TermListAdminComponent implements OnInit {
});
}
openSnackBar(message: string) {
this.snackBar.open(message, null, {
duration: 2500,
});
}
}

View File

@ -0,0 +1,9 @@
export class NewTerms {
months: number[];
year: number
constructor() {
this.months = [];
this.year = null;
}
}

View File

@ -0,0 +1,12 @@
import { TestBed } from '@angular/core/testing';
import { AuthGuardsService } from './auth-guards.service';
describe('AuthGuardsService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: AuthGuardsService = TestBed.get(AuthGuardsService);
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,22 @@
import {Injectable} from '@angular/core';
import {CanActivate} from '@angular/router/src/interfaces';
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
import {AngularFireAuth} from 'angularfire2/auth';
import {AuthService} from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardsService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.user) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}

View File

@ -0,0 +1,12 @@
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: AuthService = TestBed.get(AuthService);
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,40 @@
import {Injectable} from '@angular/core';
import {AngularFireAuth} from 'angularfire2/auth';
import {User} from 'firebase';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
user: User;
constructor(private angularFireAuth: AngularFireAuth, private router: Router) {
angularFireAuth.authState.subscribe(user => {
this.user = user;
});
}
login(email: string, password: string) {
this.angularFireAuth.auth.signInWithEmailAndPassword(email, password).then(user => {
console.log(user);
this.router.navigate(['/admin']);
}).catch(err => {
console.log(err);
});
}
register() {
this.angularFireAuth.auth.createUserWithEmailAndPassword('test@op.pl', 'password').then(user => {
console.log(user);
}).catch(err => {
console.log(err);
});
}
logout() {
this.angularFireAuth.auth.signOut();
this.router.navigate(['']);
}
}

View File

@ -1,8 +1,9 @@
import { Injectable } from '@angular/core';
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {environment} from '../../environments/environment';
import {Term} from '../models/Term';
import {RequestOptions} from '@angular/http';
import {NewTerms} from '../models/NewTerms';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
@ -12,9 +13,10 @@ const httpOptions = {
providedIn: 'root'
})
export class TermAdminService {
endpoint = 'term'
endpoint = 'term';
constructor(private httpClient: HttpClient) { }
constructor(private httpClient: HttpClient) {
}
deleteTerm(term: any) {
const headers = new HttpHeaders();
@ -25,17 +27,10 @@ export class TermAdminService {
// @ts-ignore
return this.httpClient.delete<Term>(environment.API_BACK + this.endpoint, new RequestOptions({
// @ts-ignore
headers: headers,
body: term
}))
.subscribe(
x => {
console.log('usunięto');
},
err => {
console.log('błąd usuwania');
}
);
}));
}
updateTerm(term: any) {
@ -43,54 +38,12 @@ export class TermAdminService {
headers.set('Content-Type', 'application/json; charset=utf-8');
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// @ts-ignore
return this.httpClient.put<Term>(environment.API_BACK + this.endpoint, term, headers)
.subscribe(
x => {
console.log('zaktualizowane');
},
err => {
console.log('niezaktualizowano');
}
);
return this.httpClient.put<Term>(environment.API_BACK + this.endpoint, term, headers);
}
postTest() {
console.log('testuje');
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.httpClient.post<any>('http://localhost:8080/test', {'asdasd': 15561}, httpOptions)
.subscribe(
x => {
console.log('usunięto');
},
err => {
console.log('błąd usuwania');
});
// this.httpClient.delete('http://localhost:8080/test', {headers: headers})
// .subscribe(
// x => {
// console.log('usunięto');
// },
// err => {
// console.log('błąd usuwania');
// });
createTerm(newTerms: NewTerms) {
return this.httpClient.post(environment.API_BACK + this.endpoint, newTerms, httpOptions);
}
deleteTest() {
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.httpClient.delete<any>('http://localhost:8080/test', httpOptions)
.subscribe(
x => {
console.log('usunięto');
},
err => {
console.log('błąd usuwania');
});
}
}