Use fetch API for login and getProfile calls

This commit is contained in:
William Brawner 2022-11-08 04:36:00 +00:00
parent a7ad95eff8
commit 7fa6f2a1b9
5 changed files with 37 additions and 31 deletions

View file

@ -47,7 +47,7 @@ export class AppComponent implements OnInit {
if (savedUser) { if (savedUser) {
this.user.next(savedUser); this.user.next(savedUser);
} }
this.twigsService.getProfile(userId).subscribe(fetchedUser => { this.twigsService.getProfile(userId).then(fetchedUser => {
this.storage.setItem('user', JSON.stringify(fetchedUser)); this.storage.setItem('user', JSON.stringify(fetchedUser));
this.user.next(fetchedUser); this.user.next(fetchedUser);
if (unauthenticatedRoutes.indexOf(this.location.path()) != -1) { if (unauthenticatedRoutes.indexOf(this.location.path()) != -1) {

View file

@ -25,22 +25,22 @@ export class TwigsHttpService implements TwigsService {
private storage: Storage private storage: Storage
) { } ) { }
login(email: string, password: string): Observable<User> { login(email: string, password: string): Promise<User> {
return new Observable(emitter => { return fetch(this.apiUrl + '/users/login', {
const params = { method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
'username': email, 'username': email,
'password': password 'password': password
}; })
this.http.post<AuthToken>(this.apiUrl + '/users/login', params, this.options) })
.subscribe( .then(res => res.json())
auth => { .then((auth: AuthToken) => {
// TODO: Use token expiration to determine cookie expiration
this.storage.setItem('Authorization', auth.token); this.storage.setItem('Authorization', auth.token);
this.storage.setItem('userId', auth.userId); this.storage.setItem('userId', auth.userId);
this.getProfile(auth.userId).subscribe(user => emitter.next(user), error => emitter.error(error)); return this.getProfile(auth.userId);
},
error => emitter.error(error)
);
}); });
} }
@ -307,8 +307,14 @@ export class TwigsHttpService implements TwigsService {
} }
// Users // Users
getProfile(id: string): Observable<User> { getProfile(id: string): Promise<User> {
return this.http.get<User>(`${this.apiUrl}/users/${id}`, this.options); return fetch(`${this.apiUrl}/users/${id}`, {
credentials: 'include',
headers: {
'Authorization': `Bearer ${this.storage.getItem('Authorization')}`
}
})
.then(res => res.json());
} }
getUsersByUsername(username: string): Observable<User[]> { getUsersByUsername(username: string): Observable<User[]> {

View file

@ -27,15 +27,15 @@ export class TwigsLocalService implements TwigsService {
private categories: Category[] = []; private categories: Category[] = [];
// Auth // Auth
login(email: string, password: string): Observable<User> { login(email: string, password: string): Promise<User> {
return new Observable(subscriber => { return new Promise((resolve, reject) => {
const filteredUsers = this.users.filter(user => { const filteredUsers = this.users.filter(user => {
return (user.email === email || user.username === email); return (user.email === email || user.username === email);
}); });
if (filteredUsers.length !== 0) { if (filteredUsers.length !== 0) {
subscriber.next(filteredUsers[0]); resolve(filteredUsers[0]);
} else { } else {
subscriber.error('No users found'); reject('No users found');
} }
}); });
} }
@ -313,9 +313,9 @@ export class TwigsLocalService implements TwigsService {
} }
// Users // Users
getProfile(id: string): Observable<User> { getProfile(id: string): Promise<User> {
return new Observable(subscriber => { return new Promise((resolve, reject) => {
subscriber.error("Not yet implemented") reject("Not yet implemented")
}); });
} }

View file

@ -7,7 +7,7 @@ import { Transaction } from '../transactions/transaction';
export interface TwigsService { export interface TwigsService {
// Auth // Auth
login(email: string, password: string): Observable<User>; login(email: string, password: string): Promise<User>;
register(username: string, email: string, password: string): Observable<User>; register(username: string, email: string, password: string): Observable<User>;
logout(): Observable<void>; logout(): Observable<void>;
@ -54,7 +54,7 @@ export interface TwigsService {
updateTransaction(id: string, changes: object): Observable<Transaction>; updateTransaction(id: string, changes: object): Observable<Transaction>;
deleteTransaction(id: string): Observable<void>; deleteTransaction(id: string): Observable<void>;
getProfile(id: string): Observable<User>; getProfile(id: string): Promise<User>;
getUsersByUsername(username: string): Observable<User[]>; getUsersByUsername(username: string): Observable<User[]>;
} }

View file

@ -32,13 +32,13 @@ export class LoginComponent implements OnInit {
login(): void { login(): void {
this.isLoading = true; this.isLoading = true;
this.twigsService.login(this.email, this.password) this.twigsService.login(this.email, this.password)
.subscribe(user => { .then(user => {
this.app.user.next(user); this.app.user.next(user);
this.router.navigate([this.redirect || '/']) this.router.navigate([this.redirect || '/'])
}, })
error => { .catch(error => {
console.error(error) console.error(error)
//TODO: Replace this with an in-app dialog // TODO: Replace this with an in-app dialog
alert("Login failed. Please verify you have the correct credentials"); alert("Login failed. Please verify you have the correct credentials");
this.isLoading = false; this.isLoading = false;
}) })