Skip to content

Commit 39dd8b2

Browse files
committed
Migrate Session to Angular
1 parent 92a6ce0 commit 39dd8b2

File tree

4 files changed

+235
-148
lines changed

4 files changed

+235
-148
lines changed

app-new/src/app/app.module.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { AuthService } from './common/Session';
12
import { ReviewService } from './common/ReviewFactory';
23
import { OrderHistoryService } from './common/OrderHistoryFactory';
34
import { NgModule } from '@angular/core';
@@ -10,7 +11,7 @@ import { UpgradeModule } from '@angular/upgrade/static';
1011
@NgModule({
1112
declarations: [AppComponent],
1213
imports: [BrowserModule, AppRoutingModule, UpgradeModule],
13-
providers: [ReviewService, OrderHistoryService, ],
14+
providers: [AuthService, ReviewService, OrderHistoryService, ],
1415
bootstrap: [AppComponent],
1516
})
1617
export class AppModule {}

app-new/src/app/common/Session.ts

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Import statements
2+
import { Injectable } from '@angular/core';
3+
import { downgradeInjectable } from '@angular/upgrade/static';
4+
import * as angular from 'angular';
5+
6+
// Angular Service Definition
7+
@Injectable({
8+
providedIn: 'root',
9+
})
10+
export class AuthService {
11+
constructor(private http: HttpClient, private session: SessionService, private router: Router, private eventService: EventService) {}
12+
13+
// Uses the session service to see if an authenticated user is currently registered.
14+
isAuthenticated(): boolean {
15+
return !!this.session.user;
16+
}
17+
18+
getLoggedInUser(fromServer?: boolean): Promise<User | null> {
19+
// If an authenticated session exists, we return the user attached to that session with a promise.
20+
// This ensures that we can always interface with this method asynchronously.
21+
// Optionally, if true is given as the fromServer parameter, then this cached value will not be used.
22+
if (this.isAuthenticated() && !fromServer) {
23+
return Promise.resolve(this.session.user);
24+
}
25+
26+
// Make request GET /session.
27+
// If it returns a user, call onSuccessfulLogin with the response.
28+
// If it returns a 401 response, we catch it and instead resolve to null.
29+
const URL = '/session';
30+
const response = this.http
31+
.get(URL)
32+
.toPromise()
33+
.then((res) => this.onSuccessfulLogin(res))
34+
.catch(() => null);
35+
36+
return response;
37+
}
38+
39+
signup(credentials: Credentials): Promise<User> {
40+
const URL = '/signup';
41+
const response = this.http
42+
.post(URL, credentials)
43+
.toPromise()
44+
.then((res) => this.onSuccessfulLogin(res))
45+
.catch(() => {
46+
console.log('I CAUGHT THE POST REQUEST ERROR');
47+
return Promise.reject({ message: 'Invalid signup credentials.' });
48+
});
49+
50+
return response;
51+
}
52+
53+
login(credentials: Credentials): Promise<User> {
54+
const URL = '/login';
55+
const response = this.http
56+
.post(URL, credentials)
57+
.toPromise()
58+
.then((res) => this.onSuccessfulLogin(res))
59+
.catch(() => {
60+
console.log('THIS MESSAGE IS FROM AUTHSERVICE');
61+
return Promise.reject({ message: 'Invalid login credentials.' });
62+
});
63+
64+
return response;
65+
}
66+
67+
logout(): Promise<void> {
68+
const URL = '/logout';
69+
const response = this.http
70+
.get(URL)
71+
.toPromise()
72+
.then(() => {
73+
this.session.destroy();
74+
this.eventService.broadcast(AUTH_EVENTS.logoutSuccess);
75+
});
76+
77+
return response;
78+
}
79+
80+
private onSuccessfulLogin(response: any): User {
81+
const data = response.data;
82+
this.session.create(data.id, data.user);
83+
this.eventService.broadcast(AUTH_EVENTS.loginSuccess);
84+
return data.user;
85+
}
86+
}
87+
88+
// Downgrade Component for AngularJS Compatibility
89+
angular
90+
.module('fsaPreBuilt')
91+
.service('AuthService', downgradeInjectable(AuthService));

browser/js/fsa/fsa-pre-built.js

Lines changed: 0 additions & 147 deletions
This file was deleted.

