Skip to content

Commit

Permalink
[#6] add login call & handle jwt with http interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
philipphoeninger committed Oct 22, 2024
1 parent 3611284 commit 49a4e86
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { IdentityApiService } from '../shared/identity-api.service';
import { LoginModel } from '../shared/login.model';
import { finalize, map } from 'rxjs/operators';
import { Router } from '@angular/router';

@Component({
selector: 'fs-login',
Expand Down Expand Up @@ -38,12 +42,31 @@ export class LoginComponent implements OnInit {
protected password?: string;
public keepSignedIn: boolean = false;

constructor() {}
constructor(
private identityApiService: IdentityApiService,
private router: Router,
) {}

ngOnInit() {}

onSubmit(form: NgForm, event: Event) {
event.preventDefault();
console.log('Form submitted', form.value);
let loginCommand = new LoginModel(this.username!, this.password!);

// TODO: start spinner
this.identityApiService
.login(loginCommand)
.pipe(
map((response: any) => {
debugger;
// TODO: check if login succeeded (check status code)
localStorage.setItem('fileshare-token', response.token);
this.router.navigateByUrl('/home');
}),
finalize(() => {
// TODO: stop spinner
}),
)
.subscribe();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
const jwt = localStorage.getItem('fileshare-token');
if (jwt !== null) {
req = req.clone({
headers: req.headers.set('Authorization', 'bearer ' + jwt),
});
}
return next(req);
};

0 comments on commit 49a4e86

Please sign in to comment.