adjusted login and signup post operations to work with forms

added a jwt interceptor
This commit is contained in:
2020-07-30 17:14:45 +02:00
parent 48d620e878
commit 4f2c149f5a
14 changed files with 81 additions and 25 deletions

View File

@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpParams } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@@ -23,7 +23,10 @@ export class AccountService {
}
login(username, password) {
return this.httpClient.post<User>(environment.apiUrl + '/fake_login', { username, password })
const body = new HttpParams()
.set('username', username)
.set('password', password);
return this.httpClient.post<User>(environment.apiUrl + '/login', body)
.pipe((map(user => {
localStorage.setItem('user', JSON.stringify(user));
this.userSubject.next(user);
@@ -32,7 +35,11 @@ export class AccountService {
}
register(user) {
return this.httpClient.post<User>(environment.apiUrl + '/fake_registration', user);
const body = new HttpParams()
.set('username', user.username)
.set('password', user.password)
.set('email', user.email);
return this.httpClient.post(environment.apiUrl + '/signup', body);
}
}

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { JwtInterceptor } from './jwt.interceptor';
describe('JwtInterceptor', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
JwtInterceptor
]
}));
it('should be created', () => {
const interceptor: JwtInterceptor = TestBed.inject(JwtInterceptor);
expect(interceptor).toBeTruthy();
});
});

View File

@@ -0,0 +1,31 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { AccountService } from './account.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private accountService: AccountService) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const user = this.accountService.userValue;
const isLoggedIn = user && user.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${user.token}`
}
});
}
return next.handle(request);
}
}

View File

@@ -22,7 +22,7 @@
<span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
Login
</button>
<a mat-button routerLink="/register">Sign up</a>
<a mat-button routerLink="/signup">Sign up</a>
</div>
</form>
</mat-card-content>

View File

@@ -1,5 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { FormBuilder, Validators} from '@angular/forms';
import { AccountService } from '../account.service';
import { ActivatedRoute, Router } from '@angular/router';
import { first } from 'rxjs/operators';
@@ -10,16 +10,16 @@ import { first } from 'rxjs/operators';
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: FormGroup = new FormGroup({
username: new FormControl(''),
password: new FormControl(''),
form = this.formBuilder.group({
username: ['', Validators.required],
password: ['', [Validators.required, Validators.minLength(15)]],
});
loading = false;
returnUrl = this.activatedRoute.snapshot.queryParams['returnUrl'] || '/';
onLogin() {
this.loading = true;
this.accountService.login(this.form.controls['username'], this.form.controls['password'])
this.accountService.login(this.form.get('username').value, this.form.get('password').value)
.pipe(first())
.subscribe(data => {
this.router.navigate([this.returnUrl]);
@@ -33,6 +33,7 @@ export class LoginComponent implements OnInit {
constructor(private accountService: AccountService,
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder,
private router: Router,
) { }

View File

@@ -1,20 +1,20 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RegisterComponent } from './register.component';
import { SignupComponent } from './signup.component';
describe('RegisterComponent', () => {
let component: RegisterComponent;
let fixture: ComponentFixture<RegisterComponent>;
let component: SignupComponent;
let fixture: ComponentFixture<SignupComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ RegisterComponent ]
declarations: [ SignupComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
fixture = TestBed.createComponent(SignupComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

View File

@@ -8,10 +8,10 @@ import { PasswordErrorStateMatcher } from './password-error-state-matcher';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class RegisterComponent implements OnInit {
export class SignupComponent implements OnInit {
form = this.formBuilder.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],

View File

@@ -4,7 +4,7 @@ import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AuthGuard } from './account/auth.guard';
import { LoginComponent } from './account/login/login.component';
import { RegisterComponent } from './account/register/register.component';
import { SignupComponent } from './account/signup/signup.component';
const gameModule = () => import('./game/game.module').then(x => x.GameModule);
@@ -13,7 +13,7 @@ const routes: Routes = [
{ path: '', component: AppComponent, canActivate: [AuthGuard] },
// { path: '', redirectTo: '/game', pathMatch: 'prefix', canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'game', loadChildren: gameModule, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '' },
];

View File

@@ -1,5 +1,5 @@
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
@@ -13,15 +13,15 @@ import { MatInputModule } from '@angular/material/input';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './account/login/login.component';
import { RegisterComponent } from './account/register/register.component';
import { fakeBackendProvider } from './utils/fake-backend';
import { SignupComponent } from './account/signup/signup.component';
import { GameModule } from './game/game.module';
import { JwtInterceptor } from './account/jwt.interceptor';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
SignupComponent,
],
imports: [
HttpClientModule,
@@ -37,7 +37,8 @@ import { GameModule } from './game/game.module';
GameModule,
],
providers: [
fakeBackendProvider,
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
// fakeBackendProvider,
],
exports: [
],

View File

@@ -4,7 +4,7 @@
export const environment = {
production: false,
apiUrl: 'http://localhost:4200',
apiUrl: 'http://localhost:5005',
};
/*