src/app/Session.spec.js

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
describe("fsaPreBuilt", function () {
2+
beforeEach(module("FullstackGeneratedApp"));
3+
beforeEach(module("$$UpgradeModule"));
4+
5+
var $controller, $rootScope, $scope, $httpBackend, AuthService, Session, AUTH_EVENTS;
6+
7+
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _AuthService_, _Session_, _AUTH_EVENTS_) {
8+
$controller = _$controller_;
9+
$rootScope = _$rootScope_;
10+
$scope = $rootScope.$new();
11+
$httpBackend = _$httpBackend_;
12+
AuthService = _AuthService_;
13+
Session = _Session_;
14+
AUTH_EVENTS = _AUTH_EVENTS_;
15+
}));
16+
17+
describe("AuthService", function () {
18+
describe("isAuthenticated", function () {
19+
it("should return true if user is authenticated", function () {
20+
Session.user = { id: 1, name: "John Doe" };
21+
var result = AuthService.isAuthenticated();
22+
expect(result).toBe(true);
23+
});
24+
25+
it("should return false if user is not authenticated", function () {
26+
Session.user = null;
27+
var result = AuthService.isAuthenticated();
28+
expect(result).toBe(false);
29+
});
30+
});
31+
32+
describe("getLoggedInUser", function () {
33+
it("should return the user attached to the session if user is authenticated and fromServer is not true", function () {
34+
Session.user = { id: 1, name: "John Doe" };
35+
var result;
36+
AuthService.getLoggedInUser().then(function (user) {
37+
result = user;
38+
});
39+
$rootScope.$digest();
40+
expect(result).toEqual(Session.user);
41+
});
42+
43+
it("should make a GET request to /session and call onSuccessfulLogin if user is not authenticated or fromServer is true", function () {
44+
Session.user = null;
45+
$httpBackend.expectGET("/session").respond(200, { id: 1, name: "John Doe" });
46+
var result;
47+
AuthService.getLoggedInUser().then(function (user) {
48+
result = user;
49+
});
50+
$httpBackend.flush();
51+
expect(result).toEqual({ id: 1, name: "John Doe" });
52+
});
53+
54+
it("should catch a 401 response and resolve to null if user is not authenticated", function () {
55+
Session.user = null;
56+
$httpBackend.expectGET("/session").respond(401);
57+
var result;
58+
AuthService.getLoggedInUser().then(function (user) {
59+
result = user;
60+
});
61+
$httpBackend.flush();
62+
expect(result).toBeNull();
63+
});
64+
});
65+
66+
describe("signup", function () {
67+
it("should make a POST request to /signup with the provided credentials and call onSuccessfulLogin if successful", function () {
68+
var credentials = { username: "john", password: "password" };
69+
$httpBackend.expectPOST("/signup", credentials).respond(200, { id: 1, name: "John Doe" });
70+
var result;
71+
AuthService.signup(credentials).then(function (user) {
72+
result = user;
73+
});
74+
$httpBackend.flush();
75+
expect(result).toEqual({ id: 1, name: "John Doe" });
76+
});
77+
78+
it("should reject with an error message if the POST request fails", function () {
79+
var credentials = { username: "john", password: "password" };
80+
$httpBackend.expectPOST("/signup", credentials).respond(500);
81+
var result;
82+
AuthService.signup(credentials).catch(function (error) {
83+
result = error;
84+
});
85+
$httpBackend.flush();
86+
expect(result).toEqual({ message: "Invalid signup credentials." });
87+
});
88+
});
89+
90+
describe("login", function () {
91+
it("should make a POST request to /login with the provided credentials and call onSuccessfulLogin if successful", function () {
92+
var credentials = { username: "john", password: "password" };
93+
$httpBackend.expectPOST("/login", credentials).respond(200, { id: 1, name: "John Doe" });
94+
var result;
95+
AuthService.login(credentials).then(function (user) {
96+
result = user;
97+
});
98+
$httpBackend.flush();
99+
expect(result).toEqual({ id: 1, name: "John Doe" });
100+
});
101+
102+
it("should reject with an error message if the POST request fails", function () {
103+
var credentials = { username: "john", password: "password" };
104+
$httpBackend.expectPOST("/login", credentials).respond(500);
105+
var result;
106+
AuthService.login(credentials).catch(function (error) {
107+
result = error;
108+
});
109+
$httpBackend.flush();
110+
expect(result).toEqual({ message: "Invalid login credentials." });
111+
});
112+
});
113+
114+
describe("logout", function () {
115+
it("should make a GET request to /logout and destroy the session if successful", function () {
116+
Session.user = { id: 1, name: "John Doe" };
117+
$httpBackend.expectGET("/logout").respond(200);
118+
AuthService.logout();
119+
$httpBackend.flush();
120+
expect(Session.user).toBeNull();
121+
});
122+
});
123+
});
124+
125+
describe("Session", function () {
126+
describe("create", function () {
127+
it("should set the sessionId and user properties", function () {
128+
Session.create(1, { id: 1, name: "John Doe" });
129+
expect(Session.id).toBe(1);
130+
expect(Session.user).toEqual({ id: 1, name: "John Doe" });
131+
});
132+
});
133+
134+
describe("destroy", function () {
135+
it("should set the sessionId and user properties to null", function () {
136+
Session.destroy();
137+
expect(Session.id).toBeNull();
138+
expect(Session.user).toBeNull();
139+
});
140+
});
141+
});
142+
});

0 commit comments

Comments
 (0)